관리 메뉴

개발 노트

10/20 @RequestParam, DTO, @ModelAttribute 본문

프로젝트 기반 JAVA 응용 SW개발 : 22.07.19~23.01.20/Spring

10/20 @RequestParam, DTO, @ModelAttribute

hayoung.dev 2022. 10. 28. 11:16

File > New > Spring Legacy Project

Spring MVC Project 선택하고 생성

 

context명

생성하면 모든 구조들이 만들어져있음.

 

controller에 member관련 코드 추가. 실행할 때 controller 실행함.

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 : 내 자신이 뭔지 말해줌 */
		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", "member" );
		
		return "home";
	}	
}

home.jsp에 member관련 코드 추가

<%@ 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>

URL에 / 작성한 경우

URL에 /member 작성한 경우

프로젝트 시작할 때 제일 먼저 web.xml을 준다.

 

출력 결과

 

122p. 읽어보기

 

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>

 

<och07_MVC02>

상단 java > com.oracle.mvc02(package) > HomeController.java

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;

/**
 * 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";
	}
	
	/* /board/view.jsp를 실행  */
	@RequestMapping(value = "/board/view")
	public String view() {
		logger.info("Welcome home! {} start...", "/board/view");
		return "board/view";
	}
	
	@RequestMapping("/board/content")
	public String content(Model model) {
		System.out.println("HomeController content start...");
		model.addAttribute("id", 365);
		
		return "board/content";
	}
	
	@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;
		
	}	
}

하단 src > main > webapp > WEB-INF > views > 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>

실행 결과

src > main > webapp > WEB-INF > views > 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>

실행 결과

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>

*맨 처음 프로젝트 만들었을 때 작동하는지 테스트 바로 해보기.

java > HomeController.java

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;

/**
 * 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 선택
	// 파라미터가 없어도 실행은 된다. id와 pw를 uri창에 직접 입력하면 파라미터값을 가져올 수 있다.
	@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";
		
	}
	// Parameter Force(파라미터 강제화. 파라미터가 없으면 실행 안됨)
	//@RequestParam을 사용하면 파라미터가 없을 때 400오류로 실행이 되지 않는다.
	@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";
	}
	
	// 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 /* view에 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);

		/* package가 다르기 때문에 member 선언 */
		Member member = new Member();
		/* member에 setter를 이용해 값 넣음 */
		member.setName(name);
		member.setId(id);
		member.setPw(pw);
		member.setEmail(email); 
		
		model.addAttribute("member", member);
		
		return "member/join" ;
	}
	
	
	// DTO Parameter  
	// 직접 DTO로 받아도 되기 때문에 이 방법이 편리하다.
	@RequestMapping("member/join/dto")
	public String memberDto(Member member,
			                Model model
			
			) 
	{
		System.out.println("member/join member.getName()->"+member.getName());
		System.out.println("member/join getId->"+member.getId());
		System.out.println("member/join getPw->"+member.getPw());
		System.out.println("member/join email->"+member.getEmail());
		
		model.addAttribute("member", member);
		
		return "member/join" ;
	}
}

*java에서는 package로 생성, view에서는 폴더로 생성

views > 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>

 

출력 결과 : 이렇게 직접 URI창에 id와 pw값을 직접 지정해주면 값이 나온다.

views > 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>

출력 결과 : 파라미터 없으면 실행이 되지 않음

 

*java > com.oracle.mvc03 안에서 dto 패키지를 만들어야 한다.

java > com.oracle.mvc03.dto (package) > 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;
	}

	
}

view > 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>

출력 결과

 

<och07_MVC041>

File > new > Legacy Project, Spring MVC project 선택, com.oracle.MVC041 작성

 

java > 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";
	}
	
	/* MVC모델이기 때문에 서버가 하는 일이 없어도 서버를 거쳐야 한다. */
	@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";
		
	}	
}

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

view > student > 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>

*오류 유형 알아두기

400 : 문법이 잘못 됨

404 : 데이터가 없음

405 : get이나 post 방식 등의 메소드가 잘못됨

 

출력 결과

(kk3 입력)

 

<och07_MVC042>

Spring MVC project 선택, com.oracle.mvc042 작성

 

java > 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.ModelAttribute;
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("studentView1 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";

	}

		/* @ModelAttribute는 강제로 전달받은 파라미터를 Model에 담아서 전달할 때 필요한 어노테이션이다.. */
	@RequestMapping("/studentView2")
	public String studentView2(@ModelAttribute("studentInfo") StudentInformation studentInformation) {
		logger.info("studentView2 Start...");
		System.out.println("studentInformation2.getName()->"+studentInformation.getName());
		System.out.println("studentInformation2.getClassNum()->"+studentInformation.getClassNum());
		System.out.println("studentInformation2.getGradeNum()->"+studentInformation.getGradeNum());
		System.out.println("studentInformation2.getAge()->"+studentInformation.getAge());
		
		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"> --%>
   <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"><br />
		   <input type="submit" value="전송">
   </form>
</body>
</html>

 

java > com.oracle.mvc042(package) > new package > com.oracle.mvc042.dto

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;
	}
	
	

}

view > 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.classNum} <br />
     반 : ${studentInfo.gradeNum}
</body>
</html>

출력 결과 : 두 가지 방법 다 잘 나옴.

 

반응형