spring boot演示处理session

一、session原理

原理

1. 客户端请求服务端,服务端发回响应(包含sessionId)给客户端

【实操】

/**
 * 打印HttpHeaderss
 * @param headers
 */
private void printHeaders(HttpHeaders headers){
    Iterator,List>> iter = headers.entrySet().iterator();
    while(iter.hasNext()){
        Map.Entry,List> entry = iter.next();
        System.out.println(entry.getKey()+":"+entry.getValue());
    }
}

打印Response的HttpHeaders,结果:

Set-Cookie:[JSESSIONID=3CF70F4C94F002A3C0F28B351A795250; Max-Age=28800; Expires=Thu, 01-Mar-2018 17:21:03 GMT; Path=/; HttpOnly]
Content-Type:[text/plain;charset=UTF-8]
Content-Length:[6]

结果中JSESSIONID就是sessionId

2. 客户端在第二次请求中,在Cookie中加入sessionId,发送给服务端

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
//将登录的Set-Cookie的值写入Cookie中
headers.set("Cookie",cookie);
cookie中写入
JSESSIONID=3CF70F4C94F002A3C0F28B351A795250

3. 服务端在第二次请求时,拿到的sessionId就是客户端传过来的sessionId

4. 属性

Max-Age:浏览器拿到sessionId后,通过服务端传过来的Max-Age来指定sessionId存活的描述

timeout:服务端sessionId超时的秒数,超过指定的秒数,则sessionId失效。

二、 构建服务端

创建spring-boot项目,创建AccountController类

package cn.taonc.demo.resttemplatesession.controller;

import cn.taonc.demo.resttemplatesession.model.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
public class AccountController {

    private Map,User> userMap = new HashMap<>();

    /**
     * 登录
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/account/login")
    public String login(HttpServletRequest request,User user){
        //request.getSession(true)强制获取session,否则session有可能为null.
        //request.getSession()在第一个请求返回时,才产生
        String sessionId = request.getSession(true).getId();
        //验证用户名和密码
        if("admin".equals(user.getName()) && "admin".equals(user.getPassword())){
            //将用户存入Map, sessionId为键值
            userMap.put(sessionId,user);
            return "Succss";
        }
        return "Failed";
    }

    /**
     * hello
     * @param request
     * @return
     */
    @GetMapping("/account/hello")
    public String hello(HttpServletRequest request){
        String sessionId = request.getSession(true).getId();
        if(!userMap.containsKey(sessionId)){
            return "请登录";
        }else{
            return "欢迎您:"+userMap.get(sessionId).getName() + "!";
        }
    }
}

application.properties配置

server.port=8081
server.session.cookie.max-age=28800
server.session.timeout=28800


三、 写RestTemplate客户端测试

package cn.taonc.demo.resttemplatesession.controller;

import org.junit.Test;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class AccountControllerTest {

    private RestTemplate restTemplate = new RestTemplate();

    /**
     * 没有session情况下的请求
     */
    @Test
    public void helloTestNoSession(){
        String url = "http://localhost:8081/account/hello";
        String res = restTemplate.getForObject(url,String.class);
        System.out.println(res);
    }

    /**
     * 有session的情况下的请求
     */
    @Test
    public void helloTestWithSession(){
        String url = "http://localhost:8081/account/login";
        //登录
        ResponseEntity loginRes = login(url);
        //从登录的结果中提取header:Set-Cookie
        String cookie = getCookie(loginRes);

        String url2 = "http://localhost:8081/account/hello";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //将登录的Set-Cookie的值写入Cookie中
        headers.set("Cookie",cookie);

        HttpEntity httpEntity = new HttpEntity(null,headers);
        ResponseEntity linkListRes = restTemplate.exchange(url2, HttpMethod.GET,httpEntity,String.class);
        System.out.println(linkListRes.getBody());
    }

    private ResponseEntity login(String url){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap, String> map= new LinkedMultiValueMap, String>();
        map.add("name", "admin");
        map.add("password", "admin");

        HttpEntity, String>> request = new HttpEntity, String>>(map, headers);
        ResponseEntity responseEntity = restTemplate.postForEntity(url,request,String.class);
        return responseEntity;
    }

    private String getCookie(ResponseEntity responseEntity){
        List cookies = responseEntity.getHeaders().get("Set-Cookie");
        System.out.println("Set-Cookie:"+cookies);
       return cookies.get(0);
    }
}
 
  

测试结果(helloTestNoSession):

请登录

测试结果(helloTestWithSession):

欢迎您:admin!







你可能感兴趣的:(java,session,spring,boot)