1. 程式人生 > >Servlet 過濾器

Servlet 過濾器

pri dmi ota ati tor ets 調用 send uri

1. 過濾器 Fillter

1)Servlet過濾器是在Java Servlet規範2.3中定義的,它能夠對Servlet容器的請求和響應對象進行檢查和修改

2)Servlet過濾器本身並不生成請求和響應對象,它只提供過濾器作用。

3)Servlet過濾器能過在Servlet被調用之前檢查Request對象,修改Request Heather和Request內容

4)在Servlet被調用之後檢查Response對象,修改Response Header和Response內容。Servlet過濾器負責過濾的Web組件可以是Servlet,JSP或HTML文件

2.Servlet過濾器的過濾過程

技術分享

3.所有的Servlet過濾器類都必須實現javax.servlet.Filter接口。這個過濾器含有3個過濾器類必須實現的方法:

init()

deFilter()

destory()

4.過濾器鏈式請求過程(FilterChain)

技術分享

5. 過濾器實踐1

1)創建訪問時,檢查用戶是否登錄過濾器

package com.example.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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class LoginFilter
 */
@WebFilter("/LoginFilter")
public class LoginFilter implements Filter {

    /**
     * Default constructor. 
     */
    public LoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("filter ondestory");
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		System.out.println("doFilter");
		HttpServletRequest r = (HttpServletRequest)request;
		String requestURI = r.getRequestURI();
		if (requestURI.endsWith("login.jsp") || requestURI.endsWith("MyLoginServlet")) {
			chain.doFilter(request, response);
			return;
			
		}
		HttpSession session = r.getSession();
		if(null == session.getAttribute("user")){
			((HttpServletResponse)response).sendRedirect("login.jsp");
			return;
		}else{
			chain.doFilter(request, response);

		}
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("filter init");
	}

}

  如果沒有登錄,則重定向到login.jsp

2) 在web .xml 中配置filter

 <filter>
    <filter-name>PrivFilter</filter-name>
    <filter-class>com.example.filter.LoginFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>PrivFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  

3) login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="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>Insert title here</title>
<% String basePath= request.getContextPath() + "/test"; %>
<base href=‘<%=basePath %>‘>
</head>
<body>
	<form action="MyLoginServlet" method="post">
		username <input type="text" name="username"><br>
		password <input type="password" name="password"><br>
		權限: <select name="authority">
		      	<option value="1">common user</option>
		      	<option value="2">admin</option>
		      </select>
		      <br>
		<input type="submit" value="submit" >
	</form>
</body>
</html>

  

4)index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.example.bean.User" %>
<!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>Insert title here</title>
</head>
<body>
	<a href="MyQueryServlet">Query</a>
	<% if(((User)session.getAttribute("user")).getAuthority().equals("2")){ %>
	  <a href="MyUpdateServlet">Update</a>
	 <% } %>
</body>
</html>

  

5)創建Servlet, 如MyLoginServlet.java,另外兩個Servlet: MyQueryServlet和MyUpdateServlet比較簡單,只做簡單打印信息。

package com.example.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.example.bean.User;

/**
 * Servlet implementation class MyLoginServlet
 */
@WebServlet("/MyLoginServlet")
public class MyLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyLoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User user = new User();
		HttpSession session = request.getSession();
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String authority = request.getParameter("authority");
		System.out.println("username:" +username + " authority:" + authority);
		if ("1".equals(authority)) {
			if ("zhangsan".equals(username) && "123".equals(password)) {
				setSession(session, username, password, authority);
				request.getRequestDispatcher("filter/index.jsp?username="
				+username +"&authority="+authority).forward(request, response);
			}else{
				failLogin(user,response);
			}
			
		}else if ("2".equals(authority)) {
			if ("lisi".equals(username) && "456".equals(password)) {
				setSession(session, username, password, authority);
				request.getRequestDispatcher("filter/index.jsp?username="
						+username +"&authority="+authority).forward(request, response);
			}else{
				failLogin(user,response);
			}
		}
		//登錄失敗
		else{
			failLogin(user,response);
		}
	}
	
	void failLogin(User user, HttpServletResponse response){
		/*RequestDispatcher rd = request.getRequestDispatcher("sessionlogin.jsp");
		try {
			rd.forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}*/
		try {
			response.sendRedirect("filter/login.jsp?username="
					+user.getUsername() +"&authority="+user.getAuthority());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	private void setSession(HttpSession session, String username, String password, String authority) {
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		user.setAuthority(authority);
		session.setAttribute("user", user);
	}

}

  

Servlet 過濾器