jsp中配置web.xml过滤器防止中文乱码



jsp中配置web.xml过滤器防止中文乱码,设置编码格式,getRequestDispatcher页面跳转时传递参数时如何防止乱码?以下是将所有request内的对象设置字符集为UTF-8具体实例:

filter_chanise.jsp文件源码,该文件负责页面的跳转并且传递参数:

<%@ page language=”java” pageEncoding=”utf-8″%>

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<title>My JSP ‘filter_chanise.jsp’ starting page</title>
</head>
<body>
<%
String username=”无极”;
String sex =”男”;
String address =”地球”;
request.setAttribute(“username”,username);
request.setAttribute(“sex”,sex);
request.setAttribute(“address”,address);
request.getRequestDispatcher(“filter_chanise_get.jsp”).forward(request,response);
%>
</body>
</html>

filter_chanise_get.jsp页面,request.getAttribute方法负责接收参数:

<%@ page language=”java” pageEncoding=”utf-8″%>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<title>My JSP ‘filter_chanise_get.jsp’ starting page</title>
</head>

<body>
<%
out.println(“username的值:”+request.getAttribute(“username”));
%>
<br>
<%
out.println(“sex的值:”+request.getAttribute(“sex”));
%>
<br>
<%
out.println(“address的值:”+request.getAttribute(“address”));
%>
</body>
</html>

防止乱码的编码过滤ChiniseFilter.java源码:

package com.cn.filter;

import java.io.IOException;


import javax.servlet.*;

public class ChiniseFilter implements Filter {

public void destroy() {
// TODO Auto-generated method stub

}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//将所有request内的对象设置字符集为UTF-8
request.setCharacterEncoding(“UTF-8″);
//将所有response内的对象设置字符集为UTF-8
response.setCharacterEncoding(“UTF-8″);
//用chain的doFilter处理过滤
chain.doFilter(request, response);
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub

}

}

web.xml编码配置:

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app version=”2.5″
xmlns=”http://java.sun.com/xml/ns/javaee”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”>
<filter>
<filter-name>Chanise</filter-name>
<filter-class>com.cn.filter.ChiniseFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Chanise</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>