1、接收cookie
(1)接收所有cookie
java
@RequestMapping("/request")
@RestController
public class RequestController {
@RequestMapping("/c1")
public String c1(HttpServletRequest request){
Cookie[] cookies = request.getCookies();
if(cookies != null){
for (Cookie cookie : cookies){
System.out.println(cookie.getName() + ":" + cookie.getValue());
}
return "获取cookie成功!";
}
return "cookies为空";
}
}
(2)接收单个cookie
java
@RequestMapping("/request")
@RestController
public class RequestController {
@RequestMapping("/c2")
public String c2(@CookieValue("java") String java){
return "java:" + java;
}
}
2、接收session
首先设置session
java
@RequestMapping("/request")
@RestController
public class RequestController {
@RequestMapping("/s1")
public String s1(HttpServletRequest request){
HttpSession session = request.getSession();
session.setAttribute("name","zhangsan");
return "设置会话成功!";
}
}
接收session方法一
java
@RequestMapping("/request")
@RestController
public class RequestController {
@RequestMapping("/s2")
public String s2(HttpServletRequest request){
HttpSession session = request.getSession();
String username = (String)session.getAttribute("name");
return "登录用户" + username;
}
}
接收session方法二
java
@RequestMapping("/request")
@RestController
public class RequestController {
@RequestMapping("/s3")
public String s3(@SessionAttribute(value = "username",required = false)String username){
return "登录用户" + username;
}
}
}
3、接收header
接收方法一
java
@RequestMapping("/request")
@RestController
public class RequestController {
@RequestMapping("/h1")
public String getHeader1(HttpServletRequest request){
String userAgent = request.getHeader("User-Agent");
return "userAgent: " + userAgent;
}
}
接受方法二
java
@RequestMapping("/request")
@RestController
public class RequestController {
@RequestMapping("h2")
public String getHeader2(@RequestHeader("User-Agent") String userAgent){
return "userAgent: " + userAgent;
}
}