Filter的应用

Filter的应用

使浏览器不缓存页面的过滤器

  • 解释:
    开始的时候,a.html有一个图片的展示,之后手动更换图片的地址之后,若不刷新,则不会显示现在的新图片,这就是浏览器的缓存作用.
  • 思路: 有 3 个 HTTP 响应头字段都可以禁止浏览器缓存当前页面,它们在 Servlet 中的示例代码如下:
    response.setDateHeader(“Expires”,-1);
    response.setHeader(“Cache-Control”,“no-cache”);
    response.setHeader(“Pragma”,“no-cache”);
    并不是所有的浏览器都能完全支持上面的三个响应头,因此最好是同时使用上面的三个响应头

代码如下

package com.atguigu.javaweb.cache;

import java.io.IOException;

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

import com.atguigu.javaweb.HttpFilter;

public class NoCacheFilter extends HttpFilter {

	@Override
	public void doFilter(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		
		System.out.println("cacheFilter's doFilter..");
		
		response.setDateHeader("Expires",-1);
		response.setHeader("Cache-Control","no-cache");
		response.setHeader("Pragma","no-cache");
		
		filterChain.doFilter(request, response);
	}
}

HttpFilter 的源代码在这个博客中

web.xml的配置如下:

<!--url-pattern值的作用: 对/cache下的所有文件进行过滤-->
 <filter>
    <display-name>NoCacheFilter</display-name>
    <filter-name>NoCacheFilter</filter-name>
    <filter-class>com.atguigu.javaweb.cache.NoCacheFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>NoCacheFilter</filter-name>
    <url-pattern>/cache/*</url-pattern>
  </filter-mapping>

字符编码的过滤器

  • 思路 :
    配置参数encoding指明使用何种字符编码,以处理Html Form请求参数的中文问题
  • 代码如下:
package com.atguigu.javaweb.encoding;

import java.io.IOException;

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

import com.atguigu.javaweb.HttpFilter;

public class EncodingFilter extends HttpFilter{

	private String encoding;
	// encoding 的设置在web.xml中
	@Override
	protected void init() {
		encoding = getFilterConfig().getServletContext().getInitParameter("encoding");
	}
	@Override
	public void doFilter(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		System.out.println(encoding); 
		request.setCharacterEncoding(encoding);
		filterChain.doFilter(request, response);
	}
}

web.xml

 <context-param>
  	<param-name>encoding</param-name>
  	<param-value>UTF-8</param-value>
  </context-param>
<filter>
  	<filter-name>encodingFilter</filter-name>
  	<filter-class>com.atguigu.javaweb.encoding.EncodingFilter</filter-class>
  </filter>
  
  <filter-mapping>
  	<filter-name>encodingFilter</filter-name>
  	<url-pattern>/encoding/*</url-pattern>
  </filter-mapping>

检测用户是否登陆的过滤器:

  • 情景:系统中的某些页面只有在正常登陆后才可以使用,用户请求这些页面时要检查 session中有无该用户信息,但在所有必要的页面加上session的判断相当麻烦的事情
  • 解决方案:编写一个用于检测用户是否登陆的过滤器,如果用户未登录,则重定向到指的登录页面
  • 要求:需检查的在 Session 中保存的关键字; 如果用户未登录,需重定向到指定的页面(URL不包括 ContextPath); 不做检查的URL列表(以分号分开,并且 URL 中不包括 ContextPath)都要采取可配置的方式

LoginFilter.java

package com.atguigu.javaweb.login;

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

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.atguigu.javaweb.HttpFilter;

public class LoginFilter extends HttpFilter{

	//1. 从 web.xml 文件中获取 sessionKey, redirectUrl, uncheckedUrls
	private String sessionKey;
	private String redirectUrl;
	private String unchekcedUrls;
	
	@Override
	protected void init() {
		ServletContext servletContext = getFilterConfig().getServletContext();
		//从web.xml中获取Filter的初始化参数
		sessionKey = servletContext.getInitParameter("userSessionKey");
		redirectUrl = servletContext.getInitParameter("rediretPage");
		// /login/a.jsp,/login/list.jsp,/login/login.jsp,/login/doLogin.jsp
		unchekcedUrls = servletContext.getInitParameter("uncheckedUrls");
	}
	
	@Override
	public void doFilter(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		
		//1. 获取请求的 servletPath
		// /login/b.jsp
		String servletPath = request.getServletPath();
		
		//2. 检查 1 获取的 servletPath 是否为不需要检查的 URL 中的一个, 若是, 则直接放行. 方法结束
		List<String> urls = Arrays.asList(unchekcedUrls.split(","));
		if(urls.contains(servletPath)){
			filterChain.doFilter(request, response);
			return;
		}
		//3. 从 session 中获取 sessionKey 对应的值, 若值不存在, 则重定向到 redirectUrl
		Object user = request.getSession().getAttribute(sessionKey);
		if(user == null){
			response.sendRedirect(request.getContextPath() + redirectUrl);
			return;
		}
		//4. 若存在, 则放行, 允许访问. 
		filterChain.doFilter(request, response);
	}
}

web.xml

<!-- 用户信息放入到 session 中的键的名字 -->
  <context-param>
  	<param-name>userSessionKey</param-name>
  	<param-value>USERSESSIONKEY</param-value>
  </context-param>
  
  <!-- 若未登录, 需重定向的页面 -->
  <context-param>
  	<param-name>rediretPage</param-name>
  	<param-value>/login/login.jsp</param-value>
  </context-param>
  
  <!-- 不需要拦截(或检查)的 URL 列表 -->
  <context-param>
  	<param-name>uncheckedUrls</param-name>
  	<param-value>/login/a.jsp,/login/list.jsp,/login/login.jsp,/login/doLogin.jsp,/login/b.jsp</param-value>
  </context-param>
<filter>
  	<filter-name>loginFilter</filter-name>
  	<filter-class>com.atguigu.javaweb.login.LoginFilter</filter-class>
  </filter>
  
  <filter-mapping>
  	<filter-name>loginFilter</filter-name>
  	<url-pattern>/login/*</url-pattern>
  </filter-mapping>

/login下面的文件
a.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>
</head>
<body>
	
	<h4>AAA PAGE</h4>
	
	<a href="list.jsp">Return...</a>
	
</body>
</html>

b.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>
</head>
<body>

	<%-- 
		//检验用户是否登录. 若没有登录, 则直接重定向到 login.jsp
		Object user = session.getAttribute("user");
	
		if(user == null){
			response.sendRedirect("login.jsp");
		}
	--%>
	
	<h4>BBB PAGE</h4>
	
	<a href="list.jsp">Return...</a>
	
</body>
</html>

c.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>
</head>
<body>
	
	<%-- 
		//检验用户是否登录. 若没有登录, 则直接重定向到 login.jsp
		Object user = session.getAttribute("user");
	
		if(user == null){
			response.sendRedirect("login.jsp");
		}
	--%>
	
	<h4>CCC PAGE</h4>
	
	<a href="list.jsp">Return...</a>
	
</body>
</html>

d.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>
</head>
<body>

	<%-- 
		//检验用户是否登录. 若没有登录, 则直接重定向到 login.jsp
		Object user = session.getAttribute("user");
	
		if(user == null){
			response.sendRedirect("login.jsp");
		}
	--%>
	
	<h4>DDD PAGE</h4>
	<a href="list.jsp">Return...</a>
	
</body>
</html>

e.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>
</head>
<body>

	<%-- 
		//检验用户是否登录. 若没有登录, 则直接重定向到 login.jsp
		Object user = session.getAttribute("user");
	
		if(user == null){
			response.sendRedirect("login.jsp");
		}
	--%>
	
	<h4>EEE PAGE</h4>
	<a href="list.jsp">Return...</a>
	
</body>
</html>

list.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>
</head>
<body>
	
	<a href="a.jsp">AAA</a>
	<br><br>
	
	<a href="b.jsp">BBB</a>
	<br><br>
	
	<a href="c.jsp">CCC</a>
	<br><br>
	
	<a href="d.jsp">DDD</a>
	<br><br>
	
	<a href="e.jsp">EEE</a>
	
</body>
</html>

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>
</head>
<body>
	
	<form action="doLogin.jsp" method="post">
		username: <input type="text" name="username"/>
		<input type="submit" value="Submit"/>
	</form>
	
</body>
</html>

doLogin.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>
</head>
<body>
	
	<% 
		//1. 获取用户的登录信息
		String username = request.getParameter("username");
		
		//2. 若登录信息完整, 则把登录信息放到 HttpSession
		if(username != null && !username.trim().equals("")){ 
			session.setAttribute(application.getInitParameter("userSessionKey"), username);
			//3. 重定向到 list.jsp
			response.sendRedirect("list.jsp");
		}else{
			response.sendRedirect("login.jsp");
		}
		
	%>
	
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值