According to Struts2 Budi Karnival struts2, there is one clear advantage to using a filter over a servlet as a controller. Using the filter, you can conveniently use all the resources of your application, including static ones.
With a servlet, your controller only handles access to the dynamic part of the application. Note that the url-pattern element in the web.xml file in the previous application
<servlet> <servlet-name>Controller</servlet-name> <servlet-class>...</servlet-class> </servlet> <servlet-mapping> <servlet-name>Controller</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping>
With this configuration, requests for static resources are not processed by the servlet controller, but by the container. You would not want to handle static resources in your servlet controller, because that would mean extra work.
The filter is different. A filter may allow you to skip requests for static content. To pass the request, call the filterChain.doFilter method in the filter doFilter method.
Therefore, using the filter as a controller allows you to block all requests to the application, including a request for static content. After that, the following parameter will be specified in the deployment descriptor:
<filter> <filter-name>filterDispatcher</filter-name> <filter-class>...</filter-class> </filter> <filter-mapping> <filter-name>filterDispatcher</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
The advantage of this filter: one thing is certain, you can easily protect your static files from prying eyes.
The following code will send an error message if the user tries to view the JavaScript file:
public void doFilter(ServletRequest request, ServletResponse response,FilterChain filterChain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; String uri = req.getRequestURI(); if (uri.indexOf("/css/") != -1 && req.getHeader("referer") == null) { res.sendError(HttpServletResponse.SC_FORBIDDEN); } else {
It will not protect your code from the most determined people, but users can no longer enter the URL of your static file to view it. In the same way, you can protect your images so that no one can link to them at their own expense.
Another advantage:
Implement Interceptors in the Struts2 framework. This not only reduces our coding efforts, but helps us write any code that we would use filters for coding and necessary changes in web.xml, and not Struts1.So now any code that is better suited for the filter can now be moved to interceptors (which is more manageable than filters), the entire configuration can be controlled in the struts.xml file, no need to touch the web.xml file