统一处理web请求与响应的
编码方式即使防止出现
乱码问题的要求,也是实施
输入校验,输出编码等安全管控的措施。建议统一采用UTF-9字符编码。
实现方案:
1,设置tomcat,使得tomcat在处理Get请求参数的时候用UTF-8编码。编辑tomcat的配置文件server.xml 设置<conector>URLEncoding属性为"UTF-8"。
class="java"> <Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URLEncoding="UFT-8"
/>
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443"
URIEncoding="UTF-8"/>
注意:最好是把所有的connector的编码属性都设置成utf-8的。
2,用filter来设置处理post请求参数的编码方式为UTF-8
package com.supan.framework.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 EncodingFilter implements Filter
{
private String encoding = "utf-8";
public void init(FilterConfig filterConfig) throws ServletException
{
String encodingParam = filterConfig.getInitParameter("encoding");
if (null != encodingParam)
{
encoding = encodingParam;
}
}
/**
* <读取filter配置的默认编码方式>
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChin) throws IOException, ServletException
{
request.setCharacterEncoding(encoding);
filterChin.doFilter(request, response);
}
public void destroy()
{
}
}
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>com.supan.framework.filter.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3,处理完get,post请求的参数编码之后,为每个jsp页面加入page指令,设置相应页面的编码方式为UTF-8,
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
或者直接在代码中设置相应的编码方式:
response.setCharacterEncoding("UTF-8");
至此系统统一编码处理,已经处理完毕,在所有地方都不能设置request,respon的编码格式也能正常显示中文字符。
下面是个实例:
登陆页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<script type="text/javascript">
function clearUserNameAndPassword()
{
document.getElementById("userName").value = "";
document.getElementById("password").value = "";
}
</script>
<body onload="clearUserNameAndPassword();">
This is my JSP page. <br>
<form action="dealLogin.jsp" method="get" autocomplete="false">
<input type="text" name="userName" id="userName" autocomplete="false"/>
<input type="password" name="password" id="password" autocomplete="false"/>
<input type="submit" name="登陆"/>
</form>
</body>
</html>
登陆处理页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<body>
<%
String userName = request.getParameter("userName");
String password = request.getParameter("password");
%>
<%= userName %>
<%= password %>
</body>
</html>
注意:如果读取数据库数据,则需要把数据库编码统一设置成utf-8的编码