Legacy 프로젝트 생성
context 이름 설정(세번째 자리)
프로젝트 생성 후 자동으로 controller, view 생성
DispatcherServlet : pre-Controller
@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";
}
<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>
<!-- 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
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
출력 페이지 내 한글깨짐
버전 올리기 -> 자동완성❌
한글처리 주석 줄 추가
<?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>
👍해결
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-서버메세지
DI 설정
파라미터 값
<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>
- 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>
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>
이미지 추가
만든 패키지 하위로 패키지를 만들기
메소드 지정 안하면 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";
}
}
<%@ 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>
@RequestMapping("/board/content")
public String content(Model model) {
System.out.println("HomeController content start....");
model.addAttribute("id", 365);
return "/board/content";
}
<%@ 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>
목적 : parameter와 view를 한번에 처리
반환값 : ModelAndView 객체를 반환
@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;
}
<%@ 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>
데이터가 없을 때 null 값으로 처리
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";
}
}
<%@ 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>
주소에서 직접 값을 넣음
파라미터를 강제로 넣어야한다고 선언하고 싶을 때
// 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";
}
<%@ 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>
파라미터가 필수일 때 오류 발생
파라미터를 강제로 넣었을 때 결과
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;
}
}
// 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 DTO에서 toString() 오버라이딩
System.out.println("member/join member->"+member);
@Override public String toString() { String returnStr = "[" + "이름 :" + this.name + " ,id :" + this.id + "]"; return returnStr; }
<%@ 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>
// 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에 파라미터 값을 한글로 넣으면 오류남😥
-> 한글 패치 설정 필요!
// @RequestMapping(student")
-> get / post 동시허용
default가 get이 아님
@RequestMapping(value = "student", method = RequestMethod.GET)
-> get만 허용
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";
}
}
post방식
<%@ 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>
index에서 id 입력 값을 받아 "student"로 이동 후 다시 id를 받아 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>
post / get 메소드를 잘 못 썼을 때 알림
🔹GET : 서버에게 동일한 요청을 여러 번 전송하더라도 동일한 응답이 돌아와야 한다는 것
🔹POST : 서버에게 동일한 요청을 여러 번 전송해도 응답은 항상 다를 수 있다는 것
- 게시글 조회: get
- 게시글 글쓰기: post
- 게시글 수정: put / patch
- 게시글 삭제: delete 참고
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";
}
}
-> index 생성 -> index.jsp -> StudentInformation DTO -> studentView 생성
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";
}
}
<%@ 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>
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;
}
}
<%@ 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>
@ModelAttribute("studentInfo") StudentInformation studentInformation
@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";
}
<%@ 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>
👉"redirect:"리다이렉트 처리
컨트롤러에서 리턴타입은 String으로 하고 view 이름 대신 "redirect:"로 시작하는 문자열을 반환 하면 해당 주소로 리다이렉트 해줌
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";
}
}
<%@ 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>