问题
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