국비학원_62일차(Spring-MVC)

써니·2022년 10월 20일
0

spring

목록 보기
4/23

🌞Spring MVC

💻MVC 환경설정

Legacy 프로젝트 생성

context 이름 설정(세번째 자리)

프로젝트 생성 후 자동으로 controller, view 생성




🌊Spring MVC 흐름


DispatcherServlet : pre-Controller


❗ ViewResovler

  1. "/"를 HandlerMapping을 하고 Controller에 처리 요청하면 Controller에서 처리 결과를 보여줄 view의 논리 이름 return
@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		System.out.println("HomeController home start...");
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}

  1. ViewResolver 호출 하기 위해 web-xml 에서 파라미터 값인 servlet-context.xml을 찾아감
    <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

  1. servlet-context.xml 에서 컨트롤러를 빈으로 등록 하면 선행자+후미자를 뷰의 논리 이름을 합침
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
// <beans:property name="prefix" value="/WEB-INF/views/" />
// <beans:property name="suffix" value=".jsp" />
//	/WEB-INF/views/ + home + .jsp -> /WEB-INF/views/home.jsp

JSP / Spring MVC Controller 차이

  • DispatcherServlet
  • ViewResolver
  • Validator



🔻och07_MVC01

[com.oracle.mvc01]

  • HomeController.java

request -> model

package com.oracle.mvc01;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		System.out.println("HomeController home start...");
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
}

❌오류
http://localhost:8181/mvc01/WEB-INF/classes/com/oracle/mvc01/HomeController.java

  • @RequestMapping(value = "/", method = RequestMethod.GET) -> "/" 지정 안함

⭕삭제 후 결과
http://localhost:8181/mvc01/

  • mvc01 - > context



⚡한글깨짐 처리

출력 페이지 내 한글깨짐

✍해결방법

  • pom.xml

버전 올리기 -> 자동완성❌


  • web.xml

한글처리 주석 줄 추가

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>
	
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<!--  한글처리       -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

👍해결





  • HomeController.java ( member 추가 )
    com.oracle.mvc01.HomeController -> logger
package com.oracle.mvc01;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		System.out.println("HomeController home start...");
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
		@RequestMapping(value = "/member", method = RequestMethod.GET)
		public String member(Model model) {
			System.out.println("HomeController member Start...");
			
			model.addAttribute("serverTime", model);
			
			return "home";
		}

	
}
  • "/member" 추가
  • 👇결과

    INFO-서버메세지

  • spring -> root-context.xml
    DI 설정

  • web.xml

파라미터 값
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>
	
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

  • servlet-context.xml
  • prefix : 선행자
  • suffix : 후미자
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="com.oracle.mvc01" />
	
	
	
</beans:beans>

  • home.jsp
    meta=utf-8이 안되어 있기 때문에 오류 메시지 뜨면 save as UTF-8 클릭
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> -> jstl lib 포함됨
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
	<title>Home</title>
</head>
<body>
<h1>
	Hello world!  
</h1>

<P>  The time on the server is ${serverTime}. </P>
<p> <img alt="반짝" src="resources/img/hot.gif">
</body>
</html>

이미지 추가


Controller / Service

만든 패키지 하위로 패키지를 만들기



🔻och07_MVC02

[com.oracle.mvc02]

  • HomeController.java( 테스트용 )

메소드 지정 안하면 default-GET

package com.oracle.mvc02;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@RequestMapping(value = "/board/view")
	public String view() {
		logger.info("Welcome home! {} start...", "/board/view");
		return "board/view";
	}
	
}

📂board

  • view.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>view.jsp</h1>
</body>
</html>




  • HomeController.java
	@RequestMapping("/board/content")
	public String content(Model model) {
		System.out.println("HomeController content start....");
		model.addAttribute("id", 365);

		return "/board/content";
	}

📂board

  • content.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>content.jsp</h1>
	당신의 Id는 ${id}
</body>
</html>



ModelAndView

목적 : parameter와 view를 한번에 처리
반환값 : ModelAndView 객체를 반환

Model과 ModelAndView 차이점

  1. model
  • Model은 파라미터 방식으로 메소드에 (Model model) 파라미터를 넣어주고 String형태로 리턴
  • Model은 값을 넣을 때 addAttribute()를 사용

  1. ModelAndView
  • MoelAndView는 말그대로 Model과 View를 합쳐놓은 것으로,값을 넣을때 addObject()를 사용
  • setViewName()으로 보낼 곳 View를 세팅


✍사용방법

  1. ModelAndView 객체를 선언 및 생성
    -> ModelAndView mav = new ModelAndView();
  2. view의 이름 지정
    -> mav.setViewName("뷰의 경로")
  3. 데이터를 보낼 때는 addObject() 메소드 사용
    -> mav.addObject("변수이름", "데이터값");
  4. ModelAndView 객체 반환
    -> return mav;

👉적용하기

  • HomeController.java
	@RequestMapping("/board/reply")
	public ModelAndView reply() {
		System.out.println("HomeController reply start...");
		// 목적 : parameter와 view를 한번에 처리
		ModelAndView mav =  new ModelAndView();
		mav.addObject("id", 50);
		mav.setViewName("board/reply");
		
		return mav;
	}

📂board

  • reply.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>reply.jsp</h1>
	my id : ${id}
</body>
</html>




🔻och07_MVC03

[com.oracle.mvc03]

🤔파라미터 선택

데이터가 없을 때 null 값으로 처리

  • HomeController.java

HttpServletRequest
만약 회원 정보를 컨트롤러에 보냈을 때 객체 안에 모든 데이터가 들어가게 됨

  • 원하는 데이터를 꺼낼 때는 getParameter()를 이용함(String 타입)
    참고
package com.oracle.mvc03;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	// Parameter 선택
	@RequestMapping("/board/confirmId")
	public String confirmId( HttpServletRequest httpServletRequest, Model model) {
		logger.info("confirmId start...");
		String id = httpServletRequest.getParameter("id");
		String pw = httpServletRequest.getParameter("pw");
		System.out.println("board/confirmId id->"+id);
		System.out.println("board/confirmId pw->"+pw);
		model.addAttribute("id",id);
		model.addAttribute("pw", pw);
		
		return "board/confirmId";
	}
	
}

📂board

  • confirmId.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>confirmId.jsp</h1>
	ID : ${id} <br>
	PW : ${pw}
</body>
</html>

주소에서 직접 값을 넣음


😡파라미터 강제

파라미터를 강제로 넣어야한다고 선언하고 싶을 때

  • HomeController.java
// Parameter Force
@RequestMapping("board/checkId")
public String checkId(@RequestParam("id") String idd, @RequestParam("pw") int passwd, Model model) {
	logger.info("checkId start...");
	System.out.println("board/checkId idd->"+idd);
	System.out.println("board/checkId passwd->"+passwd);
	model.addAttribute("identify", idd);
	model.addAttribute("password", passwd);
	return "board/checkId";
	}

📂board

  • checkId.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>checkId</h1>
	ID : ${identify} <p>
	PW : ${password}
</body>
</html>

파라미터가 필수일 때 오류 발생

파라미터를 강제로 넣었을 때 결과




[com.oracle.mvc03.dto]

  • Member.java
package com.oracle.mvc03.dto;

public class Member {
	private String name;
	private String id;
	private String pw;
	private String email;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPw() {
		return pw;
	}
	public void setPw(String pw) {
		this.pw = pw;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
    
    @Override
	public String toString() {
		String returnStr = "[" + "이름 :" + this.name + " ,id :" + this.id + "]";
		return returnStr;
	}
}

  • HomeController.java
// Parameter Force
@RequestMapping("member/join")
	public String member(@RequestParam("name") String name, @RequestParam("id") String id, @RequestParam("pw") String pw, @RequestParam("email") String email, Model model) {
		System.out.println("member/join name->"+name);
		System.out.println("member/join id->"+id);
		System.out.println("member/join pw->"+pw);
		System.out.println("member/join email->"+email);
        System.out.println("member/join member->"+member);
		
		Member member = new Member();
		member.setName(name);
		member.setId(id);
		member.setPw(pw);
		member.setEmail(email);
		
		model.addAttribute("member", member);
		
		return "member/join";
	}

🔎Member의 객체를 System.out.println으로 보고싶을 때?

Member DTO에서 toString() 오버라이딩

System.out.println("member/join member->"+member);
@Override
	public String toString() {
		String returnStr = "[" + "이름 :" + this.name + " ,id :" + this.id + "]";
		return returnStr;
	}


📂member

  • join.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>join.jsp</h1>
	이름 : ${member.name} <br>
	아이디 : ${member.id} <br>
	비밀번호 : ${member.pw} <br>
	이메일 : ${member.email}
</body>
</html>



🔎 Member dto를 파라미터로 받는다면?

toString() 형식을 써주기

  • HomeController.java
	// DTO Parameter
	@RequestMapping("member/join/dto")
	public String memberDto(Member member, Model model) {
		System.out.println("member/join getName()->"+member.getName());
		System.out.println("member/join getId()->"+member.getId());
		System.out.println("member/join getPw()->"+member.getPw());
		System.out.println("member/join getEmail()->"+member.getEmail());
	
		model.addAttribute("member", member);
		
		return "member/join";
	}

name에 파라미터 값을 한글로 넣으면 오류남😥
-> 한글 패치 설정 필요!




🔻och07_MVC041

[com.oracle.mvc041]

GET방식(❌)

// @RequestMapping(student")
-> get / post 동시허용
default가 get이 아님
@RequestMapping(value = "student", method = RequestMethod.GET)
-> get만 허용

  • HomeController.java
package com.oracle.mvc041;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@RequestMapping("index")
	public String goIndex() {
		logger.info("index start...");
		return "index";
	}
	
	// @RequestMapping(student")
	@RequestMapping(value = "student", method = RequestMethod.GET)
	public String getStudent(HttpServletRequest request, Model model) {
		logger.info("getStudent Start...");
		String id = request.getParameter("id");
		System.out.println("Get id : "+id);
		model.addAttribute("studentId", id);
		return "student/studentId";
	}
}

📂views

post방식

  • index.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>
	<form action="student" method="post">
		student id : <input type="text" name="id"><br>
		<input type="submit" value="전송">
	</form>
</body>
</html>

📂student

index에서 id 입력 값을 받아 "student"로 이동 후 다시 id를 받아 studentId.jsp로 이동

  • studentId.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>studentId.jsp</h1>
	studentId : ${studentId}
</body>
</html>

405 - 허용되지 않는 메소드

post / get 메소드를 잘 못 썼을 때 알림


POST방식(⭕)

GET / POST 차이

🔹GET : 서버에게 동일한 요청을 여러 번 전송하더라도 동일한 응답이 돌아와야 한다는 것
🔹POST : 서버에게 동일한 요청을 여러 번 전송해도 응답은 항상 다를 수 있다는 것

  • 게시글 조회: get
  • 게시글 글쓰기: post
  • 게시글 수정: put / patch
  • 게시글 삭제: delete 참고
  • HomeController.java
package com.oracle.mvc041;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@RequestMapping("index")
	public String goIndex() {
		logger.info("index start...");
		return "index";
	}
	
	// @RequestMapping(student")
	@RequestMapping(value = "student", method = RequestMethod.GET)
	public String getStudent(HttpServletRequest request, Model model) {
		logger.info("getStudent Start...");
		String id = request.getParameter("id");
		System.out.println("Get id : "+id);
		model.addAttribute("studentId", id);
		return "student/studentId";
	}
	
	@RequestMapping(value = "student", method = RequestMethod.POST)
	public String postStudent(HttpServletRequest request, Model model) {
		logger.info("postStudent Start...");
		String id = request.getParameter("id");
		System.out.println("POST id : "+id);
		model.addAttribute("studentId", id);
		return "student/studentId";
	}
	
}




🔻och07_MVC042

[com.oracle.mvc042]

👉순서

-> index 생성 -> index.jsp -> StudentInformation DTO -> studentView 생성

  • HomeController.java
package com.oracle.mvc042;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.oracle.mvc042.dto.StudentInformation;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@RequestMapping("/index")
	public String index() {
		System.out.println("HomeController index start...");
		return "index";
	}
	
	@RequestMapping("/studentView1")
	public String studentView1(StudentInformation studentInformation, Model model) {
		logger.info("studentView start...");
		System.out.println("studentInformation.getName() "+studentInformation.getName());
		System.out.println("studentInformation.getClassNum()"+studentInformation.getClassNum());
		System.out.println("studentInformation.getGradeNum() "+studentInformation.getGradeNum());
		System.out.println("studentInformation.getAge() "+studentInformation.getAge());
		
		model.addAttribute("studentInfo", studentInformation);
		
		return "studentView";
	}
}

📂views

  • index.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>
	<%
		String context = request.getContextPath();
	%>
<body>
	context : <%=context %> <p></p>
	<form action="<%=context %>/studentView1" method="post">
		이름 : <input type="text" name="name"><br>
		나이 : <input type="text" name="age"><br>
		학년 : <input type="text" name="gradeNum"><br>
		  반 : <input type="text" name="classNum">
		<input type="submit" value="전송">
	</form>
</body>
</html>

[com.oracle.mvc042.dto]

  • StudentInformation.java
package com.oracle.mvc042.dto;

public class StudentInformation {
	private String name;
	private String age;
	private String gradeNum;
	private String classNum;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getGradeNum() {
		return gradeNum;
	}
	public void setGradeNum(String gradeNum) {
		this.gradeNum = gradeNum;
	}
	public String getClassNum() {
		return classNum;
	}
	public void setClassNum(String classNum) {
		this.classNum = classNum;
	}
}

📂views

  • studentView.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>studentView.jsp</h1>
	이름 : ${studentInfo.name}</br>
	나이 : ${studentInfo.age}</br>
	학년 : ${studentInfo.gradeNum}</br>
	 반 : ${studentInfo.classNum}
</body>
</html>




🔎Model Annotation 사용한다면? -> 한번에 출력 가능

@ModelAttribute("studentInfo") StudentInformation studentInformation

  • HomeController.java
	@RequestMapping("/studentView2")
	public String studentView2(@ModelAttribute("studentInfo") StudentInformation studentInformation) {
		logger.info("studentView2 start...");
		System.out.println("studentInformation.getName() "+studentInformation.getName());
		System.out.println("studentInformation.getClassNum()"+studentInformation.getClassNum());
		System.out.println("studentInformation.getGradeNum() "+studentInformation.getGradeNum());
		System.out.println("studentInformation.getAge() "+studentInformation.getAge());
		
		return "studentView";
	}

  • index.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>
	<%
		String context = request.getContextPath();
	%>
<body>
	context : <%=context %> <p></p>
	<%-- <form action="<%=context %>/studentView1" method="post"> --%>
	<form action="<%=context %>/studentView2" method="post">
		이름 : <input type="text" name="name"><br>
		나이 : <input type="text" name="age"><br>
		학년 : <input type="text" name="gradeNum"><br>
		  반 : <input type="text" name="classNum">
		<input type="submit" value="전송">
	</form>
</body>
</html>




🔻och07_MVC043

🌈Redirect

👉"redirect:"리다이렉트 처리
컨트롤러에서 리턴타입은 String으로 하고 view 이름 대신 "redirect:"로 시작하는 문자열을 반환 하면 해당 주소로 리다이렉트 해줌

[com.oracle.mvc043]

  • RedirectController.java
package com.oracle.mvc043;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RedirectController {
	
	private static final Logger logger = LoggerFactory.getLogger(RedirectController.class);
	
	@RequestMapping("studentConfirm")
	public String studentRedirect(HttpServletRequest httpServletRequest, Model model) {
		
		logger.info("studentConfirm start..");
		
		String id = httpServletRequest.getParameter("id");
		logger.info("studentConfirm id->{}", id);
		
		String pw = "1234";
		
		model.addAttribute("id", id);
		model.addAttribute("pw", pw);
		// 성공이라고 가정 -- 같은 RedirectController 내 메소드로 이동
		if(id.equals("abc")) {
			return "redirect:studentSuccess";
		}
		
		//아니면 실패
		return "redirect:studentError";
	}
	
	@RequestMapping("studentSuccess")
	public String studentSuccess(HttpServletRequest request, Model model) {
		logger.info("studentSuccess start...");
		
		String id = request.getParameter("id");
		String password = request.getParameter("pw");
		logger.info("studentSuccess id->{}", id);
		logger.info("studentSuccess password->{}", password);
		model.addAttribute("id", id);
		model.addAttribute("password", password);
		
		return "student/studentSuccess";
	}
}

📂student

  • studentSuccess.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>studentSuccess</h1>
	id : ${id} <p>
	pw : ${password}
</body>
</html>

0개의 댓글