Filters vs Interceptors in Struts 2

后端 未结 6 1730
后悔当初
后悔当初 2021-01-31 04:29

What\'s the difference, really, between filters and interceptors? I realize that interceptors fire before and after an action, recursively, and filters can be configured to fir

6条回答
  •  天涯浪人
    2021-01-31 05:27

    As a rule of thumb

    • Filters are run before each request. The struts itself is a filter.
    • interceptors can run before, after struts actions. They will not run if the request does not end with .action.

    So, some example of filters could be:

    • If you want to compress your js and css files, you should go for filters not interceptors.
    • If you want only certain IP address access your web site you must develop it as filter and check request ip address.
    • If you want to safe your site against CSRF attack you must write a filter to check CSRF token on requests.
    • If you want to log your site response per request time, you can use a filter to calculate the time before and after chain.doFilter(request, response)

    Theoretically you can develop an struts web application without developing your own interceptors and using filtersonly. But you will face lots problem and code boiler filters.

    Lots of struts 2 features are build with interceptors, you can find it in struts-default.xml (https://struts.apache.org/docs/struts-defaultxml.html) the list will help to find when interceptors can be used. (For example ParametersInterceptor runs before actions to apply submited form values to actions)

    While working with interceptors you can easily access struts features, for example getText from message resources, get current action name and name space, change the action flow.

    Considering above here are some cases which can be developed by interceptors:

    • If you want that only logged in users can access certain actions, you must develop it with interceptors.
    • If you want to keep track which actions user is navigation. You can use an interceptor to keep track of visited actions.
    • If you want to handle your action errors in a single point, you can use an interceptor which catch all invocation.invoke()

    The interceptors are providing the filter and Chain of Responsibility design pattern for struts actions, while filters provide this pattern to your whole web application.

提交回复
热议问题