Generate a new session Id

眉间皱痕 提交于 2019-12-23 22:08:11

问题


How to generate new session id with out extends HttpServlet class. Is it mandatory to extend HttpServlet class & Is it mandatory to genarate new session id with in doGet method

public class LoginSupport extends ActionSupport {

    public void prepare() {
        HttpSession session = ServletActionContext.getRequest().getSession();
        session.invalidate();
        //How to genarate new session id
    }
}

回答1:


After calling HttpSession#invalidate(), you can create a new session by calling HttpServletRequest#getSession().

For example

public void prepare() {
    final HttpServletRequest request = ServletActionContext.getRequest();
    request.getSession().invalidate();

    // generate new session (and id)
    final HttpSession newSession = request.getSession();
}

The next HTTP response from your server should include a new session ID, eg

Set-Cookie: JSESSIONID=6a303082951311647336934;path=/

From https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html#getSession--

getSession

HttpSession getSession()

Returns the current session associated with this request, or if the request does not have a session, creates one.




回答2:


When on Servlet 3.1 or newer (Java EE 7), just use HttpServletRequest#changeSessionId().

request.changeSessionId();

It won't invalidate the session but just change the value of the JSESSIONID cookie.



来源:https://stackoverflow.com/questions/48899358/generate-a-new-session-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!