1. 程式人生 > >【JSP開發】自己寫的過濾器Filter例子

【JSP開發】自己寫的過濾器Filter例子

目的是讓瀏覽網站的使用者所接收到的資訊的編碼方式統一為UTF-8,防止亂碼的產生

1.沒加過濾器之前:

拿Jsp工程(名叫web)中的兩個Servlet做實驗

ChineseServlet.java:

package cn.edu.hpu.servlet;

import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ChineseServlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String data="我的中國心";
		
		request.setAttribute("data", data);
		request.getRequestDispatcher("/result").forward(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}


}


ResultServlet.java
package cn.edu.hpu.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ResultServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String text=(String)request.getAttribute("data");
		PrintWriter out=response.getWriter();
		
		out.write("傳過去的那句話是(The word get is):"+text);
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {


	}


}

在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">
  <servlet>
    <servlet-name>ChineseServlet</servlet-name>
    <servlet-class>cn.edu.hpu.servlet.ChineseServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>ResultServlet</servlet-name>
    <servlet-class>cn.edu.hpu.servlet.ResultServlet</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>ChineseServlet</servlet-name>
    <url-pattern>/chin</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>ResultServlet</servlet-name>
    <url-pattern>/result</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


啟動伺服器,在位址列上輸入:http://localhost:8080/web/chin,得到:
?????????The word get is?:?????
出現亂碼,說明沒有指定編碼。


解決辦法:
兩邊servlet同時設定(這裡以UTF-8為編碼標準):
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");


需要顯示的時候:
String text=(String)request.getAttribute("data")+"是傳過來的那句話";


System.out.println(text);
OutputStream out =response.getOutputStream(); 
out.write("<html>".getBytes());


//用html技術中meta標籤模擬了一個http響應頭,來控制瀏覽器的行為
out.write("<meta http-equiv='content-type' content='text/html;charset=UTF-8'>".getBytes());
out.write(text.getBytes("UTF-8"));
out.write("</html>".getBytes());
或者直接:
response.setContentType("text/html;charset=UTF-8");


以上方法很臃腫,而且非常不簡介,無法應對多個介面,所以要使用過濾器來統一設定編碼。

2.加過濾器之後:


ChineseServlet.java:

package cn.edu.hpu.servlet;


import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ChineseServlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String data="我的中國心";
		
		request.setAttribute("data", data);
		request.getRequestDispatcher("/result").forward(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {


	}


}
ResultServlet .java:
package cn.edu.hpu.servlet;


import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ResultServlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String text=(String)request.getAttribute("data");
		PrintWriter out=response.getWriter();
		
		out.write("傳過去的那句話是(The word get is):"+text);
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {


	}


}


過濾器:
package cn.edu.hpu.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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class TestFilter implements Filter {
	private String characterEncoding=null;
	
	public void destroy() {
		// TODO Auto-generated method stub
		
	}


	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterchain) throws IOException, ServletException {
		request.setCharacterEncoding(characterEncoding);
		response.setCharacterEncoding(characterEncoding);
		response.setContentType("text/html;charset="+characterEncoding);
		
		//獲取URL的路徑和引數
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		String path=req.getServletPath();
		String param=req.getQueryString();
		if(path!=null&¶m!=null){
			path=path+"?"+param;//全請求路徑
		}
		System.out.println("Path:"+path);
		//跳轉或帶引數跳轉
		request.getRequestDispatcher(path).forward(request, response);
	}


	public void init(FilterConfig filterConfig) throws ServletException {
		characterEncoding = filterConfig.getInitParameter("characterEncoding");
		
	}


}


在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>TestFilter</filter-name>
	<filter-class>cn.edu.hpu.filter.TestFilter</filter-class>
	<init-param>
		<param-name>characterEncoding</param-name>
		<param-value>UTF-8</param-value>
	</init-param>
    </filter>
    
    <filter-mapping>
		<filter-name>TestFilter</filter-name>
		<url-pattern>/*</url-pattern>
    </filter-mapping>


  <servlet>
    <servlet-name>ChineseServlet</servlet-name>
    <servlet-class>cn.edu.hpu.servlet.ChineseServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>ResultServlet</servlet-name>
    <servlet-class>cn.edu.hpu.servlet.ResultServlet</servlet-class>
  </servlet>




  <servlet-mapping>
    <servlet-name>ChineseServlet</servlet-name>
    <url-pattern>/chin</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>ResultServlet</servlet-name>
    <url-pattern>/result</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

啟動伺服器,在位址列上輸入:http://localhost:8080/web/chin,得到:
傳過去的那句話是(The word get is):我的中國心
沒有發生亂碼,說明過濾成功!!