Search code examples
phpjspheaderauthenticationjspinclude

php's Header equivalent in JSP


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>

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.