两种方法:
1.在方法参数中加入@RequestHeader
2.在类级别注入HttpServletRequest
建议使用第二种方法,这样可避免每个方法都加入HttpHeaders参数
@Controller
@RequestMapping("/hello")
public class HelloController {
@Autowired
private HttpServletRequest request;
@RequestMapping(value="/printname/{name}", method=RequestMethod.GET)
public String printName(@PathVariable String name,
@RequestHeader HttpHeaders headers) {
System.out.println("from request:" + request.getHeader("code"));
System.out.println("from parameter:" + headers.getFirst("code"));
return "hello";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
//..
@Controller
public class HelloController {
@RequestMapping(value = "/hello.htm")
public String hello(@RequestHeader(value="User-Agent", defaultValue = "0") String userAgent)
//..
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
————————————————
版权声明:本文为CSDN博主「两只橙」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/lzc4869/article/details/78496241