Java filter,

Source: Internet
Author: User

Java filter,
Java Filter usage

Filter

A filter is a filter between client and server resource files. before accessing a resource file, you can use a series of filters to modify and determine the request, blocks or modifies requests that do not comply with the rules. You can also filter, intercept, or modify the response.

 

 

The request sent by the browser is first submitted to the first filter for filtering. If the rule is met, the request is released and submitted to the next filter in the filter chain for filtering.The order of the filter in the chain is related to the order it is configured in web. xml.In front of the chain. When the request passes all the filters in the chain, it can access the resource file. If the request fails, it may be processed in an intermediate filter.

In the doFilter () method, the filtering operation before chain. doFilter () is generally performed on the request. The code after chain. doFilter is generally the operation performed on response.The execution sequence of the filter link code is as follows:

Filters are generally used for login permission verification, resource access permission control, sensitive word filtering, character encoding conversion, and other operations to facilitate code reuse without the need to perform operations in each servlet.

The following is a simple application of filters:

1: Create a filter

Create a new class to implement the Filter interface (Note: it is the Filter in javax. servlet ).

2: override the doFilter (request, response, chain) method of the filter. The other two init () and destroy () methods do not need to be overwritten. Filter in the doFilter method.

Common Code: GET request, get response, get session, and release.

The rest of the code is to filter and set the encoding format based on the session attribute, depending on the situation.

HttpServletRequest request = (HttpServletRequest) arg0; // obtain the request object HttpServletResponse response = (HttpServletResponse) arg1; // obtain the response object HttpSession session = request. getSession (); // obtain the session object

Filter operation code ......

Chain. doFilter (request, response); // pass through the current filter and submit it to the next filter for filtering

3: configure the filter in web. xml. Keep in mind one principle: in web. xml, listeners> Filters> servlets. That is to say, the listener in web. xml is configured before the filter, and the filter is configured before the servlet. Otherwise, an error occurs.

<Filter> <filter-name> loginFilter </filter-name> // filter name <filter-class> com. ygj. control. loginFilter </filter-class> // package path of the filter class <init-param> // optional <param-name> parameter name </param-name> // filter initialization parameter <param-value> parameter value </param-value> </init-pamm> </filter>
<Filter-mapping> // filter ing <filter-name> loginFilter </filter-name> <url-pattern> specifies the object to which the filter works </url-pattern>

Note the following two points in configuration: <filter-class> specifies the path of the package where the filter class is located. The second is the object where the filter is defined at <url-pattren>. Generally, there are the following rules:

1: function and all web resources: <url-pattern>/* </url-pattern>. When the client requests access to any resource file, it must be filtered by the filter. If the request passes, the file will be accessed; otherwise, the file will be intercepted.

2: apply to all files in a folder: <url-pattern>/dir/* </url-pattern>

3: Apply to a certain type of file: <url-pattern> *. Extension </url-pattern>. For example, <url-pattern> *. jsp </url-pattern> filters all access requests to jsp files.

4: Apply to a file type in a folder: <url-pattern>/dir/*. Extension </url-pattern>

If a filter needs to filter multiple files, you can configure multiple <filter-mapping>, and a mapping defines a url-pattern to define filter rules.

   <filter>      <filter-name>loginFilter</filter-name>      <filter-class>com.ygj.control.loginFilter</filter-class>  </filter>  <filter-mapping>      <filter-name>loginFilter</filter-name>      <url-pattern>*.jsp</url-pattern>  </filter-mapping>  <filter-mapping>      <filter-name>loginFilter</filter-name>      <url-pattern>*.do</url-pattern>  </filter-mapping>

Example 1: Use a filter for Logon verification. If you do not log on, the access request is rejected and redirected to the logon page.

Public void doFilter (ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) arg0; response = (response) arg1; HttpSession session = request. getSession (); String path = request. getRequestURI (); Integer uid = (Integer) session. getAttribute ("userid"); if (path. indexOf ("/login. jsp ")>-1) {// Login The recorded page does not filter arg2.doFilter (arg0, arg1); // submit it to the next filter return;} if (path. indexOf ("/register. jsp ")>-1) {// The registration page does not filter arg2.doFilter (request, response); return;} if (uid! = Null) {// you have logged on to arg2.doFilter (request, response); // pass the request and submit it to the next filter} else {response. sendRedirect ("login. jsp ");}}

Example 2: Set character encoding

public void doFilter(ServletRequest request, ServletResponse response,            FilterChain chain) throws IOException, ServletException {          HttpServletRequest request2=(HttpServletRequest) request;          HttpServletResponse response2=(HttpServletResponse) response;                    request2.setCharacterEncoding("UTF-8");            response2.setCharacterEncoding("UTF-8");                     chain.doFilter(request, response);     }

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.