1. 程式人生 > >JavaWeb 使用Filter實現統一全站編碼(教材學習筆記)

JavaWeb 使用Filter實現統一全站編碼(教材學習筆記)

1、編寫form.jsp頁面

在web-chapter08的WebContent目錄中,編寫一個form.jsp頁面,該頁面用於提交使用者登陸的表單資訊,程式碼如下:

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8" import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<center>
	<h3>使用者登入</h3>
</center>
<body style="text-align: center;">
	<a href="<%=request.getContextPath()%>/CharacterServlet?name=傳智播客&password=123456">單擊超連結登入</a>
	<form action="<%=request.getContextPath()%>/CharacterServlet"
		method="post">
		<table border="1" width="600px" cellpadding="0" cellspacing="0"
			align="center">
			<tr>
				<td height="30" align="center">使用者名稱:</td>
				<td>&nbsp;<input type="text" name="name" />
				</td>
			</tr>
			<tr>
				<td height="30" align="center">密 &nbsp; 碼:</td>
				<td>&nbsp;<input type="password" name="password" />
				</td>
			</tr>
			<tr>
				<td height="30" colspan="2" align="center">
				<input type="submit" value="登入" />
				 &nbsp;&nbsp;&nbsp;&nbsp;
				<input type="reset" value="重置" />
			    </td>
			</tr>
		</table>
	</form>
</body>

2、建立servlet

建立一個名為CharacterServlet類,該類用於獲取使用者輸入的請求引數,並將引數傳送到控制檯

程式碼如下:

package cn.itcast.chapter08.filter;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
public class CharacterServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println(request.getParameter("name"));
		System.out.println(request.getParameter("password"));
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

3、建立過濾器

建立一個名為CharacterFilter類,該類用於攔截使用者的請求訪問,實現統一全站編碼,只是針對請求的方式不同,解決亂碼的方式也不相同,程式碼如下:

package cn.itcast.chapter08.filter;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CharacterFilter implements Filter {
	public void init(FilterConfig filterConfig) throws ServletException {
	}
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		// 攔截所有的請求 解決全站中文亂碼
		// 指定 request 和 response 的編碼
		request.setCharacterEncoding("utf-8"); // 只對訊息體有效
		response.setContentType("text/html;charset=utf-8");
		// 對request進行包裝
		CharacterRequest characterRequest = new CharacterRequest(request);
		chain.doFilter(characterRequest, response);
	}
	public void destroy() {
	}
}
// 繼承 預設包裝類HttpServletRequestWrapper
class CharacterRequest extends HttpServletRequestWrapper {
	private HttpServletRequest request;
	public CharacterRequest(HttpServletRequest request) {
		super(request);
		this.request = request;
	}
	// 子類繼承父類一定會覆寫一些方法,此處用於重寫getParamter()方法
	public String getParameter(String name) {
		// 呼叫被包裝物件的getParameter()方法,獲得請求引數
		String value = super.getParameter(name);
		if (value == null)
			return null;
		// 判斷請求方式
		String method = super.getMethod();
		if ("get".equalsIgnoreCase(method)) {
			try {
					value = new String(value.getBytes("iso-8859-1"), "utf-8");
			} catch (UnsupportedEncodingException e) {
				throw new RuntimeException(e);
			}
		}
		// 解決亂碼後返回結果
		return value;
	}
}

4、配置對映資訊

在web.xml中配置CharacterFilter以及CharacterServlet的對映資訊

程式碼如下:

<servlet>
		<description></description>
		<display-name>CharacterServlet</display-name>
		<servlet-name>CharacterServlet</servlet-name>
		<servlet-class>cn.itcast.chapter08.filter.CharacterServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>CharacterServlet</servlet-name>
		<url-pattern>/CharacterServlet</url-pattern>
	</servlet-mapping>
	<filter>
		<filter-name>CharacterFilter</filter-name>
		<filter-class>cn.itcast.chapter08.filter.CharacterFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>CharacterFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

5、啟動tomcat,進行測試

在網址欄輸入http://localhost:8080/web-chapter08/form.jsp,結果如下:

點選登入後,控制檯輸出了使用者名稱以及密碼,將form.jsp的表單提交方式改為get之後再次點選登入,觀察就會發現控制檯輸出的使用者名稱和密碼與剛剛使用post方式提交的表單是一致的,說明過濾器Filter起作用了