发布于 2年前
Spring MVC获取请求header的方法
在Spring MVC有两种方法可以用来获取请求头Header的值。
方法一、通过在方法的参数添加注解@RequestHeader
示例如下:
@Controller
public class RequestHeaderDemoController {
@Autowired
private HttpServletRequest request;
@GetMapping("/printheader")
public String printHeader(@RequestHeader HttpHeaders headers) {
System.out.println("from parameter:" + headers.getFirst("myheader"));
return "demo";
}
}
或者在注解@RequestHeader指定获取的header:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
//..
@Controller
public class DemoController {
@GetMapping(value = "/demo")
public String hello(@RequestHeader(value="myheader") String myheader)
//..
}
}
方法二、从HttpServletRequest获取请求头信息
示例如下:
@Controller
public class RequestHeaderDemoController {
@Autowired
private HttpServletRequest request;
@GetMapping("/printheader")
public String printHeader(HttpServetRequest request) {
System.out.println("from parameter:" + request.getHeader("myheader"));
return "demo";
}
}