Evgeniy
Evgeniy

Reputation: 171

Understanding of url-patterns in web.xml

I was really confused by this parts of web.xml:

<filter>
    <filter-name>filter</filter-name>
    <filter-class>com.labwork.filter.Filter</filter-class>
</filter>

<filter-mapping>
    <filter-name>filter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

This is the real problem. For example, I have several Servlets and static html pages. All request to them pass through filter. May be, i want to forward to servlet/html page from filter. How can i do this, if all request will be forward to filter? Or, may be, i don't understand principles.

Upvotes: 0

Views: 652

Answers (2)

ayip
ayip

Reputation: 2543

If you want to specify which servlet/html the request should be forwarded to, you can add <servlet-name> and <servlet-mapping> sections in your web.xml.

For example:

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>examples.Login</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>

OR

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <jsp-file>/login.html</jsp-file>
</servlet>

<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>

Upvotes: 1

lxcky
lxcky

Reputation: 1668

Based on our conversation in the comment section, you want to filter every request with an exception of a few pages.

Let's say you want to exempt the login.html from filtering, what you could do is get the request URI and check if that string contains login.html like this:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {                
    String path = ((HttpServletRequest) request).getRequestURI();
    if (path.contains("login.html")) //login page                                                
        chain.doFilter(request, response); //proceed to the page
    } else {            
        //conditions here
    }
}

I must state though that this is not the standard practice. If you're doing this then you should review your design choices.

Upvotes: 1

Related Questions