❗ 예제 배포 금지!
- CPU 선점 / 비선점 이 있다.
최근 >> 비선점 추세
ex) 임베디드 시스템나는 내 일을 한다
- 요새 프로젝트는 MVC + ORM
My Batis : 파샬맵핑 > 부분적으로 DB설정 >> 한국에서 주로 사용
JPA : 풀 맵핑 >> 어렵다..(DB를 잘 알아야함) 서양권
🔺 배우는이유? 쓰는 회사도 있고 알긴해야해서.
아래처럼 만들고 기다리면 컨트롤러도 만들어진다! 🥰
- 컨트롤러를 열어서
System.out.println("HomeController home Start...");
를 추가해보기- 실행은 home.jsp
✔ 컨트롤러 : @Controller 해줌.
✔ logger ? 나의 메세지 뿌려줌
logger.info("Welcome home! The client locale is {}.", locale);
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 );
// <beans:property name="prefix" value="/WEB-INF/views/" />
// <beans:property name="suffix" value=".jsp" />
// /WEB-INF/views/ + home + .jsp
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";
}
}
✔ 프로젝트 시 mvc01를 하나 더 만들면 안된다. ??
mvc01.service 이런식으로 사용.
Model에다 담아서 View단에서 EL 표기법으로 사용.
✔ 둘의 차이는 설정의 자동화.
Dispatcher Servlet
, Handler Mapping
, View Resolver
설정을 해줘야함. 일일이 다 설정 해줘야한다😬context
광의의 개념
디스크에 있는걸 메모리에 옮김
협의의 개념
밖에
view 단의 루트
java 단의 루트
root-context.xml 빈설정하고 여기서 쓴다.
web.xml 을 보면
DispatcherServlet >> 프리 컨트롤러가 된다.
<?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>
<resources mapping="/resources/**" location="/resources/" />
resources 안에 이미지 파일 넣으면 된다<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
<context:component-scan base-package="com.oracle.mvc01" />
✔ 원리 이해하기
<?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>
The time on the server is 2022? 10? 20? ?? 10? 33? 18? KST.
✔ UTF-8 encoding 처리해주기
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>
🔺 맨처음 실행시 아래처럼 나오는데. WEB-INF/views/home.jsp
이부분을 지워주면 나온다.
pom.xml
의 Dependencies를 보면 아래처럼 다양한것을 사용 할수 있음을 알 수 있다.
<%@ 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>
- View 사용
@RequestMapping(value = "/board/view")
- Model 사용
@RequestMapping ("/board/content")
✔ String 으로 선언 + () 안에 Model을 넣어야 한다.
✔model.addAttribute("id", 365);
(= request.set)
🔺 spring에선 model.addAttribute 로 사용- ModelAndView 사용 `
@RequestMapping("/board/reply")
✔ 객체를 return형으로 선언 (view이름까지 한번에 전달)
✔ 모델을 일반적으로 많이 쓴다
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;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
@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";
}
// 모델 사용 - 모델을 담아서 가야한다 => String으로
@RequestMapping ("/board/content")
public String content(Model model) {
System.out.println("HomeController content Start =========");
model.addAttribute("id", 365); // id 라는 변수값에 365을 담아서 보내겠다
return "board/content";
}
// ModelAndView 사용 => view이름까지 한번에 전달하기때문에 객체를 return형으로 선언
@RequestMapping("/board/reply")
public ModelAndView reply() {
System.out.println("HomeController reply Start =========");
// 목적 : 파라메터와 View를 한방에 처리
ModelAndView mav = new ModelAndView();
mav.addObject("id", 50);
mav.setViewName("board/reply"); // () 안에 전달해줄 이름 작성
return mav;
}
}
controller에서 실행.
<%@ 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>
<%@ 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>
</body>
</html>
<%@ 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>
🔺네트워크 불안할때.
잘되는 사람의 m2를 압축해서 복붙 한다.
위치 :C:\Users\admin\.m2
@RequestParam
을 사용하면 값이 null 이면 화면이 아예 안넘어간다.
Member member
member에 다 담아서 이동.
(* member, jsp의 컬럼이 같다는 전제하에 가능.)
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;
import org.springframework.web.bind.annotation.RequestParam;
import com.oracle.mvc03.dto.Member;
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
@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("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";
}
// 파라미터 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";
}
// 파라미터 Force(강제) << @RequestParam
@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);
Member member = new Member();
member.setName(name);
member.setId(id);
member.setPw(pw);
member.setEmail(email);
model.addAttribute("member", member);
return "member/join";
}
// DTO 파라미터
@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());
System.out.println("member/join member => " + member);
model.addAttribute("member", member);
return "member/join";
}
}
board/confirmId 를 입력.
? 이하는 값을 안넣어줘서 보기 위해 넣은것.
✔ 값을 안주면 null값을 들어감
board/checkId 를 입력.
? 값 을 안넣으면 화면 자제가 보이지 않는다.
✔ 값을 안주면 오류!
Member
- 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>confirmId.jsp</h1>
ID : ${id}<br>
PW : ${pw}
</body>
</html>
<%@ 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.jsp</h1>
ID : ${identify}<br>
PW : ${password}
</body>
</html>
멤버 변수를
toString()
형태로 만들어서 써도 좋다.
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;
}
}
<%@ 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>
Get은 조회할때. Post는 입력할때
✔
index.jsp
에서<form action="student" method="post">
으로 요청했기 때문에
Get 으로 하면 오류.
Post 방식으로 하면 제대로 나온다.
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;
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
@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";
}
}
<%@ 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>
<%@ 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>
400 파라미터나 문법을 잘못 넘겨줬을때
404 못찾겠다
405 메소드가 잘못 된것get, post 잘못
두가지 방법으로 실행.
studentView1
,studentView2
=>> 같은 View를 사용. 이름만 다른것
한줄로 쓰기 :@ModelAttribute("studentInfo") StudentInformation studentInformation)
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.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.oracle.mvc042.dto.StudentInformation;
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
@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("===== studentView1 Start .......");
System.out.println("studentInformation getName() ->> " + studentInformation.getName());
System.out.println("studentInformation getAge() ->> " + studentInformation.getAge());
System.out.println("studentInformation getGradeNum() ->> " + studentInformation.getGradeNum());
System.out.println("studentInformation getClassNum() ->> " + studentInformation.getClassNum());
model.addAttribute("studentInfo", studentInformation);
return "studentView";
}
@RequestMapping("/studentView2")
// 한방에 다 해결. model 안써도 된다. 아래처럼 쓰면 한번에 다 넣을 수 있다. 위랑 같은데 다른 방식으로.
public String studentView2(@ModelAttribute("studentInfo") StudentInformation studentInformation) {
logger.info("===== studentView2 Start .......");
System.out.println("studentInformation2 getName() ->> " + studentInformation.getName());
System.out.println("studentInformation2 getAge() ->> " + studentInformation.getAge());
System.out.println("studentInformation2 getGradeNum() ->> " + studentInformation.getGradeNum());
System.out.println("studentInformation2 getClassNum() ->> " + studentInformation.getClassNum());
return "studentView";
}
}
<%=context%>
넣는 이유 ?
폴더가 깊어지면? 경로를 잘 못찾기 때문에 사용한다. 프로젝트 작업시 꼭 적어주기.
<form action="<%=context%>/studentView1" method="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>
<% String context = request.getContextPath(); %>
</head>
<body>
context : <%=context%><p/>
<form action="studentView" 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}<br/>
</body>
</html>
package com.oracle.mvc043;
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;
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
@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";
}
}
컨트롤러 만들기.
spring 에서는 조원이 각자 컨트롤러를 만들어서 작업한다.
- 성공하면 같은 Controller 내에 메소드로 이동.
- ⭐ id가 "abc" 면 성공.
주소창에id=abc
만 입력해주면.jsp
를 찾아서 이동해준다
✔ @RequestMapping("studentError")
추가
아이디가 다르면 studentError로 빠짐.
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);
// 성공이라고 가정 --> 같은 Controller 내에 메소드로 이동.
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("studentConfirm id ->{} ", id);
logger.info("studentConfirm password ->{} ", password);
model.addAttribute("id", id);
model.addAttribute("password", password);
return "student/studentSuccess";
}
@RequestMapping("studentError")
public String studentError(Model model) {
logger.info("studentError start... ");
return "student/studentError";
}
}
파일위치 :
main - webapp - WEB-INF - views - 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.jsp</h1>
ID : ${id}<br/>
PW : ${password}
</body>
</html>
파일위치 :
<%@ 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.jsp</h1>
넌 누구냐<p>
<h1>20년간 만두만</h1> 주고...
id : ${id}
</body>
</html>