【Java】SpringMVC参数接收(三):cookie、session、header

1、接收cookie

(1)接收所有cookie

@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为空";
    }
}

【Java】SpringMVC参数接收(三):cookie、session、header_第1张图片

 【Java】SpringMVC参数接收(三):cookie、session、header_第2张图片

 【Java】SpringMVC参数接收(三):cookie、session、header_第3张图片

(2)接收单个cookie 

@RequestMapping("/request")
@RestController
public class RequestController {
    @RequestMapping("/c2")
    public String c2(@CookieValue("java") String java){
        return "java:" + java;
    }
}

【Java】SpringMVC参数接收(三):cookie、session、header_第4张图片

 2、接收session

首先设置session 

@RequestMapping("/request")
@RestController
public class RequestController {
    @RequestMapping("/s1")
    public String s1(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("name","zhangsan");
        return "设置会话成功!";
    }
}

【Java】SpringMVC参数接收(三):cookie、session、header_第5张图片

接收session方法一 

@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;
    }
}

【Java】SpringMVC参数接收(三):cookie、session、header_第6张图片

接收session方法二 

@RequestMapping("/request")
@RestController
public class RequestController {
    @RequestMapping("/s3")
    public String s3(@SessionAttribute(value = "username",required = false)String username){
        return "登录用户" + username;
    }
}
}

【Java】SpringMVC参数接收(三):cookie、session、header_第7张图片

 3、接收header

接收方法一

@RequestMapping("/request")
@RestController
public class RequestController {
    @RequestMapping("/h1")
    public String getHeader1(HttpServletRequest request){
        String userAgent = request.getHeader("User-Agent");
        return "userAgent: " + userAgent;
    }
}

接受方法二

@RequestMapping("/request")
@RestController
public class RequestController {
    @RequestMapping("h2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent){
        return "userAgent: " + userAgent;
    }
}

【Java】SpringMVC参数接收(三):cookie、session、header_第8张图片 

 

 

你可能感兴趣的:(Java,#,Java网络编程,java,前端,开发语言)