- 在Web项目中,主要编码格式改变的地方有:
- 服务器载入的编码
- Jsp/html文件,xml文件等外部保存的编码
- 虚拟机加载的文件编码
- IDE的保存文件编码 - 编码过滤器(Code)
//过滤器类 CharactorFilter.jsppackagecn.com.Filter; importjava.io.IOException; importjavax.servlet.Filter; importjavax.servlet.FilterChain; importjavax.servlet.FilterConfig; importjavax.servlet.ServletException; importjavax.servlet.ServletRequest; importjavax.servlet.ServletResponse; publicclassCharactorFilterimplementsFilter { //继承Filter类//字符编码Stringencoding=null; publicvoiddoFilter(ServletRequestrequest, ServletResponseresponse, FilterChainchain) throwsIOException, ServletException { if(encoding!=null){ //设置request字符编码request.setCharacterEncoding(encoding); //设置response字符编码response.setContentType("text/html;charset="+encoding); } //传递给下一个过滤器chain.doFilter(request, response); } publicvoidinit(FilterConfigfilterConfig) throwsServletException { //获取初始化参数encoding=filterConfig.getInitParameter("encoding"); } publicvoiddestroy() { encoding=null; } }
// web.xml<filter><filter-name>CharactorFilter</filter-name><filter-class>cn.com.Filter.CharactorFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>CharactorFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>
3.response.setContentType("text/html;charset=utf-8");
等价于
response.setCharacterEncoding("utf-8");
response.setHeader("content-type", "text/html;charset=utf-8");
4.如果之前使用response.setContentType设置了编码格式,则再在它后面使用response.setCharacterEncoding指定的编码格式覆盖之前的设置。
5.response.setContentType()、response.setCharacterEncoding() 两个方法调用时必须在getWriter执行之前或者response被提交之前。
<%@page contentType="text/html;charset=gbk"%>:在服务端(tomcat)起作用,是告诉应用服务器采用何种编码输出JSP文件流;
6.<meta http-equiv="Content-Type" content="text/html; charset=GBK">:在客户端(浏览器)起作用,是告诉浏览器是采用何种编码方式显示HTML页面。
7.待更新...