ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 스프링부트+JPA - 인스타그램 클론 코딩 02-1 - 프로젝트 기본 세팅 및 기본 개념 이해
    스프링/스프링부트+JPA - 인스타 2021. 9. 17. 15:20

    이지업 최주호 강사님 강의 참조

     

     

    01 HTTP 요청을 JSON으로 응답하기

    • Controller 세팅
    @RestController
    public class HttpResponseJsonController {
    	
    	@GetMapping("/resp/json")
    	public String respJson() {
    		return "{\"username\":\"cos\"}";
    	}
    }

     

    • 하지만 보통 JSON은 이렇게 응답하지 않는다.
    	@GetMapping("/resp/json/object")
    	public User respJsonObject() {
    		User user = new User();
    		user.setUsername("홍길동");
    		return user;
    	}

    • 혹은 아래와 같이 오브젝트로 말고 계속해서 String으로 할 수는 있다. 하지만 미친짓인걸 직접 코딩 해보면 안다.
    @GetMapping("/resp/json/object")
    public User respJsonObject() {
          User user = new User();
          user.setUsername("홍길동");
          String data = "{\"username\":\""+user.getUsername()+"\"}";
          return data
    • Object를 리턴해도 JSON이 튀어나온다. 왜? → MessageConvert 가 자동으로 JO를 JSON으로 변경해서 통신을 해서 보내주기 때문
    • 또한 @RestController를 달고 있기 때문에 데이터 및 문자열이 return이 된다. 

     

     

     

     

    02 HTML로 응답 해보기

    • .text/.mustache/.jsp 로 응답을 받기
    • 기본 경로는 resources/static 아래로 정해져 있다. (YML로 경로 설정 가능)
    • mustache/jsp 는 템플릿 엔진으로 불리며 HTML파일 그 위에 JAVA코드를 쓸 수 있게 하는 용도
    • 파일을 응답하니 @Controller 사용

     

     

    • .txt 응답

    → 컨트롤러

    @Controller
    public class HttpRespController {
    	
    	@GetMapping("/txt")
    	public String txt() {
    		return "a.txt";
    	}
    }

     

     

     

    • .mustache 응답

    → 메이븐 추가 / 업데이트

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mustache -->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mustache</artifactId>
    </dependency>

    → 컨트롤러

    	@GetMapping("/mus")
    	public String mus() {
    		return "b";
    	}

    • 템플릿 엔진은 templates 폴더에서만 작동 한다. 또한 .mustache는 스프링 부트가 지원하는 확장자 이기 때문에 템플릿 폴더안에 넣어놓으면 확장자명도 생략 가능 하다

     

     

    • .jsp 응답
    • .jsp는 스프링부트에서 지원하는 템플릿이 아니기 때문에 경로가 다르다!

    → 메이븐 추가 / 업데이트 그리고 두개의 템플릿엔진은 공존 못함 muscahe 주석 처리

    <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->
    <dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jasper</artifactId>
    <version>9.0.41</version>
    </dependency>

    → 스프링에서 jsp파일을 찾을 수 있도록 YML세팅 (ViewResolver 세팅이라고도 함)

    spring:
      mvc:
        view:
          prefix: /WEB-INF/views/
          suffix: .jsp

    → 컨트롤러

    	@GetMapping("/jsp")
    	public String jsp() {
    		return "c";
    	}

     

     

     

     

    03 JSP파일에 자바코드 입혀보기

    • 컨트롤러
    @Controller
    public class JavaToJspController {
    
    	@GetMapping("/jsp/java")
    	public String jspTojava() {
    		return "d";
    	}
    }
    • d.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <h1>This is d.</h1>
    <%
    int num = 10;
    %>
    <h3>num의 값 = <%=num %></h3>
    </body>
    </html>
    • <% %> 태그를 써서 자바 코드를 입히고 그대로 내장톰켓에 의해 파싱되서 출력 되는 것. 즉 동적인 파일을 출력 할 수 있다

    굿!

     

     

    • 다른 예제

    → 컨트롤러

    	@GetMapping("/jsp/java/model")
    	public String jspTojavatomodel(Model model) {
    		User user = new User();
    		user.setUsername("KIM");
    		model.addAttribute("username", user.getUsername());
    		return "e";
    	}

    → e.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <h1>This is e.</h1>
    <h3>${username}</h3>
    </body>
    </html>

    • 데이터를 찾을때는 반드시 찾는 데이터의 변수명과 동일해야 불러온다!
    • Model 이라는 스트링부트의 기능(해쉬맵 자료구조)을 이용하면 파라미터로 model을 선언하고 model이 들고 있는 .addattribute를 통해 키와 값을 넣고 이값을 return 을 통해 원하는 파일로 보낼 수 있다
    • 그 값을 불러오는것은 '${}'

     

     

     

     

     

    04 HTTP 요청 재분배 하기 - REDIRECTION

    • HTTP 상태코드 300번대로 다른 주소로 요청이 왔지만 결국 결과가 같은 요청이라면 함수를 비슷한거를 만들지 말고 하나의 함수를 재사용해서 REDIECTION처리를 하면 되는 형태

     

    • 코드로 보자 - Controller
    @Controller
    public class HttpRedirectionController {
    	
    	@GetMapping("/home")
    	public String home() {
    		//1만줄
    		return "home";
    	}
    	
    	@GetMapping("/away")
    	public String away() {
    		//다른코드
    		//반복되는 1만줄
    		return "redirect:/home";
    	}
    	
    }
    • home.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <h1>This is home</h1>
    </body>
    </html>

    • 요청을 away로 해도 redirection을 통해 home으로 보내졌고 300번대 상태코드를 보여준다.
      302 Found 코드로 요청한 리소스의 URI가 일시적으로 변경되었음을 의미하고 새롭게 변경된 URL를 요청한 상태
    • 다시 말하면 return 을 redirect형식이아닌 포워드 형태(페이지 이동)로 하면 인서트 이후에 데이터 저장 한번 포워드로 페이지 이동시키면서 또 한번 중복 요청이 발생하게 되기때문에 이를 방지 하기 위함
Designed by Tistory.