Detailed description of Servlet filters and servletfilter

Source: Internet
Author: User

Detailed description of Servlet filters and servletfilter

I. Basic working principles of filters

1. Basic working principles of filters

The basic working principle of the filter is 4-8.


2. Filter features
Filters have the following features:
(1) It is declarative.
(2) It is dynamic
(3) It is modular
(4) It is portable.
(5) It is reusable.
(6) It is transparent.


Ii. Filter API interfaces and deployment information
1. javax. servlet. Filter Interface
(1) public void init (FilterConfig filterConfig) throws ServletException
Initialize the init () method.
(2) public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws java. io. IOException, ServletException
The Service Logic code of the filter is implemented in the doFilter () method.
(3) public void destroy ()
Before a filter object is destroyed, this method is called to release the resources applied in init (). The execution of this method indicates that the life cycle of a filter ends.

2. javax. servlet. FilterConfig Interface
(1) public java. util. Enumeration getInitParameterNames ()
Read the variable name of the initialization parameter to the enumerated object.
(2) public java. lang. String
GetInitParameter (java. lang. String name)
Reads the initialization parameter value of the specified variable name. If this parameter is not available, Null is returned.
(3) public ServletContext getServletContext ()
Obtain the ServletContext object of the current Web application.

3. javax. servlet. FilterChain Interface
The key methods in the interface are:
Public void doFilter (ServletRequest request,
ServletResponse response) throws java. io. IOException, ServletException

4. Filter deployment
The process of deploying a filter in WEB-INF \ web. xml is: Register filter, ing filter
(1) register the filter
The filter is loaded and run by the container only after it is registered in the Web application. The following describes how to register a filter in web. xml:

<Filter>
<Filter-name> my1 </filter-name>
<Filter-class> com. abc. mis. Filter1 </filter-class>
<Init-param>
<Param-name> password </param-name>
<Param-value> 123 </param-value>
</Init-param>
</Filter>

The container creates a filter instance for a <filter> </filter> element. The same filter class can generate multiple instances, you only need to deploy multiple <filter> </filter> elements, for example:
<Filter>
<Filter-name> my1 </filter-name>
<Filter-class> com. abc. mis. Filter1 </filter-class>
<Init-param>
<Param-name> password </param-name>
<Param-value> 123 </param-value>
</Init-param>
</Filter>

(2) ing filter
Filter ing is the activation condition for defining this filter. It is generally defined by the URI mode of the target resource and the request type. You can use the wildcard "*" in the URI to express the request URI mode. The basic method of filter ing is as follows:
<Filter-mapping>
<Filter-name> my1 </filter-name>
<Url-pattern>/test/* </url-pattern>
<Dispatcher> REQUEST </dispatcher>
<Dispatcher> FORWARD </dispatcher>
</Filter-mapping>


3. the first filter program
The basic programming process of the filter is:
Step 1: Edit and compile the filter program, publish the package folder and *. class to the root \ WEB-INF \ classes folder.
Step 2: edit the WEB-INF \ web. xml file to add deployment information for the filter.
Step 3: restart Tomcat or reload the Web application to make the filter take effect.

[Example]: Define three filters:
If filter 1 is activated when a user accesses resources under "/test", it determines whether the user has logged on. If no logon is performed, the request is interrupted and Error 404 is returned, if you have logged on, the request is forwarded to the next filter.
Define filter 2. When the request "/*" resource is requested and the request comes from the client, it is activated, a prompt is displayed, and the request is forwarded to the next filter.
The function of filter 3 is the same as that of filter 2, but its REQUEST type is REQUEST or FORWARD.

The procedure is as follows:
(1) Start JC4, create a class "Filter1", and enter the following code in the code editing window:

<Span style = "font-family: SimSun;"> <span style = "font-family: FangSong_GB2312; font-size: 14px;"> package my; import java. io. *; import javax. servlet. *; import javax. servlet. http. *; public class Filter1 implements Filter {private FilterConfig config = null; public void init (FilterConfig config) throws ServletException {this. config = config;} public void destroy () {config = null;} public void doFilter (Ser VletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {response. setCharacterEncoding ("GB2312"); PrintWriter out = response. getWriter (); HttpSession session = (HttpServletRequest) request ). getSession (); System. out. println ("filter 1 works, the request is forwarded to the next processing .. "); out. print ("<br> information added by filter 2 before the request reaches the target resource <br>"); String loginStatus = (String) session. getAttribute ("loginName"); if (loginS Tatus = null) {out. print ("<br> you have not logged in and no room is available to access resources! <Br> "); return;} else chain. doFilter (request, response); System. out. println ("the output information of the target resource is returned to the filter 1... "); out. print ("<br> the information added by filter 2 when the output information of the target resource is returned <br>") ;}</span> </span>

(2) Compile the Filter1 program. After successful, the Filter1.class file will be automatically stored in the c: \ tomcat \ webapps \ ROOT \ WEB-INF \ classes folder, use "my computer" to view and verify.
(3) Start JC4, create a class named "Filter2", and enter the following code in the code editing window:

<Span style = "font-family: SimSun;"> <span style = "font-family: FangSong_GB2312; font-size: 14px;"> package my; import java. io. *; import javax. servlet. *; import javax. servlet. http. *; public class Filter2 implements Filter {private FilterConfig config = null; public void init (FilterConfig config) throws ServletException {this. config = config;} public void destroy () {config = null;} public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {response. setCharacterEncoding ("GB2312"); PrintWriter out = response. getWriter (); System. out. println ("filter 2 works, the request is forwarded to the next processing .. "); out. print ("<br> information added by filter 2 before the request reaches the target resource <br>"); chain. doFilter (request, response); </span> <pre name = "code" class = "java"> <span style = "font-family: FangSong_GB2312; font-size: 14px; "> <span style =" white-space: pre "> </span> System. out. println ("the output information of the target resource is returned to the filter 2... "); out. print ("<br> information added by filter 2 when the output information of the target resource is returned <br>"); </span>
}}

 

(4) Compile the Filter2 program. (5) Start JC4, create a class named "Filter3", and enter the following code in the code editing window:

<Span style = "font-family: SimSun;"> <span style = "font-family: FangSong_GB2312; font-size: 14px;"> package my; import java. io. *; import javax. servlet. *; import javax. servlet. http. *; public class Filter3 implements Filter {private FilterConfig config = null; public void init (FilterConfig config) throws ServletException {this. config = config;} public void destroy () {config = null;} public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, servletException {</span> <pre name = "code" class = "java"> <span style = "font-family: FangSong_GB2312; font-size: 14px; "> <span style =" white-space: pre "> </span> System. out. println ("filter 3 works, the request is forwarded to the next processing .. "); out. print ("<br> information added by filter 3 before the request reaches the target resource <br>"); chain. doFilter (request, response); </span> <pre name = "code" class = "java"> <span style = "font-family: FangSong_GB2312; font-size: 14px; "> <span> </span> System. out. println ("the output information of the target resource is returned to the filter 3... "); out. print ("<br> information added by filter 3 when the output information of the target resource is returned <br>"); </span>

}} 
(6) Compile the Filter3 program. 

(7) Deploy the above three filters to get a filter chain: filter 3 → filter 1 → filter 2.
Edit the WEB-INF \ web. xml file and add the following deployment information:




(8) define JSP resources for the experiment. Start DW8 and complete the following tasks:
Create exam406.jsp and enter the prompt text "current is/exam406.jsp resource" in the design view ".
Create exam407.jsp and enter the following code in the Code view:
<Body>
<%
Session. setAttribute ("loginName", "tom ");
Out. print ("successfully logged on, you can access resources under/test! ");
%>
</Body>

Create exam408.jsp. In the design view, insert the "ROOT \ tomcat.gif" Image in the site to the document.
Create a new/test sub-folder under the root folder of the site.
Create an index. jsp file in the/test folder and enter the text "/test Homepage" in the design view ".
Create exam409.jsp and enter the following code in the Code view:

<Body>
<%
RequestDispatcher go = application. getRequestDispatcher ("/exam406.jsp ");
Go. forward (request, response );
%>
</Body>
(9) start Tomcat and complete the test on your own.




Create a Servlet Filter

Public class IPFilter implements Filter {
Public void destroy (){
}
Public void doFilter (ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) arg0;
String ip = req. getRemoteAddr ();
If ("192.168.70.88". equals (ip )){
Req. getRequestDispatcher ("error. jsp ");
// Arg2.doFilter (arg0, arg1 );
}
Req. getRequestDispatcher ("success. jsp ");
}
Public void init (FilterConfig arg0) throws ServletException {
}
}

Java filter can filter all servlets in a certain package?

The filter expression is skipped when the end of jsp is detected in the Code *. Otherwise, the processing is performed.
 

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.