Java servlet Filter Example

Source: Internet
Author: User

Servlet filter Introduction
Servlet filters are actually a standard java class. This class obtains the Filter function by implementing the Filter interface. It is loaded by the system through the web. xml configuration file when the jsp Container is started.
The Servlet filter is called when a user request is received. When the server receives a user request, it calls the configured filter in sequence. After the configuration, the requested servlet is executed, the servlet response after execution is first sent to the user through the configured filter.

Filter usage:
1. user authentication and authorization management.
2. Calculate the access traffic and access hit rate of web applications and generate an Access Report.
3. Implement the log processing function of web applications.
4. data compression.
5. encrypt the transmitted data.
6. Implement XSLT conversion for xml files.
A servlet filter is actually a java class. Its implementation needs to be divided into two parts: java class itself and xml description in the web. XML file. For the filter interface, this interface is composed of a pair of described life cycle Methods init (), destroy (). The init method is called when the server initializes the filter, the destory method is called when the server is shut down. Another behavior method, doFilter, is called when a filtering operation is executed.

Servlet filter configuration
The Servet filter must be deployed to the application through the web application deployment descriptor file web. xml. The configuration is as follows:

Copy codeThe Code is as follows:
<Filter>
<Filter-name> Filtername </filter-name>

<Filter-class> com. filter. Filter/class </filter-class>

<Init-param>
<Param-name> file </param-name>
<Param-value> filename </param-value>
</Init-param>
</Filter>

<Filter-mapping>
<Filter-name> Filtername </filter-name>
<Url-pattern>/* </url-pattern>
</Filter-mapping>

The following is an example:

Use filters to solve Chinese Encoding Problems:
Because java's default encoding method is ISO-8859-1, and usually when writing Chinese applications are using GB2312 or gbk encoding. In this case, you should use the <% @ page contentType = "text/html; charset = gbk" %> command in the header of the page to specify the page encoding method. In this way, the Chinese page is displayed normally. However, if the form is in the sheet. For example, an input box, if a visitor enters Chinese in it and submits it to a servlet for processing, java will first encode the text in the default way of ISO-5589-1, and then hand it to servet for processing, the processed text will still be in the ISO-5589-1 encoding mode village, if this text returns a page displayed according to GBK encoding at this time, due to the different encoding formats, obviously, the results cannot be correctly displayed.
There are many solutions for encoding methods. Here we mainly introduce how to use filters to solve Chinese Encoding Problems:

Copy codeThe Code is as follows:
Public class CharacterEncodingFilter implements Filter {
Private FilterConfig config;
Private String encoding = "ISO8859_1 ";
Public void destroy (){

Config = null;

}

Public void doFilter (ServletRequest request, ServletResponse response,

FilterChain chain) throws IOException, ServletException {

Request. setCharacterEncoding (encoding );

Chain. doFilter (request, response );

}

Public void init (FilterConfig config) throws ServletException {

This. config = config;

String s = config. getInitParameter ("encoding ");

If (s! = Null ){

Encoding = s;

}

}

}

Then in the XML Configuration:

 Copy codeThe Code is as follows:
<Filter>

<Filter-name> encodingFilter </filter-name>

<Filter-class> com. filter. CharacterEncodingFilter </filter-class>

<Init-param>

<Param-name> encoding </param-name>

<Param-value> UTF-8 </param-value>

</Init-param>

</Filter>

<Filter-mapping>

<Filter-name> encodingFilter </filter-name>

<Url-pattern>/* </url-pattern>

</Filter-mapping>
 

Finally, is the compilation of encoding. jsp?

 Copy codeThe Code is as follows:
Username: <c: out value = "$ {param. username}" default = "none"> </c: out> <br>

Password: <c: out value = "$ {param. userpassword}" default = "none"> </c: out> <br>

<Form action = "MyJsp. jsp" method = "post">

Username: <input type = "test" name = "username"> <br>

Password: <input type = "password" name = "userpassword"> <br>

<Input type = "submit" value = "submit">

</Form>
 

Start tomcat, access encoding. jsp, and enter "zhangshan". After the filter is passed, the page will display the server's outgoing information normally...

Use a filter to record user access logs
For some projects, it requires detailed records for each user access. This is a good solution to log recording. Using a filter, you can easily record each user's access. However, when a visitor Accesses Different pages at the same time, the log cannot be recorded repeatedly. Otherwise, the log will fill the server's hard disk space in a short time. So here we can use the session object to determine each session of the user. In a session, the filter will only record once.
Write the LogFilter class below. This filter is mainly used to record user access records:

Copy codeThe Code is as follows:
Package com. filter;

Import java. io. File;
Import java. io. IOException;
Import java. io. RandomAccessFile;

Import java. text. SimpleDateFormat;
Import java. util. Date;
Import javax. servlet. Filter;
Import javax. servlet. FilterChain;
Import javax. servlet. FilterConfig;
Import javax. servlet. ServletException;
Import javax. servlet. ServletRequest;
Import javax. servlet. ServletResponse;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpSession;

Import com.sun.org. apache. bcel. internal. generic. NEW;

Public class LoginFilter implements Filter {

Private FilterConfig config = null;
Private String filename = null;
Private String filtername = null;
Public void destroy (){
This. config = null;
This. filename = null;
This. filtername = null;
}

Public void doFilter (ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest hRequest = (HttpServletRequest) request;
// Obtain the session object
HttpSession session = hRequest. getSession ();
// First determine whether the LOGGED value in the session exists. If no value exists, it indicates a new request.
If (null = session. getAttribute ("LOGGED ")){
Session. setAttribute ("LOGGED", "yes"); // set the value of LOGGED to yes to prevent repeated records of the same session
File file = new File (this. filename );
If (! File. exists ())
File. createNewFile (); // determines whether the file exists. If it does not exist, a new

/*
* Create a log record. The logContent includes the visitor's IP address, access page URL, access time, and log Filter Name.
*/
String logContent = hRequest. getRemoteHost () + "->" + hRequest. getRequestURI () + "Logged" + getTime () + "By s" + this. filtername + "\ r \ n ";
RandomAccessFile rf = new RandomAccessFile (this. filename, "rw"); // create a random file operation object
Rf. seek (rf. length (); // point the write pointer to the end of the file, rf. length () gets the length of the file. The length of the seek file is exactly the end of the file.
Rf. writeBytes (logContent); // write logs to files.
Rf. close (); // close the file
}
Chain. doFilter (request, response );
}

Public void init (FilterConfig config) throws ServletException {
This. config = config;
This. filename = this. config. getInitParameter ("file ");
This. filtername = this. config. getFilterName ();
}

// Obtain the time
Private String getTime (){
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd-HH-mm-ss ");
Return sdf. format (new Date ());
}

}

Here, the session is used to limit that the same session will only record the log once. No matter how many pages are accessed by the visitor in this session, during the first access, because the LOGGED of the session is empty, therefore, logs are recorded at this time and LOGGED is set to yes, so that logs are not recorded during the second judgment.
Then, configure XML:

Copy codeThe Code is as follows:
<Filter>
<Filter-name> LogFilter </filter-name>
<Filter-class> com. filter. LoginFilter </filter-class>
<Init-param>
<Param-name> file </param-name>
<Param-value> D:/log.txt </param-value>
</Init-param>
</Filter>

<Filter-mapping>
<Filter-name> LogFilter </filter-name>
<Url-pattern>/* </url-pattern>
</Filter-mapping>

After the XML file is configured, access to any file under the directory will be able to get the visitor's record in the D:/log.txt file.

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.