08.过滤器(Filter),监听器((Listener))
1、过滤器(Filter)
在请求传入Servlet之前以及Servlet相应请求到浏览器之前进行的追加操作的一种程序。(保安)
应用场景:
在服务程序执行之前需要执行的重复操作就可以通过过滤器进行。
创建过程
创建Java类
实现Filter接口
重写
doFilter
init
destory
2、监听器(Listener)
(作用)域监听器
request ServletRequestListener
session HttpSessionListener
applicaiton ServletContextListener
创建
request requestInitialized
application contextInitialized
session sessionCreated
销毁
request requestDestroyed
application contextDestroyed
session sessionDestroyed
属性
application ServletContextAttributeListener
attributeAdded:添加元素触发监听器的该方法
attributeRemoved:删除元素触发监听器的该方法
attributeReplaced:修改元素触发监听器的该方法
session HttpSessionAttributeListener
attributeAdded:添加元素触发监听器的该方法
attributeRemoved:删除元素触发监听器的该方法
attributeReplaced:修改元素触发监听器的该方法
request ServletRequestAttributeListener
attributeAdded:添加元素触发监听器的该方法
attributeRemoved:删除元素触发监听器的该方法
attributeReplaced:修改元素触发监听器的该方法xxxxxEvent getName:获得当前添加/删除/修改的key getValue:获得当前添加/删除/修改的value
监听器的创建
1)、创建一个Java类
2)、实现监听器接口
3)、重写监听器方法
init:域对象初始化调用该方法
destory:域对象被销毁的时候调用该方法
4)、配置监听器
在Web.xml文件中
<listener>
<listener-class>
监听器的全类名(报名.类名)
</listener-class>
</listener>
*配置多个监听器,需要使用多个listener标签
过滤器案例:
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>
<h2>欢迎来到index.jsp</h2>
<h3>${name }</h3>
</body>
</html>
<%@ 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>
<form action="servlets" method="post">
用户名:<input type="text" name="name" /><br/>
<input type="submit" value="提交"/>
</form>
<hr/>
<a href="request?name=小王">点我提交</a>
</body>
</html>
Filter
package com.zuxia.Filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyFilter01 extends HttpFilter{
@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("过滤器开始执行");
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("初始化过滤器");
}
}
package com.zuxia.Filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class MyFilter02 extends HttpFilter {
//设置公共编码变量
private String filterFig;
@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
//设置输出编码
request.setCharacterEncoding(filterFig);
//放行
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("过滤器初始化了");
filterFig= filterConfig.getInitParameter("encoding");
System.out.println(filterFig);
}
}
servlet
package com.zuxia.servelt;
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("/servlets")
public class MyServlet01 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
System.out.println(name);
request.setAttribute("name", name);
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
package com.zuxia.servelt;
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("/request")
public class MyServlet02 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
System.out.println(name);
request.setAttribute("name", name);
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
案例1:
<%@ 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>
<a href="hello?age=25">发起请求</a>
</body>
</html>
<%@ 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>
${msg }
</body>
</html>
controller
package com.zuxia.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("/hello")
public class MyServlet01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("请求已经到服务器了");
request.setAttribute("msg", "我是从服务器回来的参数");
request.getRequestDispatcher("page02.jsp").forward(request, response);
}
}
filter
package com.zuxia.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 {
/**
* 过滤方法,过滤执行的核心方法
* */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("过滤器执行了");
int age = Integer.parseInt(request.getParameter("age"));
//验证用户输入的年龄是否有合法
if(age>=18) {
chain.doFilter(request, response);
}else {
request.setAttribute("msg", "未成年人禁止入内");
request.getRequestDispatcher("page02.jsp").forward(request, response);
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//过滤器对象在初始化的时候会调用该方法
//服务器启动的时候,执行会执行一次该
System.out.println("过滤器初始化了");
}
@Override
public void destroy() {
//过滤器对象在销毁的时候会调用该方法
//服务器关闭的时候会执行,只会执行一次
System.out.println("过滤器被销毁了");
}
}
案例2:
<%@ 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>
<a href="login?name=小明">login</a>
<a href="register?name=小王">register</a>
<form action="login" method="post">
<input type="text" name="name"><input type="submit" value="提交到login">
</form>
<form action="register" method="post">
<input type="text" name="name"><input type="submit" value="提交到register">
</form>
</body>
</html>
filter
package com.zb.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class MyFilter01 implements Filter {
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
System.out.println("过滤器执行了");
arg2.doFilter(arg0, arg1);
}
/*
* 1、实现Filter接口
* 2、重写方法
* init:初始化方法
* filterConfig:用户获取过滤器的配置信息
* getFilterName:获取过滤器的配置名称
* getServletContext:获取Application作用域对象
* destory:销毁方法
* doFilter:过滤器核心的过滤方法
* 3、配置Filter
* */
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println(filterConfig.getFilterName());
//获得Application作用域
ServletContext application = filterConfig.getServletContext();
application.setAttribute("f1Value", "我是通过过滤器中添加的一个application作用域参数");
//获取过滤器的初始化参数
String str = filterConfig.getInitParameter("className");
System.out.println(str);
}
@Override
public void destroy() {
//释放资源
}
}
package com.zb.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyFilter02 extends HttpFilter {
@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
System.out.println("过滤器执行了,该过滤器设置了字符集");
//放行
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
package com.zb.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyFilter03 extends HttpFilter{
@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("我是第一个过滤器");
chain.doFilter(request, response);
}
}
package com.zb.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyFilter04 extends HttpFilter{
@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("我是第二个过滤器");
chain.doFilter(request, response);
}
}
servlet
package com.zb.servlet;
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 MyServlet01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
System.out.println(name);
System.out.println("login Servlet访问到了");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
System.out.println(name);
System.out.println("register Servlet访问到了");
}
}
package com.zb.servlet;
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("/register")
public class MyServlet02 extends HttpServlet {
/**
* 处理GET请求的乱码,无法通过单纯的设置request对象的characterEncoding来进行设置
* 1、通过tomcat设置地址栏所使用的字符集
* server.xml
* <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>
* 2、重新编码
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
System.out.println(name);
System.out.println("register Servlet访问到了");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
System.out.println(name);
System.out.println("register Servlet访问到了");
}
}
案例3:
<%@ 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>
version:${applicationScope.version }
userName:${sessionScope.userName }
<a href="test">执行Servlet中的session销毁操作</a>
</body>
</html>
servlet
package com.zuxia.servlet;
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;
import javax.servlet.http.HttpSession;
@WebServlet("/test")
public class MyTestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getServletContext().setAttribute("version", "5.5 Final");
System.out.println("servlet执行了");
HttpSession session = req.getSession();
System.out.println("Session被手动销毁了");
session.invalidate();
}
}
监听器案例:
案例1:
package javaWebSenoirDemo09;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyServletContextListener implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("监听到ServletContext容器被创建啦,服务器启动时进行创建ServletContext操作");
ServletContext application = sce.getServletContext();
application.setAttribute("version", "1.5 Final");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("监听到ServletContext容器被销毁啦,服务器关闭时进行销毁ServletContext操作");
}
}
package javaWebSenoirDemo09;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
* 监听Session对象被创建和销毁的
* @author Administrator
*
*/
public class MySessionListener implements HttpSessionListener {
/**
* 在创建Session的时候(当一个用户访问服务器中的某个内容的时候,会话开始建立)执行该方法
*/
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("创建了一个新的Session会话");
HttpSession session = se.getSession();
session.setAttribute("userName", "张三");
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("销毁了一个Session会话");
}
}
案例2:
<%@ 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>
contextPath:${path }
<a href="page02.jsp">page02.jsp</a>
<a href="toPage02">page02.jsp</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Page02</h1>
</body>
</html>
listener
package com.zb.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ApplicationListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("监听器启动了");
String path = sce.getServletContext().getContextPath();
sce.getServletContext().setAttribute("path", path);
}
}
package com.zb.listener;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
public class MyRequestListener implements ServletRequestListener {
@Override
public void requestInitialized(ServletRequestEvent sre) {
System.out.println("请求创建了");
ServletRequest request = sre.getServletRequest();
Object path = request.getServletContext().getAttribute("path");
System.out.println(path);
}
@Override
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("请求销毁了");
}
}
package com.zb.listener;
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("/toPage02")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//req.getRequestDispatcher("page02.jsp").forward(req, resp);;
resp.sendRedirect("page02.jsp");
}
}
案例3:
<%@ 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>
<%
application.setAttribute("name", "消化吗");
session.setAttribute("sex", "男");
%>
<a href="removeApplicationAttribute">移除一个元素</a>
</body>
</html>
listener
package com.zb.listener;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
public class ApplicationAttributeListener implements ServletRequestListener,ServletContextAttributeListener, HttpSessionAttributeListener,ServletRequestAttributeListener {
/**
* Application相关
*/
@Override
public void attributeAdded(ServletContextAttributeEvent event) {
System.out.println("添加操作执行");
System.out.println(event.getName());
System.out.println(event.getValue());
}
@Override
public void attributeRemoved(ServletContextAttributeEvent event) {
System.out.println("移除操作执行");
}
@Override
public void attributeReplaced(ServletContextAttributeEvent event) {
System.out.println("替换操作执行");
}
/**
* Session相关
*/
@Override
public void attributeAdded(HttpSessionBindingEvent event) {
System.out.println(event.getName());
System.out.println(event.getValue());
}
@Override
public void attributeRemoved(HttpSessionBindingEvent event) {
}
@Override
public void attributeReplaced(HttpSessionBindingEvent event) {
}
@Override
public void attributeAdded(ServletRequestAttributeEvent srae) {
}
@Override
public void attributeRemoved(ServletRequestAttributeEvent srae) {
}
@Override
public void attributeReplaced(ServletRequestAttributeEvent srae) {
}
}
servlet
package com.zb.servlet;
import java.io.IOException;
import javax.servlet.ServletContext;
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("/removeApplicationAttribute")
public class MyServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext application = req.getServletContext();
System.out.println("在Servlet中执行了移除application作用域中的内容");
application.removeAttribute("name");
}
}
练习:
1、使用过滤器完成用户登录状态验证功能
要求:当用户处于未登录状态,则不能访问页面中除了登录与注册以外的任何页面。登录与注册页面名称在Web.xml中通过配置进行设置。
2、使用Session监听器完成用户登录记录功能
要求:在用户每次登录时记录用户的登录时间,以便于在下一次提醒用户上次登录的时间。
3、使用ServletContext监听器记录当前项目名称
要求:在ServletContext中记录当前项目的名称,以便在任何页面可以随时取出打印
4、使用Session监听器
5、预习HttpServletRequest监听器的使用
6、预习属性监听器的使用
预习练习:使用属性监听器监听用户每次请求的类型
首页
<%@ 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>
<h1>欢迎${sessionScope.userName }使用!</h1>
</body>
</html>
登录页面
<%@ 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>
<form action="user" method="post">
<input type="hidden" name="op" value="login">
账号:<input type="text" name="userUne"><br/>
密码:<input type="text" name="userPwd"><br/>
<input type="submit" value="登录">
</form>
</body>
</html>
注册页面
<%@ 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>
<form action="user" method="post">
<input type="hidden" name="op" value="register">
账号:<input type="text" name="userUne"><br/>
密码:<input type="text" name="userPwd"><br/>
<input type="submit" value="注册">
</form>
</body>
</html>
dao类
package com.zb.dao;
import java.util.ArrayList;
import java.util.List;
import com.zb.entity.UserInfo;
public class UserDao {
private static List<UserInfo> listUi= new ArrayList<UserInfo>();
/**
* 保存用户信息
* @param ui
* @return
*/
public boolean saveUser(UserInfo ui) {
listUi.add(ui);
return true;
}
/**
* 登录信息验证
* @param userInfo
* @return
*/
public boolean querUserInfoInList(UserInfo userInfo) {
for(UserInfo ui : listUi) {
if(ui.getUserUne().equals(userInfo.getUserUne())&&ui.getUserPwd().equals(userInfo.getUserPwd())) {
return true;
}
}
return false;
}
}
entity类(实体类)
package com.zb.entity;
public class UserInfo {
private String userUne;
private String userPwd;
public String getUserUne() {
return userUne;
}
public void setUserUne(String userUne) {
this.userUne = userUne;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
public UserInfo() {
super();
}
public UserInfo(String userUne, String userPwd) {
super();
this.userUne = userUne;
this.userPwd = userPwd;
}
@Override
public String toString() {
return "UserInfo [userUne=" + userUne + ", userPwd=" + userPwd + "]";
}
}
filter
package com.zb.filter;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginFilter extends HttpFilter {
private String[] epns;
@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
String userName = (String)request.getSession().getAttribute("userName");
/*
String serverName = request.getServerName();
System.out.println(serverName);
int serverPort = request.getServerPort();
System.out.println(serverPort);
String proName = request.getContextPath();
System.out.println(proName);
*/
String path = request.getServletPath();
//System.out.println(path);
if(userName==null||userName.equals("")) {
boolean isDoFilter = false;
for(String epn:epns) {
if(path.indexOf(epn)>-1) {
isDoFilter = true;
break;
}
}
if(isDoFilter) {
chain.doFilter(request, response);
}else {
response.sendRedirect("login.jsp");
}
}else {
chain.doFilter(request, response);
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String excludePageName = filterConfig.getInitParameter("excludePage");
epns = excludePageName.split(",");
}
}
servlet
package com.zb.servlet;
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;
import com.zb.dao.UserDao;
import com.zb.entity.UserInfo;
@WebServlet("/user")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String op = request.getParameter("op");
UserDao ud = new UserDao();
if("register".equals(op)) {
String userName = request.getParameter("userUne");
String passWord = request.getParameter("userPwd");
ud.saveUser(new UserInfo(userName, passWord));
response.sendRedirect("login.jsp");
}else if("login".equals(op)) {
String userName = request.getParameter("userUne");
String passWord = request.getParameter("userPwd");
boolean bl = ud.querUserInfoInList(new UserInfo(userName, passWord));
if(bl) {
request.getSession().setAttribute("userName", userName);
response.sendRedirect("index.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>
<h3>欢迎来到index.jsp</h3>
<h3>上一次登录时间是:${sessionScope.time }</h3>
<h3>项目名称:${applicationScope.system }</h3>
<hr/>
请求:${get }
</body>
</html>
登录页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<form action="login" method="post">
用户名:<input type="text" name="name"/><br/>
密 码:<input type="text" name="pwd"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
注册页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>request监听</title>
</head>
<body>
<a href="request">request监听</a>
<hr/>
<form action="request" method="post">
<input type="text" name="txt"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
filter
package com.zuxia.cw.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyFilter01 extends HttpFilter {
//定义编码的公共变量
private String encoDing;
@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding(encoDing);
//过滤器判断
if(request.getSession().getAttribute("name") != null) {
//放行
chain.doFilter(request, response);
}else {
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("过滤器初始化");
encoDing = filterConfig.getInitParameter("encoding");
}
}
package com.zuxia.cw.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.http.HttpServletRequest;
public class MyFilter02 implements Filter{
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
//获得request对象和response对象
HttpServletRequest request=(HttpServletRequest)req;
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
if(name.equals("admin")&&pwd.equals("123456")) {
request.getRequestDispatcher("index.jsp").forward(request, resp);
chain.doFilter(request, resp);
}else {
request.getRequestDispatcher("login.jsp").forward(request, resp);
}
//System.out.println(name);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
Filter.super.init(filterConfig);
}
}
listener
package com.zuxia.cw.listener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class LoginListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
//得到当前时间
Date dt = new Date();
//获取session对象
HttpSession session = se.getSession();
session.setAttribute("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dt));
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
}
}
package com.zuxia.cw.listener;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
public class RequestListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("request 监听销毁了");
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
ServletRequest request = sre.getServletRequest();
System.out.println("aa");
}
}
package com.zuxia.cw.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class SystemApplication implements ServletContextListener {
/**
* 销毁ServletContext监听器
*/
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
/**
* 执行ServletContext监听器
*/
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext application = sce.getServletContext();
//得到项目名称
String system = application.getContextPath();
//传项目名称
application.setAttribute("system", system);
}
}
servlet
package com.zuxia.cw.servlet;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
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")
@SuppressWarnings("serial")
public class Servlet01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//接收登录的值
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
//判断
if(name.equals("admin")&&pwd.equals("123456")) {
//session传值
request.getSession().setAttribute("name", name);
//页面内部跳转
request.getRequestDispatcher("index.jsp").forward(request, response);
//session失效
request.getSession().invalidate();
}
}
}
package com.zuxia.cw.servlet;
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("/request")
@SuppressWarnings("serial")
public class Servlet02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("get请求");
request.setAttribute("get", "get请求");
request.getRequestDispatcher("index.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("post请求");
request.setAttribute("get", "post请求");
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}