使用过滤器,处理中文显示乱码,并且在插入到mysql数据库的中文数据不为乱码
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
// TODO 自动生成方法存根
// 处理中文乱码问题
arg0.setCharacterEncoding("gbk");
//程序继续前进
arg2.doFilter(arg0, arg1);
}
public void init(FilterConfig arg0) throws ServletException {
// 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:类的路径
别的就不需要修改了
?