当浏览器禁用了cookie,java实现传递JSESSIONID

当浏览器禁用了cookie,java实现传递JSESSIONID,代码如下:

代码块

package com.demo.springmvc.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 /**
  * 测试当浏览器关闭cookie 后
  * java 如何获取session
  * @author lz
  *
  */
@Controller
@RequestMapping("/test")
public class CookieSessionController {

    @RequestMapping("/createSession")
    public void hello4(HttpServletRequest request,HttpServletResponse response) throws IOException{
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        //request 获取session  
        HttpSession session = request.getSession();
        session.setAttribute("sessionAttr","当浏览器禁用了cookie,"
                + "利用response.encodeRedirectURL获取session的属性");
        String seesionId = "保存成功,当前sesionId:"+session.getId();
        //添加sessionID到cookie中
        Cookie cookie = new Cookie("JSESSIONID", session.getId());  
        //设置cookie存活时间,数字越大cookie保存时间越长
        cookie.setMaxAge(Integer.MAX_VALUE);
        //添加cookie到浏览器
        response.addCookie(cookie);
        out.println(seesionId);
        String url = response.encodeRedirectURL("/test/getSession");
        out.println("<a href='"+url+"'>hello</a>");
    }

    @RequestMapping("/getSession")
    public void hello(HttpServletRequest request,HttpServletResponse response) throws IOException {         
        response.setContentType("text/html;charset=utf-8"); 
        HttpSession session = request.getSession();

        String sessionAttr = (String)request.getSession().getAttribute("sessionAttr");  
        PrintWriter writer = response.getWriter();
        writer.write("当前sessionId:"+session.getId());   
        writer.write(sessionAttr);   
        PrintWriter out = response.getWriter();
        String url = response.encodeRedirectURL("/test/createSession");
        out.println("<a href='"+url+"'>createSession</a>");
    }

}
阅读更多
换一批

没有更多推荐了,返回首页