JSP用過濾器解決request中文亂碼問題

來源:互聯網
上載者:User

標籤:jsp用過濾器解決request中文亂碼   解決request中文亂碼問題   jsp過濾器   亂碼   servlet中讀取表單   

(1)用戶端的資料一般是通過HTTP  GET/POST方式提交給伺服器,在伺服器端用request.getParameter()

讀取參數時,很容易出現中文亂碼現象。

(2)用過濾器解決request中文亂碼問題。

(3)代碼如下:

package my;import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class ChineseFilter implements Filter { //定義了一個過濾器 實現Filter介面  private FilterConfig config = null;  public void init(FilterConfig config) throws ServletException {    this.config = config;  }  public void destroy() {    config = null;  }  public void doFilter(ServletRequest request, ServletResponse response,                     FilterChain chain) throws IOException, ServletException  {         request.setCharacterEncoding("GB2312");       chain.doFilter(request, response); //把過濾後的request對象轉寄給下一個過濾器處理  }}


(4)部署過濾器。編輯WEB-INF\web.xml檔案,添加以下內容:

<filter>    <filter-name>cf</filter-name>    <filter-class>my.ChineseFilter</filter-class></filter><filter-mapping>    <filter-name>cf</filter-name>    <url-pattern>/*</url-pattern>    <dispatcher>REQUEST</dispatcher>    <dispatcher>FORWARD</dispatcher>    <dispatcher>INCLUDE</dispatcher></filter-mapping>

這裡的<dispatcher></dispatcher>主要是配合RequestDispatcher使用。


1.取值為REQUEST時 表示有請求直接來自用戶端時,過濾器才能被啟用,如果請求是來自RequestDispatcher.forward時不啟用;


2.取值為FORWARD時 表示如果請求是來自RequestDispatcher.forward時此過濾器才啟用;


3.取值為INCLUDE時 表示如果請求是來自RequestDispatcher.include時此過濾器才啟用;


4.取值為ERROR時 表示如果請求是來自RequestDispatcher使用“錯誤資訊頁”時此過濾器才啟用;


5.預設為REQUEST。


(5)建立一個jsp頁面檢驗

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>無標題文檔</title></head><body><%    String s=request.getParameter("data");out.print(s);%></body></html>


(6)OK!到此結束 望你成功!

JSP用過濾器解決request中文亂碼問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.