커리큘럼(12-30/변경)
01. Java
02. git
03. Database
04. Jsp [Server]
05. HTML,CSS
07. JS
06. 미니프로젝트-2W
08. SpringFramework , SrpingBoot (v)
09. React JS [Front-end]
10. 중간프로젝트 (1M)
11. Linux 명령어
12. AWS 클라우드
13. DevOps - Docker
14. App - Android
15. 최종프로젝트 (1M)
스프링 부트
파일조회
// 이미지 응답기능
// 클라이언트에서 요청은 display?파일패스=값&uuid=값&파일명=값
@GetMapping("/display")
public ResponseEntity<byte[]> display(@RequestParam("filepath")String filePath,
@RequestParam("uuid") String uuid,
@RequestParam("filename") String filename) {
String path= uploadPath+"/"+filePath+"/"+uuid+"_"+filename;
byte[] fileData = null; // 데이터정보
HttpHeaders header = new HttpHeaders(); // 헤더정보
try {
File file = new File(path);
fileData = FileCopyUtils.copyToByteArray(file); // 파일을 읽어서 바이트로 변환
header.add("Content-type", Files.probeContentType(file.toPath()));
}catch (Exception e){
e.printStackTrace();
}
return new ResponseEntity<>(fileData,header, HttpStatus.OK);
}
파일다운로드
@GetMapping("/download")
public ResponseEntity<byte[]> download(@RequestParam("filepath")String filePath,
@RequestParam("uuid") String uuid,
@RequestParam("filename") String filename) {
String path= uploadPath+"/"+filePath+"/"+uuid+"_"+filename;
byte[] fileData = null; // 데이터정보
HttpHeaders header = new HttpHeaders(); // 헤더정보
try {
File file = new File(path);
fileData = FileCopyUtils.copyToByteArray(file); // 파일을 읽어서 바이트로 변환
header.add("Content-Disposition", "attachment; filename="+filename);
}catch (Exception e){
e.printStackTrace();
}
return new ResponseEntity<>(fileData,header, HttpStatus.OK);
}
세션 & 인터셉터
# 인터셉터 클래스
// 1. 핸들러 인터셉터 상속
public class UserAuthHandler implements HandlerInterceptor {
// 2.오버라이딩
// pre - 컨트롤러 진입전
// post - 컨트롤러 실행이후
//after 컴플리션 - 리졸버 뷰까지 실행된 이후에 동작
//3. 스프링 설정파일에 인터셉터를 등록
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 리턴에 true가 들어가면 controller를 실행함, false가 들어가면 컨트롤러 실행 안함
System.out.println("컨트롤러 실행전 인터셉터 동작");
// 세션이 존재여부를 확인해서 세션이 없으면 돌려보냄
// 리퀘스트에서 세션얻음
HttpSession session = request.getSession();
String username = (String)session.getAttribute("username"); // 로그인 만든사람이 지정한 값
if(username == null){
// 인증되지않음
response.sendRedirect("/user/login"); // 로그인페이지로 리다이렉트
return false; // 컨트롤러를 실행하지 않음
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("컨트롤러 실행 후 인터셉터 동작");
}
}
# 스프링 설정파일
@Configuration
public class WebConfig implements WebMvcConfigurer {
//빈으로 생성
@Bean
public UserAuthHandler userAUthHandler() {
return new UserAuthHandler();
}
//핸들러적용
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(userAUthHandler())
.addPathPatterns("/user/*") //패스에 포함
.excludePathPatterns("/user/login") //패스에서 제외
.excludePathPatterns("/user/로그인시도"); //패스에서 제외
//여러 핸들러를 사용하려면 빈을 생성하고 각기 다르게 등록하면 된다
}
}