當把全部牽涉到的都改成utf-8時,依然有亂碼。後來在網站上求助,滄海一夢 給出了這個解決方案:將表單提交方式由get改成post,果真成功。謝過!html
解決問題後,我並無深究爲何會出現這種現象,後來在網上查資料,無心看到 java_pengjin 這位仁兄寫的「java
」中給出了以下解釋:web
自從Tomcat5.x開始,GET和POST方法提交的信息,Tomcat採用了不一樣的方式來處理編碼,對於POST請求,Tomcat會仍然使用request.setCharacterEncoding方法所設置的編碼來處理,若是未設置,則使用默認的iso-8859-1編碼。而GET請求則不一樣,Tomcat對於GET請求並不會考慮使用request.setCharacterEncoding方法設置的編碼,而會永遠使用iso-8859-1編碼。app
1.filter/comments.jsp:jsp
<%@ page language ="java" import="java.util.*" pageEncoding="UTF-8" %>post
<%網站
String path = request.getContextPath();ui
String basePath = request.getScheme()+"://" +request.getServerName()+":"+request.getServerPort()+path+ "/";編碼
%>url
<!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>