반응형

빌드하는디 컴파일에러나서 보니까 dto에....

cannot find symbol

getter setter를 못찾는것 같다 -> lombok에 문제있다

 

찾아보니

gradle 버전 5 이상에서 lombok 사용시 컴파일에 문제가 있나봄.

https://intellij-support.jetbrains.com/hc/en-us/community/posts/360003400520-Intellij-Idea-Lombok-Gradle-5-broken-build

 

개발환경

Gradle 6.8

Intellij 2021.1.3

Java 11.0.11

 

의존성 아래처럼 수정하니 빌드 잘 된다.

compileOnly("org.projectlombok:lombok:1.18.10")
annotationProcessor("org.projectlombok:lombok:1.18.10")
반응형
반응형

XML 문서

<!--XML 문서 내용 -->
<response>
	<header>
		<resultCode>00</resultCode>
			<resultMsg>NORMAL_CODE</resultMsg>
	</header>
	<body>
		<items>
			<item>
				<pm25Grade1h>2</pm25Grade1h>
				<pm10Value24>55</pm10Value24>
				<so2Value>0.002</so2Value>
			</item>
			<item>
				<pm25Grade1h>2</pm25Grade1h>
				<pm10Value24>57</pm10Value24>
				<so2Value>0.002</so2Value>
			</item>
		</items>
<numOfRows>10</numOfRows>
<pageNo>1</pageNo>
<totalCount>23</totalCount>
</body>
</response>

 

  • DocumentBuilderFactor  : 어플리케이션으로 XML 문서로부터 DOM 객체 트리를 생성하는 파서를 취득할 수 있는 팩토리 API를 정의합니다.
  • DocumentBuilder  : 현재 설정되어 있는 파라미터를 사용해  새로운 DocumentBuilder 인스턴스를 작성합니다.
    이 클래스의 인스턴스를 취득하면, 다양한 입력 소스로부터 XML 문서를 구문 분석 할 수 있습니다. 이러한 입력 소스에는 InputStream, File, URL 및 SAX InputSource가 있습니다.
  • Document  : HTML 문서 또는 XML 문서 전체를 나타냅니다.

 

XML 파싱 및 태그의 값 가져오기

//XML 요청 url
String url = "http://api.adfafadsfasdfadf";

//XML 파싱
DocumentBuilderFactory dbFactoty = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactoty.newDocumentBuilder();
Document doc = dBuilder.parse(url);

//item이라는 태그의 element들 가져오기
NodeList nList = doc.getElementsByTagName("item");
Node nNode = nList.item(0);

if (nNode.getNodeType() == Node.ELEMENT_NODE) {
      Element eElement = (Element) nNode;
      getTagValue("so2Value", eElement);
}

 

XML 파싱 및 내용 출력하기

//XML문서 요청 url
String url = "http://api.adfafadsfasdfadf";

//XML 파싱
DocumentBuilderFactory dbFactoty = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactoty.newDocumentBuilder();
Document doc = dBuilder.parse(url);

//XML을 Strig으로 출력
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
Writer out = new StringWriter();
tf.transform(new DOMSource(doc), new StreamResult(out));
System.out.println(out.toString());
반응형
반응형

1. binary to image

convert binary source to image

<!--HTML Source-->
<img id="imgPreview" src="">
//javascript source
let binarySrc = 'AB4AA…6HNrfUH/cbXQYCRHJ/v8HL9i0B/qBtAMAAAAASUVORK5CYII';
document.getElementById("imgPreview").src = "data:image/png;base64," + binarySrc;

 

2. binary image to file 

convert image with binary source to file

<!--image html source -->
<img id="imgPreview" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB4AAAAQ3CAIAAACW5+TB">
imageToFile(document.getElementById("imgPreview").src);

function imageToFile(imgsrc){
//atob : base64로 인코딩된 src 디코딩
let bstr = atob(imgsrc.split(',')[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);

while(n--){
    u8arr[n] = bstr.charCodeAt(n);
}

let file = new File([u8arr],'imgFile.png',{type:'mime'});
console.log(file);
console.log(file.name);
//javascript 보안상 file을 input type file value에 할당할 수는 없음.
}

 

3. file to image (for previewing image )

convert file to image

shows the selected file as a preview

<!--HTML Source-->
<input type="file" id="file">
<img id="imgPreview" src="">
//파일 변경 시 미리보기 변경
$('#file').change(function(){
    readImage();
})


function readImage() {
    if(document.getElementById('file').files[0]){
        const reader = new FileReader();
        reader.onload = e => {
             const previewImage = document.getElementById('imgPreview')
             imgPreview.src = e.target.result
         }
        reader.readAsDataURL(document.getElementById('file').files[0])
}
반응형
반응형

파일 및 디렉터리 삭제 방법

디렉터리 안의 파일을 모두 제거해야 디렉터리가 삭제되므로 파일먼저 삭제.

String datePath = "\\src\\main\\resources\\static\\assets\\data\\data1";
File dateFolder = new File(datePath);

File dir[] = dateFolder.listFiles();

 try {
		for (int i = 0; i < dir.length; i++) {
			dir[i].delete(); //파일 삭제
		}

		dateFolder.delete(); //폴더 삭제


	}catch (Exception e){
		e.printStackTrace();
	}

Exception 에러도 없이 삭제가 안 되는 파일이 있었다.

이유 : 해당 파일을 어딘가에서 붙잡고 있음.

delete 이전에 파일을 읽어오는 소스가 있는데 IO stream을 안 닫아 줬기 때문.

///수정 전 
/////Scanner를 닫아야 하는데 안 닫았음. 

try{
	Scanner commentScan = new Scanner(new File(dir[i] + "\\comment"));
	mtDto.setComment(commentScan.nextLine());
}catch(Exception e){

}

try catch를 사용하는 경우 try에서도 닫고 catch에서도 닫아줘야함...

 

결론 : try-with-resource를 사용하면 예외가 발생했든 안 했든간에 사용했던 리소스 객체를 자동으로 닫아주므로

try with resource를 사용하자.

///수정 후

try ( Scanner commentScan = new Scanner(new File(dir[i] + "\\comment")); )
{
	mtDto.setComment(commentScan.nextLine());
}catch(Exception e){

}
반응형
반응형

1. System.getProperty("user.dir")

현재 작업 path

String cwd = System.getProperty("user.dir");

System.out.println("현재 경로 : "+cwd);
//현재 실행 프로젝트 경로가 출력됨
//현재 경로 : D:\myProject

 

2. listFiles()

특정 파일/디렉터리 아래의 파일들 full path

File dirs = new File(cwd + "\\src\\main\\resources\\static\\assets\\data");

File dir[] = dirs.listFiles();

for(int i=0;i<dir.length;i++){
    System.out.println("지정한 경로 아래의 파일 경로 : " + dir[i]);
}

//디렉터리 아래에 있는 파일or디렉터리들의 full path가 출력됨.
//지정한 경로 아래의 파일 경로 : D:\myProject\src\main\resources\static\assets\data\file1
//지정한 경로 아래의 파일 경로 : D:\myProject\src\main\resources\static\assets\data\fil2
//지정한 경로 아래의 파일 경로 : D:\myProject\src\main\resources\static\assets\data\folder1

 

3. list()

특정 파일/디렉터리 아래의 파일들 이름 출력

File dirs = new File(cwd + "\\src\\main\\resources\\static\\assets\\data");

String dirName[] = dirs.list();

for(int i=0;i<dirName.length;i++){
    System.out.println("지정한 경로 아래의 파일 : " + dirName[i]);
}

//디렉터리 아래에 있는 파일or디렉터리들의 이름만 출려됨
//지정한 경로 아래의 파일 : file1
//지정한 경로 아래의 파일 : file2
//지정한 경로 아래의 파일 : folder1
반응형
반응형

FormData 및 <form> 으로 Javascript 데이터를 전송하기


submit 버튼으로 보내는 경우

 

1) HTML 소스

파일이 있는 경우 enctype="multipart/form-data" 로 지정해주어야 하며

파일이 없어도 상관없다.

* enctype : method가 post인 경우 enctype데이터의 MIME 타입을 말함.

<form id="testForm" action="/test" method="post" enctype="multipart/form-data">
  <input type="text" name="aa" value="11">
  <input type="text" name="bb" value="22">
  <input type="file" name="cc">
  <input type="submit">
</form>

 

2) 데이터 수신부 JAVA Controller 소스

파일이 있는 경우 파라미터 타입을 MultipartHttpServletRequest 타입으로 받고

파일이 없는 경우 HttpServletRequest 로 받는다.

@RequestMapping(value="/test", method = RequestMethod.POST)
@ResponseBody
public void test(MultipartHttpServletRequest req) throws Exception{
      String test = req.getParameter("aa");
      MultipartFile file = req.getFile("cc");
      System.out.println(test);
      System.out.println(file);
}

 

 

 
반응형

 

 

버튼에 함수 걸어서 fetch로 보내는 경우

 

1) HTML 소스

form 안에 타입 지정 안 하고 버튼을 만들면 기본값인 submit이 되어버려서 함수 거는 button은 form 밖에 만들었다.

<form id="testForm">
  <input type="text" name="aa" value="11">
  <input type="text" name="bb" value="22">
  <input type="file" name="cc">
</form>
<button onclick="submit()">완료</button>




<script>
//fetch에서 Content-Type 은 지정하지 않는다. 
function submit(){
	let myform = document.getElementById('testForm');
	formData = new FormData(myform);
	fetch('http://localhost:8001/test',{
		method:'POST',
		body : myform
	});
}
</script>

 

2) 데이터 수신부 Controller JAVA 소스 

//JAVA Controller source
//MultipartHttpServletRequest 타입으로 받는다.
@RequestMapping(value="/test", method = RequestMethod.POST)
@ResponseBody
public void test(MultipartHttpServletRequest req) throws Exception{
      String test = req.getParameter("aa");
      MultipartFile file = req.getFile("cc");
      System.out.println(test);
      System.out.println(file);
}

 

 

 

FormData 객체를 직접 만들어서 보내는 경우 

1) HTML 소스

<input type="text" id="aa" value="11">
<input type="text" id="bb" value="22">
<input type="file" id="cc">
<a onclick="submit1()">완료</a>

<script>
function submit1(){
	let formData = new FormData();
	formData.append('aa',document.getElementById('aa').value);
	formData.append('bb',document.getElementById('bb').value);
	formData.append('pic',document.getElementById('cc').files[0]);

	fetch('http://localhost:8001/test',{
		method:'POST',
		body : formData
	});

}
</script>

 

2) 데이터 수신부 Controller JAVA 소스 

//JAVA Controller source
@RequestMapping(value="/test", method = RequestMethod.POST)
@ResponseBody
public void test(MultipartHttpServletRequest req) throws Exception{
	String test = req.getParameter("aa");
	MultipartFile file = req.getFile("cc");
}

 

 

 

반응형
반응형

 

사색에 대한 고찰.

어떻게 생각하고 어떻게 살아가면 좋을까에 대한 생각에 인문학을 곁들였다. 

요새 유행하는 '~해도 괜찮아' 같은 부류의 책인 줄 알았으나

그보다는 조금 더 깊이가 있고 작가가 얼마나 많은 사색을 하였는지가 엿보인다. (굉장한 자부심이 느껴진다 ㅋㅋㅋ)

추상적인 주제를 다루기 때문에 뜬구름잡는 소리처럼 느껴질 수 있지만 그렇기 때문에 더 생각을 하게 만드는 것 같다.

 

삶의 방향을 정해주진 않아도 방향을 정하기 위한 생각을 정리하는데에 도움이 되는 것 같다.

'어떤 자세로 일상에 임해야 할까'를 생각하게 해주었던 점이 좋았다.

근데 뒤돌아서면 까먹게 된다....ㅋㅋㅋ

작가가 자신의 '사색'과 '독서'의 뽕에 너무 취해있는 것..이 보였다. 나쁘진 않았지만 좀 피식했다. 

 


처음 만나는 사람이 가진 내면의 강도를 알 수 있는 방법이 하나 있다.
바로 그가 무엇을 경멸하는지 관찰하는 것이다.
사람은 누구나 자신이 추구하는 일상과 철학을 잘 말해주지 않는다. 자신도 잘 모르고 있기 때문이다.
상대가 무엇을 경멸하는지를 보면 우리는 그가 어떤 일상을 보내고 있으며, 어떤 철학으로 점철된 미래를 살게 될지 짐작할 수 있다.

 

일상에서의 작은 성취가 중요하다.
누구나 처음과 시작이 있고, 그 때 자신이 선택한 방법에 따라 다른 결과를 맞이하게 된다. 
대가의 조언을 그대로 따르는 것도 좋지만 스스로에게 자신감을 부여할 수 있도록 작은 성취를 쌓는 시스템을 견고하게 만들어야 한다.

 

언제나 모든 변화는 그렇게 되겠다는 자신의 의지에서 시작한다.
지금 당신에게 필요한 것은 자신에게 내릴 한 문장의 명령이다. 자신에게 새로운 시작을 허락하라.

 

함부로 멘토를 만들지 말라.
쉽게 누군가를 멘토로 섬기지도 말라. 당신의 가장 진실한 멘토는 당신이 어제 보낸 시간이다. 

 

반응형

'' 카테고리의 다른 글

인간의 법정 - 조광희  (0) 2022.08.27
완전한 행복 - 정유정  (0) 2022.05.07
포르노랜드 - 게일 다인스  (0) 2021.10.14
네 눈동자 안의 지옥 - 캐서린 조  (0) 2021.08.21
체공녀 강주룡 - 박서련  (0) 2021.07.13
반응형

invalid host/bind variable name

 

쿼리에 콤마 빠짐

반응형
반응형

spring boot + thymeleaf 구조에서 resources/static 밑의 js 파일들을 사용하려고 하는데....

경로가 잘못돼서 ... 자꾸 에러가.. 났다...

Failed to load resource: the server responded with a status of 404 ()

GET http://localhost:8888/static/assets/js/mountain.js net::ERR_ABORTED 404

 

 

thymeleaf 에서의 리소스의 디폴트 경로는 /resources/static/ 이므로

static 밑의 경로부터 적어주면 잘 됨!

<script src="/assets/js/mountain.js"></script>
<script src="/js/index.js"></script>

 


관련 내용 참고

 

[SpringBoot] 정적자원관리(Resource handle) - Jongmin's Blog

정적 자원(Static Resource) 정적자원이란 html, css, image, javascript와 같이 컴파일이 필요없는 파일들을 말합니다. 스프링 부트에서 Web MVC 설정을 담당하는 WebMvcAutoConfiguration 클래스는 기본 설정으로 웹

JongMinLee0.github.io

 

반응형
반응형

밀크티에 물 왕창 섞은 맛

맛없어
470ml나 먹어야됨

반응형

+ Recent posts