一般表单提交有POST,GET方式,不过处理的时候方法有所区别
一般post可以在JSP页面添加<% request.setCharacterEncoding="GBK";%> 来处理
GET方式可以用转换编码方式类似的如:<%String username = new String(username.getBytes("ISO8859_1"),"GBK");%>
不过这不是很好的处理方式,比较麻烦。每个页面都要写这样重复的转换。
POST方式一般可以用Filter过滤的Servlet来实现
创建EncodingFilter.java
=======================
/*
* CoppyRight (c) Eays Studio
* description:LoginAction
*/
package net.eays.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletException;
/**
* @author 小林信仁
* Creation date: 05-09-2007
*/
public class EncodingFilter implements Filter {
/**
* Constructor of the object.
*/
private FilterConfig config = null;
private String targetEncoding = "GBK";
public EncodingFilter() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
config = null;
targetEncoding = null;
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occure
*/
public void init(FilterConfig config) throws ServletException {
this.config = config;
this.targetEncoding = config.getInitParameter("encoding");
System.out.println("init get value:"+ this.targetEncoding );
}
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException{
System.out.println("targetEncoding :" + targetEncoding + "/n");
request.setCharacterEncoding(targetEncoding);
chain.doFilter(request, response);
}
}
==============================
Web.xml中EncodingFilter过滤器配置添加
========================
<filter>
<description>EncodingFilter</description>
<display-name>EncodingFilter</display-name>
<filter-name>EncodingFilter</filter-name>
<filter-class>net.eays.servlet.EncodingFilter</filter-class>
<init-param>
<description>encoding to GB2312</description>
<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>
=============================
处理Get方式以上还是不行,Tomcat可以修改server.xml文件
============================
知道 <Connector
最后添加属性 useBodyEncodingForURI="true"
============================
OK,一切的乱码问题通通解决!