springmvc如何获取HTTP请求头呢?

乔欣 SpringMVC 发布时间:2023-02-09 06:06:18 阅读数:16090 1
下文笔者讲述使用java代码获取http请求头的方法及示例分享,如下所示
获取http请求头的实现思路:
    我们只需在前端请求中获取HttpServletRequest即可
	实现获取请求头的效果

webUtil工具类


//获取用户信息头的所有信息

package com.java265.web.utils;
 
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
 
public class WebUtils {
 
    private Map<String, String> getHeadersInfo(HttpServletRequest request) {
 
        Map<String, String> map = new HashMap<String, String>();
 
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
 
        return map;
    }
}
例:spring mvc中获取用户请求头
package com.java265.web.controller;
 
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
@RequestMapping("/site")
public class SiteController {
 
	@Autowired
	private HttpServletRequest request; //直接注入的方式获取请求头
 
	@RequestMapping(value = "/{input:.+}", method = RequestMethod.GET)
	public ModelAndView getDomain(@PathVariable("input") String input) {
 
		ModelAndView modelandView = new ModelAndView("result");
 
		modelandView.addObject("user-agent", getUserAgent());
		modelandView.addObject("headers", getHeadersInfo());
 
		return modelandView;
 
	}
 
	//get user agent
	private String getUserAgent() {
		return request.getHeader("user-agent");
	}
 
	//get request headers
	private Map<String, String> getHeadersInfo() {
 
		Map<String, String> map = new HashMap<String, String>();
 
		Enumeration headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String key = (String) headerNames.nextElement();
			String value = request.getHeader(key);
			map.put(key, value);
		}
 
		return map;
	}
 
}


注意事项:
 当HttpServletRequest无法找到
  需在pom.xml引入以下依赖

<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>servlet-api</artifactId>
		<version>2.5</version>
	</dependency>
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringMVC/202302/5716.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者