Java web:过滤器,PPT,学习笔记,注意事项,含个人理解和注释【诗书画唱】


多去记录自己想出或发现,找到的让自己更好理解的个人理解等的部分。——诗书画唱
个人的理解:过滤器就是每次执行servlet或jsp等代码(看过滤器的路径是什么,起作用的范围就是什么)等时会自动共同一起,绑定执行的部分。
1、创建一个过滤器,对所有的jsp页面进行保护,只有访问的页面是login.jsp时,才可以正常显示,访问其他页面时一律自动跳转会login.jsp,强制要求登录。


package com.jy.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/login")
public class LoginServ extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServ() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String act = request.getParameter("act");
//登录成功以后将账号存放到session中:
request.getSession().setAttribute("_userName", act);
request.getRequestDispatcher("center.jsp")
.forward(request, response);
}
}



package com.jy.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RegServ
*/
@WebServlet("/rs")
public class RegServ extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public RegServ() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String userName = request.getParameter("userName");
System.out.println(userName);
}
}


package com.jy.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;
//做乱码处理的过滤器:
@WebFilter("/*")
public class CodeFilter implements Filter {
public CodeFilter() {
// TODO Auto-generated constructor stub
}
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
request.setCharacterEncoding("utf-8");
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}





<%@ page language="java" contentType="text/html;
charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"
+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base hreff="<%=basePath%>">
<title></title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<h1>B站UP主诗书画唱提醒你!欢迎来到购物车页面</h1>
</body>
</html>


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base hreff="<%=basePath%>">
<title></title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<h1>B站UP主诗书画唱提醒你!欢迎来到个人中心!</h1>
</body>
</html>


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base hreff="<%=basePath%>">
<title></title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<form action="ls" method="post">
<input type="text" name="act" />
<input type="submit" value="登录" />
</form>
</body>
</html>


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base hreff="<%=basePath%>">
<title></title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<h1>登录页面</h1>
<form action="login" method="post">
<input type="text" name="act" />
<input type="submit" value="登录" />
</form>
</body>
</html>


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base hreff="<%=basePath%>">
<title></title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<form action="rs" method="post">
<input type="text" name="userName" />
<input type="submit" value="注册" />
</form>
</body>
</html>


运行效果:
当没登录时:





个人的理解:过滤器就是每次执行servlet或jsp等代码(看过滤器的路径是什么,起作用的范围就是什么)等时会自动共同一起,绑定执行的部分。

2、创建一个过滤器,对项目中所有的jsp和servlet进行处理,在运行servlet前,打印出访问当前servlet的日期。


package com.jy.filter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
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;
/**
* Servlet Filter implementation class DateTimeFilter
*/
@WebFilter("/*")
public class DateTimeFilter implements Filter {
/**
* Default constructor.
*/
public DateTimeFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
// pass the request along the filter chain
SimpleDateFormat sdf=new SimpleDateFormat
("yyy-MM-dd HH: mm: ss:SSS");
String str=sdf.format(new Date());
System.out.println("访问当前servlet的日期是: "+str);
chain.doFilter(request, response);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}



3、对项目中所有的jsp和servlet进行保护,除了允许直接访问login.jsp页面外,其他的jsp页面和servlet必须在session中的“_user”属性不为空时才可以访问。

package com.jy.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;
@WebFilter("/*")
public class SecuFilter implements Filter {
public SecuFilter() {
// TODO Auto-generated constructor stub
}
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
//将ServletRequest类型强制转换成HttpServletRequest类型
HttpServletRequest req = (HttpServletRequest)request;
//获取到浏览器地址栏中的url
String url = req.getRequestURI();
System.out.println("访问地址是:" + url);
//当url中包含有login字符串时,不应该进行过滤
if(url.contains("login")) {
//直接放行
chain.doFilter(request, response);
} else {//url中没有包含login,就需要登录验证
//从session中获取用户的登录信息
Object objUserName = req.getSession()
.getAttribute("_userName");
//判断是否登录
if(objUserName == null) {
//如果没有登录,那么就强制跳转到登录页面去
req.getRequestDispatcher("login.jsp")
.forward(request, response);
} else {
//登录了,放行
chain.doFilter(request, response);
}
}
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}










不用chain.doFilter等代码的部分时,servlet的执行效果:















个人的理解:过滤器就是每次执行servlet或jsp等代码(看过滤器的路径为什么,起作用的范围就是什么)等时会自动共同一起,绑定执行的部分。
PPT和学习笔记:
过滤器FILTER介绍
Web应用中,在处理请求时,经常有一些通用的操作,比如设置字符集,添加系统日志记录等。这样的操作需要写在每个servlet的处理方法中,既费力又不好统一修改。使用过滤器就像在这些处理方法前加了几道过滤屏障,将需要进行的操作放到这些过滤屏障里执行,而所有指定的servlet操作都将在通过这些过滤屏障后执行。

FILTER原理
请求发起时,Web容器先判断是否存在过滤器和这个请求的资源相关,如果有存在关联就把请求交给过滤器去处理,在过滤器中可以对请求的内容做出改变,然后再将请求转交给被请求的资源。当被请求的资源做出响应时,Web容器同样会将响应先转发给过滤器,在过滤器中可以对响应做出处理然后再将响应发送给客户端。在这整个过程中客户端和目标资源是不知道过滤器的存在的。

FILTER中的方法
开发一个过滤器必须实现Java定义好的javax.servlet.Filter接口:
这一接口含有三个过滤器必须执行的方法:
●doFilter(ServletRequest, ServletResponse, FilterChain):这是一个完成过滤行为的方法。这同样是上游过滤器调用的方法。引入的FilterChain对象提供了后续过滤器所要调用的信息。如果该过滤器是过滤器链中的最后一个过滤器,则将请求交给被请求资源。也可以直接给客户端返回响应信息。
● init(FilterConfig):由Web容器来调用完成过滤器的初始化工作。它保证了在第一次doFilter()调用前由容器调用。您能获取在 web.xml 文件中指定的初始化参数。
● destroy():由Web容器来调用来释放资源,doFilter()中的所有活动都被该实例终止后,调用该方法。 ● Filter技术只对Post请求起作用

web.xml配置
url-pattern主要有四种匹配方式
1、精确匹配,就是填写jap或Servlet等需要过滤的请求的具体地址,例如:/servlet/MyServlet
2、扩展匹配,由“*”号和扩展名组成,例如*.jsp
3、路径前缀匹配,包含一个目录和一个/* 例如:/Servlet/*指的是对Servlet目录下的所有资源进行过滤
4、全部匹配,使用/*,指的是对所以资源都过滤
在请求资源时,过滤器链中的过滤器依次对请求作出处理。在接受到响应时再按照相反的顺序对响应作出处理。

过滤器在WEB中的应用举例
在WEB开发中常见的应用过滤器的地方:
1、 对用户请求进行统一认证,权限管理
2、 对用户的访问请求进行记录和审核
3、 对用户发送的数据进行过滤和替换
4、 转换图像格式
5、 对响应的内容进行压缩,减少传输量
6、 对请求和响应进行加密处理
