Reputation: 3225
I have this controller
@Controller
@RequestMapping(value = "/login")
public class Login{
@RequestMapping
public ModelAndView mainPage(HttpServletRequest request){
request.getSession().setAttribute("testSession", "Session test");
return new ModelAndView("/login");
}
@RequestMapping(value = "/check")
public View check(HttpServletRequest request){
System.out.println(request.getSession(false)); //null
return new RedirectView("/login");
}
}
When access /login
I create a session and add an attribute "testSession"
into it: request.getSession().setAttribute("testSession", "Session test");
On page /login
have this <form action="/login/check" method="post">
.
On /login/check
I try to get session created on /login
, but it is null.
Why session not persist between requests?
P.S.: My app run on Remote Server with Tomcat and Apache as revers proxy and I access my app via https://mydom.com
UPDATE
I created a controller to test session:
@Controller
@RequestMapping(value = "/sess")
public class TestSession{
@RequestMapping(method = RequestMethod.GET)
public void mainPage(HttpServletRequest request, HttpServletResponse response) throws IOException{
//get or create session
HttpSession session = request.getSession();
response.setContentType("text/html");
response.getWriter().println(session.getId());
}
}
At every request to /sess
it's printed another id.
Upvotes: 0
Views: 4423
Reputation: 3225
The real problem was at JSessionID path.
The path of JSessionID was /myapp
. That was result of Tomcat, because my app normaly run under mydom.com:8080/myapp
But with Apache as reverse proxy, I run my app directly from mydom.com/
, which make JSessionID
invalid because I'm not on mydom.com/myapp
.
So I added a new line in virtual host from Apache(where is setted reverse proxy) to change the path of cookies:
ProxyPassReverseCookiePath /myapp /
This is my final VirtualHost
and now Session persist between requests.
<VirtualHost *:80>
ServerName mydom.com
ProxyRequests Off
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:8080/myapp/
ProxyPassReverse / http://127.0.0.1:8080/myapp/
ProxyPassReverseCookiePath /myapp /
</VirtualHost>
Upvotes: 5
Reputation: 134
Are you using spring security? May be you can set
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER)
if you are managing sessions by yourself
Reference: https://www.baeldung.com/spring-security-session
Upvotes: 0