반응형

작성일자 : 2021.03.06

환경 : Spring Boot 2.1.6, Gradle

 

 

1. 의존성 추가

 

build.gradle

implementation 'org.apache.tomcat.embed:tomcat-embed-jasper'

 

 

2. jsp 설정 추가

 

application.properties

spring.mvc.view.prifix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

 

 

3. Controller 생성

 

JspController.java

@Controller
public class JspController {
    @GetMapping("/index")
    public String getIndex(){
        return "index";
    }
}

 

 

4. jsp 파일 생성

 

생성 경로 : src/main/webapp/WEB-INF/jsp/

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <div>JSP</div>
    </body>
</html>




5. 확인

 

 

반응형

'Java > 예제코드' 카테고리의 다른 글

[java] 소수점 표현 예제  (0) 2021.02.27
[Spring] 파일 업/다운로드 예제 코드  (0) 2021.02.20
반응형
System.out.println(a);                              
// 결과 : 0.987654321

System.out.println(Math.ceil(a * 100) / 100.0);     
// 결과 : 0.99

System.out.println(Math.round(a * 100) / 100.0);    
// 결과 : 0.

System.out.println(Math.floor(a * 100) / 100.0);    
// 결과 : 0.98

System.out.println(String.format("%.3f", a));       
// 결과 : 0.988

 

반응형

'Java > 예제코드' 카테고리의 다른 글

[Spring] JSP 설정  (0) 2021.03.06
[Spring] 파일 업/다운로드 예제 코드  (0) 2021.02.20
반응형

작성일자 : 2021.02.20

환경 : 자바8, Spring Boot 2, Chrome

1. 파일 업로드

 

HTML Code

...
  <form method="post" action="/uploadFile" enctype="multipart/form-data">
      <input type="file" name="file">
      <input type="submit">
  </form>
...

 

* submit 대신 Javascript 를 활용할 경우

 

...
	<form method="post" action="/uploadFile" enctype="multipart/form-data">
		<input type="file" name="file">
	</form>
	<button onclick="sendFile()">button</button>
...

<script>
    const sendFile = () => {
        const formElement = document.querySelector("form");
        const request = new XMLHttpRequest();
        request.open("POST", "/uploadFile");
        request.send(new FormData(formElement));
    }
</script>

 

 

Java code

@PostMapping("/uploadFile")
public void uploadFile(@RequestParam("file") MultipartFile file){
    // 파일 기본 정보
    System.out.println("file name : " + file.getOriginalFilename());
    System.out.println("file size : " + file.getSize());

    try(
    	// 프로젝트 폴더에 temp.jpg 이름으로 파일 생성
        FileOutputStream fos = new FileOutputStream("./temp.jpg"); 
        InputStream is = file.getInputStream()
    ){
        int readCount;
        byte[] buffer = new byte[1024];
        
        // 데이터 쓰기
        while((readCount = is.read(buffer)) != -1){
            fos.write(buffer, 0, readCount);
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}

 

 

2. 파일 다운로드

Java code

@GetMapping("/downloadFile")
public void downloadFile(HttpServletResponse response) {

	// 프로젝트 폴더의 temp.jpg 파일 로드
	String fileName = "temp.jpg";
	File file = new File("./" + fileName);

	// 클라이언트에서 아래의 이름으로 파일이 받아진다.
	String newFileName = "newTemp.jpg";

    try (
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        OutputStream out = response.getOutputStream()
    ){
    	// 응답이 파일 타입이라는 것을 명시
        response.addHeader("Content-Disposition", "attachment;filename=\""+newFileName+"\"");
        // 응답 크기 명시
        response.setContentLength((int)file.length());

        int read = 0;
        
        // 실제 데이터 전송
        // OutputStream 의 Deafult 버퍼 사이즈는 8192 Byte
        // 이 루프를 8000 번 정도 돌때마다 약 8KB 정도의 데이터가 전송 
        while((read = bis.read()) != -1) {
            out.write(read);
        }
        
    } catch(IOException e) {
        e.printStackTrace();
    }
}

 

---

 

* HTTP MultiPart 로 파일 전송시 formData 에서 확인이 불가능, 단 파일을 null 로 전달하면 확인 가능 (크롬 기준)

 

* form 에서 지정하는 enctype 속성은 아래 세가지의 값으로 지정될 수 있다.

 

1. application/x-www-form-urlencoded

디폴트 값. 폼데이터는 서버로 전송되기 전에 URL-Encode 됨

 

2. multipart/form-data

파일이나 이미지를 서버로 전송할 경우

 

3. text/plain

인코딩을 하지 않은 문자 상태로 전송

 

반응형

'Java > 예제코드' 카테고리의 다른 글

[Spring] JSP 설정  (0) 2021.03.06
[java] 소수점 표현 예제  (0) 2021.02.27

+ Recent posts