網上處理方法一籮筐,下面說說我用過的兩種有效地解決辦法.
1.為程式編寫一個字串處理函數,用一個靜態檔案儲存,在需要處理中文字元的JSP頁面中包含它,
複製代碼 代碼如下:
<%!
public String codeToString(String str)
{
String s=str;
try
{
byte temp[]=s.getBytes("ISO-8859-1");
s=new String(temp);
return s;
}
catch(Exception e)
{
return s;
}
}
%>
要轉換時只需:coedeToString(request.getParameter(..));就可以了,很好用的。
2.一種普遍適用的方法,加一個過濾器,之後就可以過上一勞永逸的日子了。
複製代碼 代碼如下:
package filters;
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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class TomcatFormFilter implements Filter {
/**
* Request.java
* 對 HttpServletRequestWrapper 進行擴充, 不影響原來的功能並能提供所
有的 HttpServletRequest
* 介面中的功能. 它可以統一的對 Tomcat 預設設定下的中文問題進行解決而只
需要用新的 Request 對象替換頁面中的
* request 對象即可.
*/
class Request extends HttpServletRequestWrapper
{
public Request(HttpServletRequest request) {
super(request);
}
/**
* 轉換由表單讀取的資料的內碼.
* 從 ISO 字元轉到 GBK.
*/
public String toChi(String input) {
try {
byte[] bytes = input.getBytes("ISO8859-1");
return new String(bytes, "GBK");
}
catch (Exception ex) {
}
return null;
}
/**
* Return the HttpServletRequest holded by this object.
*/
private HttpServletRequest getHttpServletRequest()
{
return (HttpServletRequest)super.getRequest();
}
/**
* 讀取參數 -- 修正了中文問題.
*/
public String getParameter(String name)
{
return
toChi(getHttpServletRequest().getParameter(name));
}
/**
* 讀取參數列表 - 修正了中文問題.
*/
public String[] getParameterValues(String name)
{
String values[] =
getHttpServletRequest().getParameterValues(name);
if (values != null) {
for (int i = 0; i < values.length; i++) {
values[i] = toChi(values[i]);
}
}
return values;
}
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse
response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpreq = (HttpServletRequest)request;
if(httpreq.getMethod().equals("POST")) {
request.setCharacterEncoding("GBK");
} else {
request = new Request(httpreq);
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws
ServletException {
}
}
當然要記得改下web.xml
複製代碼 代碼如下:
<filter>
<filter-name>TomcatFormFilter</filter-name>
<filter-class>filters.TomcatFormFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>TomcatFormFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
上面兩種方法都測試過了,比較好用,以後發現新的,會再更新哦~