note

@CookieValue 어노테이션을 이용한 쿠키 매핑 본문

JSP/Spring

@CookieValue 어노테이션을 이용한 쿠키 매핑

투한 2012. 3. 5. 10:48











실행후 모든 페이지 닫은후 다시 실행후 쿠키 확인






쿠키가 남아 있지 않음을 확인 할 수 있다(defaultValue가 동작하여 0으로 셋팅이 됨)





Servlet Import 에러 발생시 이전 게시물 참고
[JSP/Spring] - Spring Servlet import 에러시









CookieController.java

response.addCookie
쿠키를 전송하는 일을 수행
key 값 value로 전송



@CookieValue 어노테이션은 클라이언트가 제공하는 쿠키 정보를 읽어들임









dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">



	<!-- @CookieValue 어노테이션을 이용한 쿠키 매핑 -->
	<bean id="cookieController" class="madvirus.spring.chap06.controller.CookieController" />
	
	
	<!-- View 글로벌 설정 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/view/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>




CookieController.java
package madvirus.spring.chap06.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

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


@Controller
public class CookieController {
	
	@RequestMapping("/cookie/make.do")
	public String make(HttpServletResponse response){
		response.addCookie(new Cookie("auth", "1"));
		return "cookie/made"; //View경로
	}

	//@CookieValue 어노테이션은 클라이언트가 제공하는 쿠키 정보를 읽어들임
	
	@RequestMapping("/cookie/view.do")
	public String view(@CookieValue(value="auth",defaultValue="0") String auth){
		System.out.println("auth 쿠키 : "+auth);
		return "cookie/view";
	}
}







cookie/made.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>쿠키</title>
</head>
<body>
쿠키 생성함
</body>
</html>





cookie/view.jsp 
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>쿠키</title>
</head>
<body>
쿠키 확인
</body>
</html>