Reputation: 7953
how to redirect to a login page if the user is not logged in using servlet.
I have a login page user logs in using that and goes to home page,after navigating the user clicks on logout and just hits on back button in browser now the page goes to previously visited page, how to redirect the user to login page when using servlet?
thanks for the help and continued support
Upvotes: 1
Views: 11484
Reputation: 15446
Ideally you should be doing this in Filter.
public void doFilter(.......){
if(user logged in){
filterChain.doFilter(...);
} else {
response.sendRedirect("/login.jsp");
}
}
I would suggest you to use Servlet Security Feature
which allows the container to care of Web Application Security
.
Upvotes: 1
Reputation: 859
Use servlet ,
In web.xml
<filter>
<filter-name>AuthenticationFilter</filter-name>
<filter-class>com.java.web.authentication.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>/faces/manage/*</url-pattern>
</filter-mapping>
In authentication filter ,
if (visit == null) {
servletContext.log("Redirecting to the login page.");
session.setAttribute(Constants.ORIGINAL_VIEW_KEY, requestPath);
String loginView = httpRequest.getContextPath() +
httpRequest.getServletPath() +Constants.LOGIN_PAGE;
httpResponse.sendRedirect(loginView);
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
Upvotes: 2
Reputation: 7899
You can validate user session in Servlet
and if session is invalid or session doesn't contain userId(if at the time of session Creation you set that in session Attribute ) then redirect it to login
page. to disable back you need to clear the cache using following code in jsp/servlet
.
response.setHeader("Cache-Control","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
Upvotes: 1
Reputation: 4532
Use the following code in your jsp at the top of the page
if(userName.length()==0 || userType.length()==0 ){
session.setAttribute("message", "Please Login");
response.sendRedirect(response.encodeRedirectURL(path+"/"+destination));
}
Upvotes: 2
Reputation: 17930
In your servlet doGet or doPost (whichever is called) you need to check if the user is logged in (I'm guessing you have the session checking mechanism) and if you see that the user is not logged in just use:
response.sendRedirect("/login.jsp");
Upvotes: 1