package com.sp.app.test2;

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

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller("test2.testController")
@RequestMapping("/test2/*")
public class TestController {

	@RequestMapping("main")
	public String execute() throws Exception {
		return "test2/main";
	}
	
	@GetMapping("header")
	public String headerInfo(
			@RequestHeader("Accept-Language") String lang,
			@RequestHeader("User-Agent") String agent,
			HttpServletRequest req,
			Model model
			) throws Exception {
		
		String referer = req.getHeader("Referer"); // 이전 주소
		if(referer == null) {
			referer = "";
		}
		
		String s = "헤더 정보...<br>";
		s += "클라이언트 언어 정보 : " + lang + "<br>";
		s += "클라이언트 브라우저 및 OS : " + agent + "<br>";
		s += "이전 클라이언트 URL : "+ referer;
		
		model.addAttribute("msg", s);
		
		return "test2/result";
	}
	
	@RequestMapping("setCookie")
	public String cookieSet(
			HttpServletResponse resp
			) throws Exception {
		// 쿠키 설정하기(유효시간 : 브라우저를 닫으면 쿠키가 제거됨. 기본)
		Cookie ck = new Cookie("subject", "spring");
		resp.addCookie(ck);
		
		return "redirect:/test2/main";
	}
	
	// @CookieValue : 쿠키 가져오기. 기본 required는 true로 쿠키가 없으면 400에러
	// 	defaultValue 속성으로 쿠키값이 없는 경우 초기값 부여 가능
	@RequestMapping("getCookie")
	public String cookieGet(
			@CookieValue(name="subject", defaultValue = "") String subject,
			Model model
			) throws Exception {
		
		String s = "쿠키내용 : " + subject;
		
		model.addAttribute("msg", s);
		return "test2/result";
	}
	
}
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
</head>
<body>

<p>
	<a href="${pageContext.request.contextPath}/test2/header"> 헤더정보확인 </a>
</p>

<p>
	<a href="${pageContext.request.contextPath}/test2/setCookie"> 쿠키설정 </a>
</p>

<p>
	<a href="${pageContext.request.contextPath}/test2/getCookie"> 쿠키확인 </a>
</p>


</body>
</html>
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
</head>
<body>

<p>
 ${msg}
</p>

</body>
</html>

+ Recent posts