题目

  1. ServletFilter生命周期
  2. ServletFilter处理乱码
  3. ServletFilter权限控制

实现

生命周期

初始化

启动web服务器(如:Tomcat)的时候,ServletFilter就初始化启动了

过滤

只要监听到前台浏览器有动作就马上doFilter做过滤的动作

销毁

Tomcat服务器关闭时,ServletFilter也同时销毁

处理乱码

把所有字符编码提前过滤设置成统一编码
方便以后编写与维护,一个filter全部通用
输入中文用户名

没出现乱码

权限控制

检查用户是否登陆,如果用户没有登陆,则跳转到登陆页面,反之,则正常访问
用户没登陆,始终不能访问success.jsp

检查到用户已登录,正常访问success.jsp

工程截图

代码

ServletFilter生命周期

package 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;
public class MyFilter implements Filter {
/*
 * 演示ServletFilter的生命周期
 * 1.启动web服务器(如:Tomcat)的时候,ServletFilter就初始化启动了
 * 2.只要监听到前台浏览器有动作就马上doFilter做过滤的动作
 * 3.Tomcat服务器关闭时,ServletFilter也同时销毁
 * 
 */
	public MyFilter() {
		System.out.println("Constuctor!");
	}
	@Override
	public void destroy() {
		System.out.println("Filter Destroy!");
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("Filter Init!");
	}
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		System.out.println("Filter Start!");
		arg2.doFilter(arg0, arg1);
		System.out.println("Filter Doing!");

	}

}

ServletFilter处理乱码

package 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;
/*
 * 字符编码过滤
 * 把所有字符编码提前过滤设置成统一编码
 * 方便以后编写与维护,一个filter全部通用
 */
public class CharacterEncodingFilter implements Filter {

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		chain.doFilter(request, response);
	}

}

ServletFilter权限控制

 package filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class PermissionFilter implements Filter {
   /*
    * 访问权限过滤
    * 检查用户是否登陆,如果用户没有登陆,则跳转到登陆页面,反之,则正常访问
    * 
    */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//强转ServletRequest,ServletResponse 为HttpServletRequest,HttpServletResponse
		HttpServletRequest req=(HttpServletRequest)request;
		HttpServletResponse rsp=(HttpServletResponse)response;
		//得到request的路径
		String path= req.getServletPath();
		//如果路径包含success那么就得到session
		if(path.startsWith("/success")) {
			HttpSession session=req.getSession();
			//如果session为空,说明用户没有登陆过,重定向登陆网页
			if(session==null) {
				rsp.sendRedirect(req.getContextPath()+"/login.jsp");
				//否则session不为空,得到session对象
			}else {
				String username=(String)session.getAttribute("username");
				//如果得到的session对象username为空,说明没有登陆过,重定向登陆网页
				if(username==null) {
					rsp.sendRedirect(req.getContextPath()+"/login.jsp");
				}
			}
		}	//doFilter进行过滤
		chain.doFilter(request, response);
	}
}

LoginServlet测试处理

	package filter;
	
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 LoginServlet extends HttpServlet {
		private static final long serialVersionUID = 1L;
	       	    
		protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			//字符设置编码写到CharacterEncodingFilter里了,这里无需再写
			//得到login.jsp传过来的username
			String username=request.getParameter("username");
			System.out.println(username);
			//把用户名放到session中,方便PermissionFilter调用检查与过滤
			request.getSession().setAttribute("username", username);
			//向浏览器输出用户名,看是否是乱码
				PrintWriter out = response.getWriter();
				out.println("用户名是:"+username);	
		}		
		protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			doGet(request, response);
		}
	
	}

login.jsp登陆测试页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/login"  method="post">
Name:<input name="username" type="text"><br>
<input type="submit" value="提交">
</form>
</body>
</html>

success.jsp登陆成功页

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
登陆成功后才可以看到的页面!

</body>
</html>

web.xml

ServletFilter标记对的写法与servlet相似,注意 /* 表示过滤所有的请求

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>06-13-filter</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>filter.MyFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <filter>
    <display-name>CharacterEncodingFilter</display-name>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>filter.CharacterEncodingFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <servlet>
    <servlet-name>CharacterEncodingFilter</servlet-name>
    <servlet-class>filter.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CharacterEncodingFilter</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>
  <filter>
    <display-name>PermissionFilter</display-name>
    <filter-name>PermissionFilter</filter-name>
    <filter-class>filter.PermissionFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>PermissionFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>