When Using JSP for web projects, we may encounter problems that cannot be displayed in Chinese.
In servlet, request. setcharacterencoding ("gb2312"); (the request is an object of httpservletrequest) is used for processing.
Every servlet is very troublesome.
The following describes how to use a filter to solve this problem, which is simple and convenient and does not require repeated writes.
1. First write an encodingfilter. Java
Package AA;
Import java. Io .*;
Import javax. servlet .*;
Public class encodingfilter implements Filter
{
Protected string encoding = NULL;
Protected filterconfig config;
Public void Init (filterconfig) throws servletexception
{
This. Config = filterconfig;
// Obtain the encoding configuration from the Web. xml configuration file
This. Encoding = filterconfig. getinitparameter ("encoding ");
}
Public void dofilter (servletrequest request, servletresponse response, filterchain chain) throws ioexception, servletexception
{
If (request. getcharacterencoding () = NULL)
{
String encode = getencoding ();
If (encode! = NULL)
{
// Set the Request Encoding Method
Request. setcharacterencoding (encode );
}
}
Chain. dofilter (request, response );
}
Public String getencoding ()
{
Return encoding;
}
Public void destroy ()
{
}
2. Configure the following content in the web. xml file:
<Filter>
<Filter-Name> encodingfilter </filter-Name>
<Filter-class> AA. encodingfilter </filter-Name>
<Init-param>
<Param-Name> encoding </param-Name>
<Param-value> gb2312 </param-value>
</Init-param>
</Filter>
<Filter-mapping>
<Filter-Name> encodingfilter </filter-Name>
<URL-pattern>/* </url-pattern>
</Filter-mapping>
3. Restart the service and solve the problem.