当把所有牵涉到的都改为utf-8时,依然有乱码。后来在网站上求助,滄海一夢 给出了这个解决方案:将表单提交方式由get改为post,果然成功。谢过!
1.filter/comments.jsp:
<%@ page language ="java" import="java.util.*" pageEncoding="UTF-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://" +request.getServerName()+":"+request.getServerPort()+path+ "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head >
<base href ="<%=basePath%> ">
<meta http-equiv ="content-language" content="zh-CN" />
</head >
<body >
<form action="filter/commentsResult.jsp" method= "post">
<%--get方式容易出现乱码,改成post即解决--%>
用户名: <input type ="text" name="uname" /><br/>
评论: <textarea rows ="7" cols="10" name= "comments"></textarea ><br/>
<input type ="submit" value="提交"/>
</form >
</body >
</html>
2.filter/commentsFilter.java:
package 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 CommentsFilter implements Filter{
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding( "utf-8"); //
response.setContentType( "text/html; charset=UTF-8");
String uname=request.getParameter( "uname");
String comments=request.getParameter( "comments");
if( null!=uname){
uname=uname.replace( "hui", "#");
request.setAttribute( "uname", uname);
}
if( null!= comments){
comments=comments .replace("党" , "*" );
request.setAttribute( "comments", comments);
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
同时在web.xml中配置如下:
<filter >
<filter-name >CommentsFilter </filter-name>
<filter-class >filter.CommentsFilter </filter-class>
</filter >
<filter-mapping >
<filter-name >CommentsFilter </filter-name>
<url-pattern >/filter/commentsResult.jsp </url-pattern>
</filter-mapping >
3.filter/commentsResult.jsp:
<%@ page language ="java" import="java.util.*" pageEncoding="UTF-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://" +request.getServerName()+":"+request.getServerPort()+path+ "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body >
用户名: <%=request.getAttribute( "uname") %><br />
评论: <%=request.getAttribute( "comments") %>
</body >
</html>