A simple JAVA Character Set Filter Implementation

Source: Internet
Author: User

Copy codeThe Code is as follows:
Package dw05prj. util. filter;

Import javax. servlet. Filter;
Import javax. servlet. FilterConfig;
Import javax. servlet. ServletException;
Import javax. servlet. ServletRequest;
Import javax. servlet. ServletResponse;
Import javax. servlet. FilterChain;
Import java. io. IOException;

/* Page character set filtering stream */

/*
Example of configuration in web. xml
<Filter>
<Filter-name> CharEncodingFilter </filter-name>
<Filter-class> dw05prj. util. filter. CharEncodingFilter </filter-class>
<Init-param>
<Param-name> charset </param-name>
<Param-value> GBK </param-value>
</Init-param>

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

Public class CharEncodingFilter implements Filter {

Private String charSet;

Public void init (FilterConfig parm1) throws ServletException {
CharSet = parm1.getInitParameter ("charset ");
If (charSet = null & charSet. length () <1)
{
CharSet = "UTF-8 ";
}
System. out. println ("CharEncodingFilter -- Character Set:" + this. getCharSet ());
}


Public void doFilter (ServletRequest parm1, ServletResponse parm2,
FilterChain parm3) throws IOException, ServletException {

// Set the character set
Parm1.setCharacterEncoding (this. getCharSet ());
Parm3.doFilter (parm1, parm2 );
// Every request sent to the server in the page is filtered-for example, images, js, HTML/JSP, etc.
// System. out. println ("--- CharEncodingFilter:" + this. getCharSet ());
}

Public void destroy (){
// TODO: Add your code here
This. setCharSet (null );
}


Public void setCharSet (String charSet ){
This. charSet = charSet;
}

Public String getCharSet (){
Return (this. charSet );
}
}

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.