2022-08-20

Spring MVC提供@RequestHeader注解方便我们获取请求头信息。

1 设计表单

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

2 编写Controller

            
            package com.yiidian.controller;
            import org.springframework.stereotype.Controller;
            import org.springframework.web.bind.annotation.RequestHeader;
            import org.springframework.web.bind.annotation.RequestMapping;
            /**
             * @RequestHeader注解获取请求头信息
             * 一点教程网 - www.yiidian.com
             */
            @Controller
            public class ParamController {
            
                @RequestMapping("/param.do")
                public String save(@RequestHeader("host") String host,
                                   @RequestHeader("accept") String accept){
                    System.out.println("host---"+host);
                    System.out.println("accept---"+accept);
                    return "success";
                }
            }

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 运行测试

202202131334470881.png

202202131334475912.png

源码下载:https://pan.baidu.com/s/1xDApmHB4T5bVpFQAqvjOpw

阅读全文