Many in the learning JSP encountered garbled problem, the solution is actually very simple, a custom character interceptor can be.
In order to be decoupled from the business code, we should separate the character conversion code into a character interceptor.
Directly on the code:
Package com.jdbc.filter;
Import java.io.IOException;
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.HttpServletResponse;
public class Characterfilter implements Filter {private filterconfig config; public void Dofilter (ServletRequest req, Servletresponse resp, Filterchain chain) throws IOException, Servletexception
{HttpServletRequest request = (httpservletrequest) req;
HttpServletResponse response = (httpservletresponse) resp;
Gets the param-value String encoding = config.getinitparameter ("encoding") in the corresponding init-param in the encoding from the Web.xml file; If you define a variable, you must judge whether it is empty, or you will report a null pointer exception if (encoding!= null) {//Specify the character encoding set of the content request format Response.setcontenttype ("text/html; charse
t= "+ encoding);
When requested, the canonical character encoding format request.setcharacterencoding (encoding); //Indicates the output of the format character encoding set response.setcharacterencoding (encoding);
}//Enter the next interceptor Chain.dofilter (request, response);
}//Filterconfig is the interceptor's global variable public void init (Filterconfig config) throws servletexception {this.config = config; public void Destroy () {}}
The next step is to have the request go into the character interceptor and configure it in the Web.xml file
<!--character encoding set interceptor-->
<filter>
<filter-name>CharacterFilter</filter-name>
< Filter-class>com.jdbc.filter.characterfilter</filter-class>
<!--configuration initialization parameters-->
< init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value >
</init-param>
</filter>
<!--mapping path-->
<filter-mapping>
< filter-name>characterfilter</filter-name>
<url-pattern>/*</url-pattern>
</ Filter-mapping>
The above is the character interceptor, independent of the business code, only need to copy to the project.
A little learning, a little growth, have any questions and suggestions can leave a message, I will promptly deal with.
More dry goods wait for you to get http://www.itit123.cn/