Servlet 过滤器

Posted work hard work smart

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Servlet 过滤器相关的知识,希望对你有一定的参考价值。

 

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 过滤器的主要内容,如果未能解决你的问题,请参考以下文章

是否可以编写一个 servlet 过滤器来检查 HTTP 响应代码? [复制]

Servlet过滤器行为模棱两可?

servlet 过滤器(Filter)

javaweb-Servlet过滤器Filter

为什么我不能在此片段中生成唯一对象数组?

servlet 过滤器中的 StringBuffer 与 StringBuilder