Question

in php i used to authenticate whether a user was logged in or not by checking the session for a member id, if set ok, else the page would be redirected via Header to the login page. this auth script was in auth.php and i used to include it in any page that required login. simple. however i cannot do the same in jsp. because the rest of the page which includes the auth.jsp gets loaded no matter what auth.jsp does. the auth.jsp is

<%
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
if (user == null) {
%>
<jsp:forward page="/index"/>
<%
return; 
}
%>

if the user is not logged in he still can see the original page below the login page. because of this i have to manually include the user checking using if else on every page, very inconvenient. any solutions?? the including page is

<jsp:include page="auth.jsp" />
<p>Welcome</p>
Was it helpful?

Solution

At the very least, you could write your own custom Servlet Filter. It gets called each time a request is made, without you having to do anything.

Also, you may want to look into something like Container level security, or evenSpring Security. Both handle this for you.

EDIT:

No problem.

In the mean time, you probably want to do something like this in auth.jsp

<%
  if (user == null){
    response.sendRedirect(redirectURL);
  }
%>

which is sort of like

response.addHeader("location", "/login.jsp");

which is sort of like what you're used to with PHP.

OTHER TIPS

A servlet filter is definitely what you're looking for. You can also grab container managed or spring security, but given your knowledge, those shall probably be some steps too far away to get a proper grasp.

Here's a basic example how the doFilter() method of your filter should look like:

if (UserServiceFactory.getUserService().getCurrentUser() != null) {
    chain.doFilter(request, response); // User is logged in, just continue request.
} else {
    ((HttpServletResponse) response).sendRedirect("/login.jsp"); // Not logged in, show login page. You can eventually show the error page instead.
}

Map this filter in web.xml on an url-pattern covering the pages you'd like to authenticate. E.g. /secured/*, /private/*, /authenticated/* etc, and place all JSPs (expect of the login page!) in the same folder.


As to why it fails in a JSP: that may happen when the response is already committed. If you have read the server logs, you should have seen IllegalStateException: Response already committed at the point <jsp:forward> is been called. That is works in PHP is probably because it has a larger response buffer or because that logic is by coincidence correctly called before any part of the response body, thus right before <!DOCTYPE> and so on. As long as the response is not committed, you can change its destination using forward or redirect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top