@CookieValue注解

Spring MVC提供@CookieValue方便我们获取指定Cookie数据。

1 设计表单

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>一点教程网 - www.yiidian.com</title>
</head>
<body>
<h2>使用@CookieValue获取Cookie数据</h2>
<a href="/param.do">获取Cookie</a>
</body>
</html>

2 编写Controller

package com.yiidian.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
/**
 * @CookieValue注解获取指定Cookie数据
 * 一点教程网 - www.yiidian.com
 */
@Controller
public class CookieController {

    @RequestMapping("/cookie.do")
    public String save(@CookieValue("JSESSIONID") String sessionId){
        System.out.println("JSESSIONID---"+sessionId);
        return "success";
    }
}

注意:这里获取了JSESSIONID这个Cookie值,当然也可以获取其他Cookie值。

3 springmvc.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 1.扫描Controller的包-->
    <context:component-scan base-package="com.yiidian.controller"/>

    <!-- 2.配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 2.1 页面前缀 -->
        <property name="prefix" value="/pages/"/>
        <!-- 2.2 页面后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 3.创建处理器适配器和处理器映射器-->
    <mvc:annotation-driven/>
</beans>

4 运行测试

 

 

源码下载:https://pan.baidu.com/s/1lL8P2d8l1OJWHrH_Z-pb-g

热门文章

优秀文章