springmvc如何获取HTTP请求头呢?
下文笔者讲述使用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>
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。