1. 程式人生 > >講授Javax.servlet.Filter使用總結例子

講授Javax.servlet.Filter使用總結例子

今天給同學們講解SpringMVC,很多同學們反應對Servlet過濾器、監聽了解甚少,所以現場給大家分享了一個小例子,然大家學習掌握一下;

1、登入頁面

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>login pages</title>
</head>
<body>
	<form action="login" method="post">
		<input name="userName" type="text" /> 
		<input name="userPwd" type="password" /> 
		<input type="submit" value="submit" />
	</form>
</body>
</html>

2、請求Servlet
package springdemo01;

import java.io.IOException;

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

public class LoginServlet extends HttpServlet {
	
	
	
	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
	}

	/**
	 * 當view發生請求時,進入該Servlet,然後呼叫Dao進行持久化使用者....
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setCharacterEncoding("utf-8");
		String userName = req.getParameter("userName");
		String userPwd = req.getParameter("userPwd");
		if("huayongsheng".equals(userName) && "123456".equals(userPwd)){
			resp.sendRedirect("main.jsp");
			req.getSession().setAttribute("userName", userName);
		}else{
			resp.getWriter().print("<script>alert('登入失敗了');window.history.back(-1);</script>");
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
}
3、登入成功頁面
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<!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">
<title>歡迎您的登入</title>
</head>
<body>歡迎您的登入...
</body>
</html>

4、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>LoadServlet</servlet-name>
		<servlet-class>springdemo01.LoadServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>LoadServlet</servlet-name>
		<url-pattern>/load</url-pattern>
	</servlet-mapping>

	<servlet>
		<servlet-name>LoginServlet</servlet-name>
		<servlet-class>springdemo01.LoginServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>LoginServlet</servlet-name>
		<url-pattern>/login</url-pattern>
	</servlet-mapping>

	<filter>
		<filter-name>loginFilter</filter-name>
		<filter-class>springdemo01.LoginFilter</filter-class>
		<init-param>
			<param-name>excludedPages</param-name>
			<param-value>/login,login.jsp</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>loginFilter</filter-name>
		<!-- 過濾所有的請求 -->
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<welcome-file-list>
		<welcome-file>login.jsp</welcome-file>
	</welcome-file-list>
</web-app>
5、建立過濾器
package springdemo01;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

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.HttpSession;

public class LoginFilter implements Filter {

	private String excludedPagesString;
	private List<String> excludedPagesList;
	
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("過濾器====init");
		excludedPagesString = filterConfig.getInitParameter("excludedPages");
		if(!"".equals(excludedPagesString)){
			String[] arr = excludedPagesString.split(",");
			excludedPagesList = Arrays.asList(arr);
		}
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("utf-8");
		System.out.println("過濾器====doFilter");
		//請求的Url路徑
		boolean flag = false;//是否在排除過濾的url當中
		String requestUrl = ((HttpServletRequest) request).getRequestURI();  
		for (String string : excludedPagesList) {
			if(requestUrl.contains(string)){
				flag = true;
				break;
			}
		}
		
		HttpSession session = ((HttpServletRequest)request).getSession();
		if(flag ||( session.getAttribute("userName") != null && !"".equals(session.getAttribute("userName")))){
			chain.doFilter(request,response);//放行。讓其走到下個鏈或目標資源中 
		}else{
			response.getWriter().print("<script>alert('過濾器過濾了,無許可權訪問');window.locaiton.href='login.jsp';</script>");
		}		
	}

	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("過濾器====destroy");
	}

}

6、Filter執行流程如下圖



OK,將例子放入eclipse即可執行;

1、當部署專案之後,啟動Tomcat;此時控制檯列印:“過濾器====init”;說明在啟動Tomcat容器時,過濾器已經執行init方法;

2、當開啟http://127.0.0.1/springdemo01/login.jsp時,錄入使用者名稱huayongsheng、密碼123456;可以正常登入;

此時已經控制檯列印""過濾器====doFilter";因為在web.xml配置了

<filter>
		<filter-name>loginFilter</filter-name>
		<filter-class>springdemo01.LoginFilter</filter-class>
		<init-param>
			<param-name>excludedPages</param-name>
			<param-value>/login,login.jsp</param-value><!--排除此處的請求,允許你訪問的jsp與servlet;否則無法顯示登入介面>
		</init-param>
	</filter>
<filter-mapping>
		<filter-name>loginFilter</filter-name>
		<!-- 過濾所有的請求 -->
		<url-pattern>/*</url-pattern>
	</filter-mapping>
誰需要demo或者指導,請加QQ 2283622216(匠人):共同學習、分享視訊為快樂之本;