본문 바로가기
Java Web Programming/6. Spring | MyBatis

[SpringMVC] Annotation 어노테이션 기반의 SpringMVC 연습!

by 파프리카_ 2020. 11. 5.
728x90
반응형

Maven pom 설정

/pom.xml

<dependencies>
  <!-- Spring-Web MVC Framework -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.14.RELEASE</version>
  </dependency>
</dependencies>

★web.xml과 springmvc-servlet.xml은 WEB-INF 폴더에 같이 두어야 한다! ★

DD (Deploytment Descriptor) 설정

/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>SpringMVC3-Annotation</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- servlet 설정 -->
  <servlet>
  	<!-- servlet-name을 기반으로 spring 파일을 찾는다. -->
  	<servlet-name>springmvc</servlet-name>
 	<!-- Libary 제공 -->
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<!-- load-on-startup 
  		 : Serlvet LifeCycle에 의거해서, 
  		   어플리케이션 최초 실행 시 해당 servlet을 객체 생성, init()까지 실행되도록 설정
  		   만약 이 태그를 기입해주지 않으면, 클라이언트 최초 요청 시점에 서블릿이 초기화된다. -->
  	<load-on-startup>1</load-on-startup>
  </servlet>
  
  <!-- servlet-mapping 설정 -->
  <servlet-mapping>
  	  <!-- DispatcherSerlvet은 자신의 설정 파일(springMVC 설정)을 
  	  	   [serlvet-name]-serlvet.xml로 찾아서 로딩한다. -->
	  <servlet-name>springmvc</servlet-name>
	  <!-- 클라리언트 요청 url이 .do으로 마치는 요청은
	  	   모두 DispatcherSerlvet이 처리한다. -->
	  <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
  
  <!-- POST 방식으로 전송 시, 한글처리를 위한 인코딩 설정 -->
  <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>
  </filter>
  
  <filter-mapping>
  	<filter-name>EncodingFilter</filter-name>
  	<!-- 모든 요청에 인코딩 처리하겠다는 의미 -->
  	<url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

Spring configure 설정

* namespace에서 context,  mvc 추가

 

1. IOC 설정

<context:component-scan> :  IOC, DI, DL에 대한 설정
 1) 컴포넌트 계열의 어노테이션이 명시된 클래스에 대해 객체를 생성하고,
 2) DI 계열 어노테이션이 명시된 대상에 대해 해당 객체를 주입하는 역할을 한다.

2. SpringMVC 설정

3. ViewResolver 설정 : client에게 응답하는 view에 대한 설정

 

/springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
	
	<!-- IOC 설정 -->
	<context:component-scan base-package="org.kosta"></context:component-scan>

	<!-- SpringMVC 설정 : annotation 기반 controller 설정 -->
	<mvc:annotation-driven/>
	
	<!-- ViewResolver 설정 : client에게 응답하는 view에 대한 설정 -->
	<bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/views/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
	
	<!-- error page 설정 -->
	<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<!-- views/error.jsp로 응답 -->
		<property name="defaultErrorView" value="error"/>
	</bean>
</beans>

Model

/org.kosta.model

 

/CustomerVO.java

package org.kosta.model;

public class CustomerVO {
	private String id;
	private String name;
	private String address;
	
	public CustomerVO() {
		super();
	}

	public CustomerVO(String id, String name, String address) {
		super();
		this.id = id;
		this.name = name;
		this.address = address;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "CustomerVO [id=" + id + ", name=" + name + ", address=" + address + "]";
	}
}

View

/index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
	<!-- Annotation 기반 SpringMVC 예제 -->
	<a href="hello.do">hello test</a>
	<br>
	<a href="bye.do">bye test</a> 
	<br><br>
	<form action="paramtest1.do">
		이름 <input type="text" name="userName">
		<input type="submit" value="전송 테스트 1">
	</form>
	<br>
	<form action="paramtest2.do">
		이름 <input type="text" name="userName">
		<input type="submit" value="전송 테스트 2">
	</form>
	<br>
	<form action="paramtest3.do">
		이름 <input type="text" name="userName">
		주소 <input type="text" name="userAddr">
		<input type="submit" value="전송 테스트 3">
	</form>
	<br><br>
	<form action="paramtest4.do">
		<input type="checkbox" name="hobby" value="독서">독서<br>	
		<input type="checkbox" name="hobby" value="기타연주">기타연주<br>	
		<input type="checkbox" name="hobby" value="피아노연주">피아노연주<br>
		<input type="submit" value="등록">
	</form>
	<br><br>
	<!-- POST방식으로 VO객체 전달 -->
	<form action="paramtest5.do" method="POST">
		아이디 <input type="text" name="id"><br>
		이름 <input type="text" name="name"><br>
		주소 <input type="text" name="address"><br>
		<input type="submit" value="등록">
	</form>
	<br><br>
	<form action="login.do" method="POST">
		아이디 <input type="text" name="id"><br>
		패스워드 <input type="password" name="password"><br>
		<input type="submit" value="로그인">
	</form>
	<br><br>
	<!-- Error page test -->
	<a href="testError.do">에러 설정 테스트</a>
	<br><br>
	
	<!-- ModelAndView Test -->
	<form action="testModelAndView.do">
		닉네임 <input type="text" name="nick" required="required">
		<input type="submit" value="전송">
	</form>
	
</body>
</html>

/Views

 

/result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>result</title>
</head>
<body bgcolor="pink">
	result page
</body>
</html>

 

/bye_result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>bye_result</title>
</head>
<body bgcolor="skyblue">
	bye result page	
</body>
</html>

 

/test_result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test result</title>
</head>
<body bgcolor="lime">
	result page <br>
	parameter => 이름: ${param.userName}, 주소: ${param.userAddr}
</body>
</html>

 

/redirect_result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>redirect_result</title>
</head>
<body bgcolor="coral">
	redirect result page<br>
	id: ${sessionScope.id} <br>
	password : ${sessionScope.password}
</body>
</html>

 

/error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body bgcolor="red">
	<marquee scrollamount="100" behavior="alternate">
		<font color="blue" size="9">ERROR! 콘솔을 확인해주세요.</font> 
		<br><br>
		<img src="error.jpg">
	</marquee>
</body>
</html>

 

/test_result2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test_result2</title>
</head>
<body>
	<!-- request scope에 저장되어있는 
		 정보를 출력 -->
	test_result2 page <br>
	${requestScope.memberInfo}
</body>
</html>

Controller

/org.kosta.Controller

 

@Controller

@RequestMapping("[method_name] .do") : @RequestMapping 어노테이션 바로 밑에 있는 메서드가 실행된다.

 

- post방식만 처리 (get방식으로 보내면 405에러)

  1) spring version 4.3 미만인 환경에서 처리
   @RequestMapping(method=RequestMethod.POST, value="paramtest5.do")
   2) spring version 4.3 이상인 환경에서 지원

   @PostMapping("paramtest5.do")

 

/MyController.java

package org.kosta.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.kosta.model.CustomerVO;
import org.kosta.model.MemberVO;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/* annotation기반 controller는 
 * 클라이언트의 다양한 요청을 하나의 컨트롤러에서 
 * 처리할 수 있다.
 */

@Controller
public class MyController {
	
	//client가 hello.do로 요청하면 아래 hello()메서드가 실행된다.
	@RequestMapping("hello.do") //url은 유일해야함
	public ModelAndView hello() { //Handler
		System.out.println("hello() 실행");
		
		String data = "model의 dao와 연동한 데이터";
	
		/* 1. springmvc-serlvet.xml에 있는 ViewResolver 설정에 의해
		 * /views/result.jsp로 응답한다.
		 * 2. new ModelAndView(view-name, attribute-name, attribute-value); */
		return new ModelAndView("result", "data", data);
	}
	
	// 1. client가 bye.do로 요청하면 아래 bye()메서드가 실행된다.
	@RequestMapping("bye.do")
	public ModelAndView bye() {
		System.out.println("bye() 실행");
		return new ModelAndView("bye_result");
	}
	
	// 2. parameter 가져오기 1 (request.getParameter()로)
	@RequestMapping("paramtest1.do")
	public ModelAndView paramtest1(HttpServletRequest request) {
		System.out.println(request.getParameter("userName"));
		return new ModelAndView("test_result");
	}
	
	// 3. parameter 가져오기 2 
	// Spring Framework에서 내부적으로 request.getParameter()를 진행해서,
	// 아래 메서드 매개변수에 전달한다. 
	// 매개변수 이름은 param의 name을 적어준다.
	// (ex. <input type="text" name="userName">)
	@RequestMapping("paramtest2.do")
	public ModelAndView paramtest2(String userName) {
		System.out.println(userName);
		return new ModelAndView("test_result");
	}
	
	// 4. 여러개의 parameter 값 받아오기
	@RequestMapping("paramtest3.do")
	public String paramtest3(String userName, String userAddr) {
		System.out.println(userName+" "+userAddr);
		return "test_result"; //viewName만 반환할 경우에, String형식으로 리턴 가능
	}
	
	// 5. checkbox 결과값 받아오기
	@RequestMapping("paramtest4.do")
	public String paramtest4(String[] hobby) { //request.getParameterValues("hobby")
		for (int i = 0; i < hobby.length; i++) {
			System.out.println(hobby[i]); //독서 피아노연주
		}
		return "test_result";
	}
	
	// 6. POST방식으로 받아, VO로 결과값 반환하기
	//post방식 처리 (get방식으로 보내면 405에러)
	//   - spring version 4.3 미만인 환경에서 처리
	//@RequestMapping(method=RequestMethod.POST, value="paramtest5.do")
	//   - spring version 4.3 이상인 환경에서 지원
	@PostMapping("paramtest5.do")
	//form데이터를 객체로 전달받을 수 있다.
	public String paramtest5(CustomerVO vo) { 
		System.out.println(vo); //CustomerVO [id=milk, name=밀크, address=부천]
		return "test_result";
	}
	
	// 7. session 세션 생성 & redirect 방식으로 view 이동
	@PostMapping("login.do")
	public String paramtest6(String id, String password, HttpSession session) {
		System.out.println(id + " "+ password + " 확인해서 로그인 처리");
		//milk milk 확인해서 로그인 처리
		System.out.println(session + " 세션");
		//org.apache.catalina.session.StandardSessionFacade@6bb20d1 세션
		
		//세션 보내주기
		session.setAttribute("id", id);
		session.setAttribute("password", password);
		
		//redirect 방식으로 응답 (viewResolver에 가지 않아서 경로를 다 써줘야 함)
		return "redirect:views/redirect_result.jsp";
	}
	
	// 8. error page test
	@RequestMapping("testError.do")
	public String testError() {
		String s = null;
		System.out.println(s.length());
		return "test_result";
	}
	
	// 9.  매개변수 받아 모델 연동 결과 값 공유
	
	// 9_1. ModelAndView로 반환 (Model과 View를 ModelAndView로 처리)
	/*@RequestMapping("testModelAndView.do")
	public ModelAndView testModelAndView(String nick) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("test_result2");
		//dao와 연동결과
		mv.addObject("memberInfo", "넥네임 '" +nick + "' 회원정보 아이유 28세 판교");
		return mv;
	}*/
	
	//9_2. 매개변수를 Model로 받아 add한 후 String(url)만 반환
	@RequestMapping("testModelAndView.do")
	public String TestModelAndView(String nick, Model model) {
		//아래 코드는 request.setAttribute("name, value)
		model.addAttribute("memberInfo", "넥네임 '" +nick + "' 회원정보 아이유 28세 판교");
		return "test_result2";
	}
}

[ 결과 ]

> 홈화면

 

> 'hello test' 링크 클릭하면, result.jsp가 나온다

 

> 'bye test'링크를 클릭하면, bye_result.jsp가 나온다.

 

> 이름 기입 후 '전송테스트1' 혹은 '전송테스트2' 클릭

 

> 이름, 주소 기입 후 '전송테스트3' 클릭

 

> 아이디, 비밀번호 기입 후, '로그인' 클릭

728x90
반응형