简体   繁体   中英

how to restric Servlet Mapping only for some extensions

I would like to use Cutome servlet only for url which are not having extensions like .jsp,jss,css and image extensions.

I tried like this but no use.

Web.xml :

<filter>
    <filter-name>ControllerFilter</filter-name>
    <filter-class>tut.controller.ControllerFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>ControllerFilter</filter-name>
    <servlet-name>ControllerServlet</servlet-name>
</filter-mapping>

<servlet>
    <servlet-name>ControllerServlet</servlet-name>
    <servlet-class>tut.controller.ControllerServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>ControllerServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

    <servlet>
    <servlet-name>FileServlet</servlet-name>
    <servlet-class>tut.controller.FileServlet</servlet-class>
</servlet>

Filter :

String requestedUri = ((HttpServletRequest)request).getRequestURI();
System.out.println("requestedUri:"+requestedUri);
if(requestedUri.matches(".*[css|jpg|png|gif|js|jsp]*")){
           //How to configure the default calling here
       return;
}
else 
{
  // ControllerServlet  for other requests
  chain.doFilter(request, response);
}

Try with $ that represents The end of a line in regex pattern

requestedUri.matches(".*[css|jpg|png|gif|js|jsp]$")

If matched then follow the chain otherwise forward the request to the required Servlet, JSP or HTML.

if (uri.matches(".*[css|jpg|png|gif|js|jsp]$")) {
    filterChain.doFilter(req, res);
}else{
    // forward the request to Servlet/JSP/HTML
    req.getRequestDispatcher("path").forward(req, resp);
}

web.xml:

use / as url pattern for filter to inspect all the request then based on uri forward it to Servlet/JSP/HTML in the filter itself.

<filter-mapping>
    <filter-name>ControllerFilter</filter-name>
    <servlet-name>/</servlet-name>
</filter-mapping>

Find a better solution here Servlet for serving static content

I don't think that Filter is a good mechanism for achieving what you want. If Filter gets a request for unwanted extensions, it's too late to deal with this.

You can modify your request and response in Filter to do pre-processing or post-processing, but it's probably not what you're looking for. You want those extensions not to be routed to the servlet at all , but rather be processed by a static content handler.

To do what you want you'll need to put your static content to a folder which is not under path that can match Servlet path, otherwise your servlet is going to get requests for the static content at which point you'll need to do something about those requests inside your servlet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM