I have a requirement just like when user try to access any url in an application without logging into app
loggedin=false;
if(!loggedin)
{
forward request to login jsp page
}
else
{
execute the jsp
}
now login jsp will take and send the login credentials to controller servlet ,if login credentials were right the controller servlet has to send back the request to the url which was accessed by the user. I have tried to use redirect / forward but those weren't full fill the need.
Can i have some suggestion to achieve this
There are out of the box solutions for that in Spring Security or even Java EE Declarative Security.
Anyway if you want to achieve that behaviour it's as simple as storing in a Cookie the value of the original URL. Then, when the user logs in correctly you can redirect to that saved URL
boolean loggedin=false;
if(!loggedin){
Cookie c = new Cookie("URC", request.getPathInfo());
c.setHttpOnly(true);
c.setPath(request.getContextPath());
c.setMaxAge(-1);
response.addCookie(c);
//forward request to login jsp page
}else{
Cookie cookie = getUrlRedirectCookie(request);
if(cookie!=null){
//redirect to cookie.getValue()
}else{
//execute the jsp
}
}
}
private Cookie getUrlRedirectCookie(HttpServletRequest request){
Cookie[] cookies = request.getCookies();
if(cookies!=null && cookies.length>0){
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if(cookie.getName().equals("URC")){
return cookie;
}
}
}
return null;
}