본문 바로가기
Back-End/Spring

[Spring] MVC 패턴

by 찐코딩 2021. 12. 14.

1.model 형식

2.ModelAndView 형식

 

ModelAndView 형식

ModelAndView 객체란?
   - ModelAndView 객체는 컨트롤러에 의해서 비즈니스 로직이 수행되고 나면 대체적으로 사용자에게 반환되어 브라우저에 보여질 정보들이 만들어진다.
    이때 만들어진 정보를 view page로 넘겨주게 되는데 응답을 할 view page 정보와 전달할 데이터를 한꺼번에 저장하여 넘겨줄 때 사용함

 

Mycontroller.java

package com.sist.mvc01;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller

public class MyController {
	
	@RequestMapping("/info")
	public ModelAndView abc() {
		ModelAndView mav = new ModelAndView();
		
		//addObject("키","데이터");
		mav.addObject("email","hong@naver.com");	// 정보를 ModelAndView에 저장
		// setViewName("폴더명/폴더에 들어갈 jsp page");
		mav.setViewName("member/email");
		
		return mav;
		// 이 return정보가 servlet-context.xml로 넘어감
	}
	

}

위에서 member폴더에 email.jsp로 경로와 파일명을 지정해주었으므로,

email.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>

	<div align="center">
      <h2>홍길동 님의 메일 주소 : ${email }</h2>   
   </div>

</body>
</html>

 

MVC2패턴

 

1. 한글 인코딩 작업

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>

	<!-- 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>
	
	<!-- 한글 인코딩 설정 작업 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharaterEncodingFilter</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>	

</web-app>

MyController.java

package com.sist.mvc02;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyController {
	
	// input이라는 명령이 들어오면 insertForm이라는 웹 페이지로 이동하라
	@RequestMapping("/input")
	public String aaa() {	// 메서드 이름은 상관없음
		return "insertForm";
	}
}

 

 

@RequestParam 애노테이션을 이용한 방식

MyController.java

@RequestMapping("/login")
	public String login() {
		return "loginForm";
	}

login.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>
	<div align="center">
		<hr width="50%" color="blue">
			<h3>입력된 개인 정보</h3>
		<hr width="50%" color="blue">
		
		<br><br>
		
		<table border="1" cellspacing="0" width="300"> 
			<tr>
				<th>이름</th>
				<td>${userName }</td>
			</tr>
			
			<tr>
				<th>아이디</th>
				<td>${userId }</td>
			</tr>
		</table>
		
	</div>
</body>
</html>

loginForm.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>

	<div align="center">
		<hr width="50%" color="gray">
			<h3>로그인 입력 폼 페이지</h3>
		<hr width="50%" color="gray">
		<br><br>
		
		<form method="post"
			action="<%=request.getContextPath() %>/LoginOk">
			
			<table border="1" cellspacin="0" width="300">
				<tr>
					<th>아이디</th>
					<td> <input name="user_id"> </td>
				</tr>
				
				<tr>
					<th>비밀번호</th>
					<td> <input name="user_pwd" type="password"> </td>
				</tr>
				
				<tr>
					<td colspan="2" align="center">
					 <input type="submit" value="로그인">&nbsp;&nbsp;&nbsp;
					 <input type="reset" value="취소"> </td>
				</tr>
			</table>
		</form>
	</div>
</body>
</html>

MyController.java

@RequestMapping("/loginOk")
	public String loginOk(@RequestParam("user_id") String userId, 
			@RequestParam("user_pwd") String userPwd,
			Model model) {
		
		model.addAttribute("userId",userId);
		model.addAttribute("userPwd",userPwd);
		
		return "result";
	}

형식

@RequestParam("넘어온 키 이름") String 저장할 변수명

 

댓글