Generate a new session Id

3.7k Views Asked by At

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
    }
}
2

There are 2 best solutions below

10
Phil On

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.

0
BalusC On

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.