Java servlet Filter using sample _JSP programming

Source: Internet
Author: User

Introduction to the servlet filter
The servlet filter is actually a standard Java class that gets the function of the filter by implementing the Filters interface. It is loaded by the system through the Web.xml configuration file when the JSP container is started.
The servlet filter is invoked when a user request is received. When the server receives the user's request, the configured filter is invoked in turn, the servlet requested by the request is executed, and the response after the servlet executes is first sent to the user via the configured filter.

Use of filter:
1, user authentication and authorization management.
2, Statistics Web application access and access hit rate, generate Access reports.
3, the implementation of the Web application log processing functions.
4, the realization data compression function.
5, the transmission of data encryption.
6, the implementation of the XML file XSLT transformation.
A servlet filter is actually a Java class, and its implementation needs to be divided into two parts, the Java class itself and the XML description in the Web.xml file. For the filter interface, this interface is initialized () by a pair of described lifecycle methods (), Destroy (), and the Init method is invoked when the server initializes the filter, and the Destory method is invoked when the server shuts down. There is also a behavioral method the Dofilter method is invoked when the filter operation is performed.

The configuration of the servlet filter
The Servet filter needs to be deployed to the application through the Web application Deployment descriptor file Web.xml. Configured as follows

Copy Code code 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>

Here is an example:

Use filters to solve Chinese coding problems:
Because the default encoding for Java is iso-8859-1, the GB2312 or GBK encoding is usually used when writing Chinese applications. In this case, you should specify how the page is encoded by the <%@ page contenttype= "TEXT/HTML;CHARSET=GBK"%> command at the header of the page. So the Chinese page can be displayed normally. But if the page is in the village form. such as an input input box, if the visitor entered Chinese in it, and submitted to a servlet for processing, Java will first iso-5589-1 the default way to encode the text, and then give Servet processing, The processed text will still be iso-5589-1 encoded in the village, if this time this text returns a page that is displayed by GBK encoding, because of the different encoding format, it is obviously not get the correct display result.
There are many ways to solve the coding method, which mainly introduces the use of filters to solve the Chinese coding problem:

Copy Code code 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 configuration of the XML:

Copy Code code 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>

And finally, the writing of encoding.jsp?

Copy Code code as follows:

User name: <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" >

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

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

<input type= "Submit" value= "submitted" >

</form>

Start Tomcat, Access encoding.jsp, enter "Zhang Shan Gujiao" can be seen, after the filter, the page can display the information from the server normally ...

Using filters to record user access logs
For some projects, it has a detailed record of each visit to the user. So this is a great way to use log logs, which makes it easy to record each user's access with a filter. However, because the same visitor accesses different pages of the site at the same time, the log cannot be repeated, otherwise the logs will be crammed into the server's hard disk space for a very short period. Thus, the session object can be used to judge each conversation of a user, and in one session the filter is logged only once.
Write the Logfilter class below, which is primarily responsible for recording user access records:

Copy Code code 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;
Get Session Object
HttpSession session = Hrequest.getsession ();
First determine whether the logged in the session has a value, if not the new request
if (Null==session.getattribute ("logged")) {
Session.setattribute ("logged", "yes"); Set the value of logged to Yes to prevent duplicate records from the same session
File File = new file (this.filename);
if (!file.exists ())
File.createnewfile (); To determine whether a file exists, if it does not exist, create a new

/*
* Create logging content logcontent include the IP of the visitor, the URL of the page visited and the time of the visit and the name of the log filter
*/
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 manipulation object
Rf.seek (Rf.length ()); Writes the pointer to the end of the file, Rf.length () Gets the length of the file, and the length of the seek file is so long that it is just the tail of the file.
Rf.writebytes (logcontent); Write a log to a file
Rf.close (); Close 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 ();
}

Get time
Private String GetTime () {
SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd-hh-mm-ss");
Return Sdf.format (New Date ());
}

}

The session is used to limit the same conversation to just one log, regardless of how many pages the visitor accesses in the session, and as the logged of the sessions is empty at the first visit, this time logging and setting the logged to Yes, The record log will not be executed when the second judgment is done.
Then you can configure the XML:

Copy Code code 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 is configured, access to any file in the fields and directories can be recorded by the visitor in the D:/log.txt file.

Related Article

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.