Java filter to redirect users who are not logged in to the login page

I tried to create a filter to stop users who are not logged in from accessing certain pages. To do this, I created a filter class with the following methoddoFilter

HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String url = request.getRequestURI();
boolean allowedRequest = false;

System.out.println(url);

if(urlList.contains(url)) {
    allowedRequest = true;
    System.out.println("in list");
}

if (!allowedRequest) {
    Object o = request.getSession().getAttribute("UserInfo");
    if (null == o) {
        System.out.println("Hey i am in");
        response.sendRedirect("/login.jsp");
    }
}

chain.doFilter(req, res);

} // end of doFilter

To allow pages that the user does not need to log in, I created the url list of arraylist in init ()

. , home.jsp dcr.jsp. home.jsp , login.jsp, dcr.jsp, , if (null == o), , . , ,

/dcrmaintenance.jsp

Hey i am in

, null == o .

dcr.jsp , , java.lang.NullPointerException , , . - pt out, , .

+3
4

response.sendRedirect("/login.jsp"); return;.

+9

, sendRedirect doFilter. .

if (requiresLogin)
  response.sendRedirect("/login.jsp");
else
  chain.doFilter(req,resp);
+3
chain.doFilter(req, res);

? , . , . , .

Java WebApp web.xml. .

:

<security-constraint>
  <web-resource-collection>
     <web-resource-name>Restricted Area</web-resource-name>
     <url-pattern>*</url-pattern>
  </web-resource-collection>
  <auth-constraint>
     <role-name>Authorized</role-name>
  </auth-constraint>
</security-constraint>
0
source

I think you need to change your web.xml ... you should put limited resources in the appropriate folder. Thus, the Filter Servlet will limit the files that are allocated in the "restricted" folder. ( http://www.developer.com/security/article.php/3467801/Securing-J2EE-Applications-with-a-Servlet-Filter.htm ) (And I think the reason for using Filter Servlet is writing its own authorization system - thus, you should not define your security restrictions in web.xml, you should define it in the database;))))

<!--Servlet Filter that handles site authorization.-->
<filter>
     <filter-name>AuthorizationFilter</filter-name>
     <filter-class>examples.AuthorizationFilter</filter-class>
     <description>This Filter authorizes user access to application
                  components based upon request URI.</description>
     <init-param>
        <param-name>error_page</param-name>
        <param-value>../../login.html</param-value>
     </init-param>
</filter>

<filter-mapping>
     <filter-name>AuthorizationFilter</filter-name>
     <url-pattern>/restricted/*</url-pattern>
</filter-mapping>
0
source

All Articles