使用过滤器,处理中文显示乱码,并且在插入到mysql数据库的中文数据不为乱码

写道
你可以单独写一个过滤器 代码我有现成的 我看看给你写在这也可以

先新建一个Servlet要求extendsHttpServletimplementsFilter

packagecom.huangshan.filt;

importjava.io.IOException;

importjava.io.PrintWriter;

importjavax.servlet.Filter;

importjavax.servlet.FilterChain;

importjavax.servlet.FilterConfig;

importjavax.servlet.ServletException;

importjavax.servlet.ServletRequest;

importjavax.servlet.ServletResponse;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

publicclassmyfiltextendsHttpServletimplementsFilter{

/**

*ThedoGetmethodoftheservlet.<br>

*

*Thismethodiscalledwhenaformhasitstagvaluemethodequalstoget.

*

*@paramrequesttherequestsendbytheclienttotheserver

*@paramresponsetheresponsesendbytheservertotheclient

*@throwsServletExceptionifanerroroccurred

*@throwsIOExceptionifanerroroccurred

*/

publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)

throwsServletException,IOException{

response.setContentType("text/html");

PrintWriterout=response.getWriter();

out

.println("<!DOCTYPEHTMLPUBLIC\"-//W3C//DTDHTML4.01Transitional//EN\">");

out.println("<HTML>");

out.println("<HEAD><TITLE>AServlet</TITLE></HEAD>");

out.println("<BODY>");

out.print("Thisis");

out.print(this.getClass());

out.println(",usingtheGETmethod");

out.println("</BODY>");

out.println("</HTML>");

out.flush();

out.close();

}

/**

*ThedoPostmethodoftheservlet.<br>

*

*Thismethodiscalledwhenaformhasitstagvaluemethodequalstopost.

*

*@paramrequesttherequestsendbytheclienttotheserver

*@paramresponsetheresponsesendbytheservertotheclient

*@throwsServletExceptionifanerroroccurred

*@throwsIOExceptionifanerroroccurred

*/

publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)

throwsServletException,IOException{

response.setContentType("text/html");

PrintWriterout=response.getWriter();

out

.println("<!DOCTYPEHTMLPUBLIC\"-//W3C//DTDHTML4.01Transitional//EN\">");

out.println("<HTML>");

out.println("<HEAD><TITLE>AServlet</TITLE></HEAD>");

out.println("<BODY>");

out.print("Thisis");

out.print(this.getClass());

out.println(",usingthePOSTmethod");

out.println("</BODY>");

out.println("</HTML>");

out.flush();

out.close();

}

publicvoiddoFilter(ServletRequestarg0,ServletResponsearg1,FilterChainarg2)throwsIOException,ServletException{

//TODO自动生成方法存根

//处理中文乱码问题

arg0.setCharacterEncoding("gbk");

//程序继续前进

arg2.doFilter(arg0,arg1);

}

publicvoidinit(FilterConfigarg0)throwsServletException{

//TODO自动生成方法存根

}

}

完成以上操作以后再修改web.xml在中间加入以下代码

<filter>

<filter-name>myfilt</filter-name>

<filter-class>com.huangshan.filt.myfilt</filter-class>

</filter>

<filter-mapping>

<filter-name>myfilt</filter-name>

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

</filter-mapping>

myfilt:建立Servlet的类名称

com.huangshan.filt.myfilt:类的路径

别的就不需要修改了

相关推荐