第一种:硬编码方式
? 1)在 .jsp 页面中,修改字符集设置:
<%@ page pageEncoding="GB2312" %>
或者,<%@ page contentType="text/html;GB2312" %>
该代码的作用就是告诉JSP引擎(如Tomcat),本页面使用的字符集是GB2312。如果没有此行代码,JSP则使用默认的字符集(通常为utf-8)。
? 2)更改Servlet中相关的代码:
设置输出页面的字符集GB2312,并对获取的内容进行强制转码;
?
//JSP引擎会自动把输出的页面转换成指定的字符集
response.setCharacterEncoding("text/html;GB2312");
//使用request.getParpameter("参数名");获得参数值
//参数值默认的字符集是ISO8859_1,如果不进行字符集转换,将导致汉字乱码
String sname = request.getParameter("name") ;
String name = new String(sname.getBytes("ISO8859_1"),"GB2312") ;
??? //new String(字符串值.getBytes(“原编码方式”),”目录编码方式”);
?
第二种:采用过滤器方式
?? 1)在 .jsp 页面中,修改字符集设置:
<%@ page pageEncoding="GB2312" %>
或者,<%@ page contentType="text/html;GB2312" %>
该代码的作用就是告诉JSP引擎(如Tomcat),本页面使用的字符集是GB2312。如果没有此行代码,JSP则使用默认的字符集(通常为utf-8)。
?? 2)编写一个过滤器:CharacterEncodingFilter.java
package cn.wjz.web.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;
/** 请求数据统一编码过滤器 */
public class CharacterEncodingFilter implements Filter {
??? private FilterConfig config ;
//此Filter被释放时的回调方法
public void destroy() {
}
//主要做过滤工作的方法
//FilterChain用于调用过滤器链中的下一个过滤器
public void doFilter(ServletRequest request,
ServletResponse response,FilterChain chain)
throws IOException, ServletException {
??????? //获取Filter的初始化参数的值
String encoding = config.getInitParameter("encoding") ;
??? if(encoding != null && !"".equals(encoding)){
?? //设置请求数据的编码方式
request.setCharacterEncoding(encoding) ;?
}
//把请求和响应对象传给过滤链中的下一个要调用的过滤器或Servlet
chain.doFilter(request, response) ;
}
//Filter初始化时的回调方法
//FilterConfig接口实例中封装了这个Filter的初始化参数
public void init(FilterConfig config) throws ServletException {
????????? this.config = config ;
}
}
?? 3)注册过滤器,修改配置文件web.xml
<!-- 定义一个过滤器 -->
? <filter>
????? <filter-name>characterEncodingFilter</filter-name>
????? <filter-class>cn.wjz.web.filter.CharacterEncodingFilter
</filter-class>
????? <!-- 配置初始化参数 -->
????? <init-param>
??????? <param-name>encoding</param-name>
??????? <!―设置encoding的值为GB2312 -->
??????? <param-value>GB2312</param-value>
????? </init-param>
? </filter>
? <!-- 过滤器的映射配置 -->
? <filter-mapping>
????? <filter-name>characterEncodingFilter</filter-name>
????? <url-pattern>/*</url-pattern>
? </filter-mapping>