0
votes

I am creating a simple web application using servlets and JSP. I am implementing a Filter which checks if the user has logged in already, literally checks if the user session is alive. If the session is not alive, then the user has to be redirected to the login page (index,jsp)

This is my filter mapping in the web.xml file

 <web-app xmlns...>
  <display-name>FilterTest</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <filter>
    <filter-name>LoginFilter</filter-name>
    <filter-class>LoginFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <servlet>
    <description></description>
    <servlet-name>LoginController</servlet-name>
    <servlet-class>LoginController</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginController</servlet-name>
    <url-pattern>/LoginController</url-pattern>
  </servlet-mapping>
</web-app>

When the user tries to access a different page, then the LoginFilter checks for the session. If the session is alive the user is redirected to the requested page else redirected to index.jsp.

The problem I am facing here is, the LoginFilter checks for the session even when the user is logging in ( request comes from the index.jsp which is the login page). So what I see here is, When the user logs in, the control goes to the LoginFilter, since the session is not yet created for this user, he is redirected back to login page which is creating a indefinite redirect loop.

I want to exclude the filter checking/session checking if the request is coming from index.jsp.

Is there any way in which I can accomplish this ? Or any way by which I can identify if the requesting page is index.jsp ?

UPDATE: The url when the application starts up is http://servername:port/FilterTest Here the index.jsp is loaded.

I am validating the login in LoginController servlet which redirects the user to home.jsp (welcome page) if the login was successful.

Thanks..!

1
can u post url for accessing landing page(which asks for login) and welcome page(successful login page)? please share these 2 urls - Pranalee

1 Answers

4
votes

Skip your Filter check for Login page

You need to check requestedUrl and see if it doesn't require Filter (for LoginPage, CSS, Images, JS) then simply do

chain.doFilter(request, response);  

Pass the init parameter to Filter from web.xml from init() create a List<String> urls which doesn't need filter check now in doFilter() check if URL is one of those then simply chain.doFilter(request, response);