监听servlet创建
java
package com.hspedu.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* 老韩解读
* 1. 当一个类实现了 ServletContextListener
* 2. 该类就是一个监听器
* 3. 该类可以监听的事件 由该类实现的监听接口决定 ,比如 实现ServletContextListener
* , 则该类就可以监听 ServletContext对象的创建和销毁, 以此类推
* 4. HspServletContextListener 就是一个监听者
* 5. 当web应用启动时,就会产生 ServletContextEvent 事件, 会调用监听器的对应事件处理方法
* contextInitialized, 同时会传递 事件对象
* 6. 程序员可以通过 ServletContextEvent 事件对象,来获取需要的信息, 然后再进行业务处理
* 7. tomcat怎么知道这个监听器存在 ? 因为我们需要在web.xml中配置
*/
public class HspServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();
System.out.println("HspServletContextListener 监听到 " +
servletContext + " 被创建..");
//如果我们获取到ServletContext 对象..进行业务处理
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();
System.out.println("HspServletContextListener 监听到 " +
servletContext + " 被销毁..");
//比如可以对servletContext 数据进行处理, 或者日志的管理...
System.out.println("进行处理工作.....");
}
}
java
HspHttpSessionListener 监听到 session销毁= FAEC215D4C92B5325848CF7438FC7138
用户id=FAEC215D4C92B5325848CF7438FC7138 离线
HspHttpSessionListener 监听到 session销毁= 2785B79C0D9A36C33CA215EA5C23D254
用户id=2785B79C0D9A36C33CA215EA5C23D254 离线
监听文本属性的变化
java
package com.hspedu.listener;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
public class HspServletContextAttributeListener implements ServletContextAttributeListener {
@Override
public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {
System.out.println("HspServletContextAttributeListener 监听到添加属性.."
+ servletContextAttributeEvent.getName() + "=" + servletContextAttributeEvent.getValue() );
}
@Override
public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {
System.out.println("HspServletContextAttributeListener 监听到删除属性.."
+ servletContextAttributeEvent.getName() + "=" + servletContextAttributeEvent.getValue() );
}
@Override
public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {
System.out.println("HspServletContextAttributeListener 监听到修改属性.."
+ servletContextAttributeEvent.getName() + "=" + servletContextAttributeEvent.getValue() );
}
}
java
package com.hspedu.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class HiServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//给servletContext 对象操作属性
ServletContext servletContext = request.getServletContext();
servletContext.setAttribute("name", "韩顺平教育");
servletContext.setAttribute("name", "老韩教育");
servletContext.removeAttribute("name");
//获取session对象
//Filter
HttpSession session = request.getSession();
session.setAttribute("age", 100);
session.setAttribute("age", 400);
session.removeAttribute("age");
System.out.println("HiServlet 处理完毕....");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
java
HspHttpSessionListener 监听到 session销毁= FAEC215D4C92B5325848CF7438FC7138
用户id=FAEC215D4C92B5325848CF7438FC7138 离线
HspHttpSessionListener 监听到 session销毁= 2785B79C0D9A36C33CA215EA5C23D254
用户id=2785B79C0D9A36C33CA215EA5C23D254 离线
HspRequestListener 监听到 request对象创建
记录访问日志....
访问IP= 127.0.0.1
访问的资源= http://localhost:8080/filter/hi
HspServletContextAttributeListener 监听到添加属性..name=韩顺平教育
HspServletContextAttributeListener 监听到修改属性..name=韩顺平教育
HspServletContextAttributeListener 监听到删除属性..name=老韩教育
HspHttpSessionListener 监听到 session创建= A8714B2384A7FF7505EA20A456952DAC
用户id=A8714B2384A7FF7505EA20A456952DAC 上线
HspHttpSessionAttributeListener 监听到session添加属性age=100
HspHttpSessionAttributeListener 监听到session修改属性age=100
HspHttpSessionAttributeListener 监听到session删除属性age
HiServlet 处理完毕....
HspRequestListener 监听到 request对象被销毁
监听session创建
java
package com.hspedu.listener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class HspHttpSessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
HttpSession session = httpSessionEvent.getSession();
//当session创建时,我们给它设置一个生命周期 30s
session.setMaxInactiveInterval(30);
System.out.println("HspHttpSessionListener 监听到 session创建= " +
session.getId());
System.out.println("用户id=" + session.getId() + " 上线");
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
HttpSession session = httpSessionEvent.getSession();
System.out.println("HspHttpSessionListener 监听到 session销毁= " +
session.getId());
System.out.println("用户id=" + session.getId() + " 离线");
}
}
监听session属性改变
java
package com.hspedu.listener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
public class HspHttpSessionAttributeListener implements HttpSessionAttributeListener {
@Override
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
//HttpSession session = httpSessionBindingEvent.getSession();
System.out.println("HspHttpSessionAttributeListener 监听到session添加属性" +
httpSessionBindingEvent.getName() + "=" + httpSessionBindingEvent.getValue());
}
@Override
public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
HttpSession session = httpSessionBindingEvent.getSession();
System.out.println("HspHttpSessionAttributeListener 监听到session删除属性" +
httpSessionBindingEvent.getName());
}
@Override
public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
System.out.println("HspHttpSessionAttributeListener 监听到session修改属性" +
httpSessionBindingEvent.getName() + "=" + httpSessionBindingEvent.getValue());
}
}
监听request
java
package com.hspedu.listener;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
public class HspRequestListener implements ServletRequestListener {
@Override
public void requestInitialized(ServletRequestEvent servletRequestEvent) {
System.out.println("HspRequestListener 监听到 request对象创建");
ServletRequest servletRequest = servletRequestEvent.getServletRequest();
System.out.println("记录访问日志....");
System.out.println("访问IP= " + servletRequest.getRemoteAddr());
System.out.println("访问的资源= " + ((HttpServletRequest)servletRequest).getRequestURL());
}
@Override
public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
System.out.println("HspRequestListener 监听到 request对象被销毁");
}
}
filter过滤器的使用
java
<%--
Created by IntelliJ IDEA.
User: 韩顺平
Version: 1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>管理后台登录</title>
</head>
<body>
<h1>管理后台登录</h1>
<%
System.out.println("request=" + request);
%>
<form action="<%=request.getContextPath() %>/login" method="post">
u:<input type="text" name="username"/> <br/><br/>
p:<input type="password" name="password"/> <br/><br/>
<input type="submit" value="用户登录"/></form>
</body>
</html>
java
package com.hspedu.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginCheckServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取到用户名和密码->DB
//假设密码是123456, 就可以通过
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("request=" + request);
if("123456".equals(password)) {
//合法, 讲用户名,加入session
request.getSession().setAttribute("username", username);
//请求转发到admin.jsp
request.getRequestDispatcher("/manage/admin.jsp")
.forward(request,response);
} else {
//不合法, 返回登录页面
request.getRequestDispatcher("/login.jsp")
.forward(request,response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
为其添加过滤器
java
package com.hspedu.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* 老韩解读
* 1. filter在web项目启动时, 由tomcat 来创建filter实例, 只会创建一个
* 2. 会调用filter默认的无参构造器, 同时会调用 init方法, 只会调用一次
* 3. 在创建filter实例时,同时会创建一个FilterConfig对象,并通过init方法传入
* 4. 通过FilterConfig对象,程序员可以获取该filter的相关配置信息
* 5. 当一个http请求和该filter的的url-patter匹配时,就会调用doFilter方法
* 6. 在调用doFilter方法时,tomcat会同时创建ServletRequest 和 ServletResponse 和 FilterChain对象
* , 并通过doFilter传入.
* 7. 如果后面的请求目标资源(jsp,servlet..) 会使用到request,和 response,那么会继续传递
* 8. 老师的提醒:到javaweb - ssm - springboot , 有 浏览器和 web服务器(tomcat)参与, 而这两个部分不是我们
* 程序员自己写,所以理解起来比 java se要困难!!!
*/
public class ManageFilter implements Filter {
private int count = 0;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//当Tomcat 创建 Filter创建,就会调用该方法,进行初始化
//老韩提醒:回忆我们自己实现tomcat底层机制+servlet程序, 就会了然
//
System.out.println("ManageFilter init被调用...");
}
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
System.out.println("ManageFilter doFilter() 被调用=" + (++count));
//到每次调用该filter时,doFilter就会被调用
//如果这里,没有调用继续请求的方法,则就停止
//如果继续访问目标资源-> 等价于放行
//老师说明:在调用过滤器前,servletRequest对象=request已经被创建并封装
//所以:我们这里就可以通过servletRequest获取很多信息, 比如访问url , session
//比如访问的参数 ... 就可以做事务管理,数据获取,日志管理等
//获取到session
//可以继续使用 httpServletRequest 方法.
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
System.out.println("输入密码=" + httpServletRequest.getParameter("password"));
HttpSession session = httpServletRequest.getSession();
//获取username session对象, 还可以继续使用
Object username = session.getAttribute("username");
if (username != null) {
//老韩解读filterChain.doFilter(servletRequest, servletResponse)
//1. 继续访问目标资源url
//2. servletRequest 和 servletResponse 对象会传递给目标资源/文件
//3. 一定要理解filter传递的两个对象,再后面的servlet/jsp 是同一个对象(指的是在一次http请求)
System.out.println("servletRequest=" + servletRequest);
System.out.println("日志信息==");
System.out.println("访问的用户名=" + username.toString());
System.out.println("访问的url=" + httpServletRequest.getRequestURL());
System.out.println("访问的IP=" + httpServletRequest.getRemoteAddr());
filterChain.doFilter(servletRequest, servletResponse);
} else {//说明没有登录过..回到登录页面
servletRequest.getRequestDispatcher("/login.jsp").
forward(servletRequest, servletResponse);
}
}
@Override
public void destroy() {
//当filter被销毁时,会调用该方法
System.out.println("ManageFilter destroy()被调用..");
}
}
最终到达的页面
java
<%--
Created by IntelliJ IDEA.
User: 韩顺平
Version: 1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>后台管理</title>
<base href="<%=request.getContextPath() %>/manage/"/>
</head>
<body>
<h1>后台管理</h1>
<%
//验证request对象是和前面的filter是一个对象
System.out.println("request=" + request);
%>
<a href="#">用户列表</a>||<a href="#">添加用户</a>||<a href="#">删除用户</a>
<hr/>
<img src="shunping.jpg" height="300"/>
</body>
</html>
过滤的进一步使用
java
package com.hspedu.filter;
import javax.servlet.*;
import java.io.IOException;
import java.util.Enumeration;
/**
* 老师解读: 演示FilterConfig使用
*
*/
public class HspFilterConfig implements Filter {
private String ip; //从配置获取的ip
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("HspFilterConfig init() 被调用..");
//通过filterConfig 获取相关的参数
String filterName = filterConfig.getFilterName();
ip = filterConfig.getInitParameter("ip");
ServletContext servletContext = filterConfig.getServletContext();
//可以获取到该filter所有的配置参数名
Enumeration<String> initParameterNames =
filterConfig.getInitParameterNames();
//遍历枚举
while (initParameterNames.hasMoreElements()) {
System.out.println("名字=" + initParameterNames.nextElement());
}
System.out.println("filterName= " + filterName);
System.out.println("ip= " + ip);
System.out.println("servletContext= " + servletContext);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//通过forbidden ip 来进行控制
//先获取到访问ip
String remoteAddr = servletRequest.getRemoteAddr();
if(remoteAddr.contains(ip)) {
System.out.println("封杀该网段..");
servletRequest.getRequestDispatcher("/login.jsp").
forward(servletRequest,servletResponse);
return; //直接返回
}
//继续访问目标资源
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
java
<filter>
<filter-name>config</filter-name>
<filter-class>
com.hspedu.filter.HspFilterConfig
</filter-class>
<init-param>
<param-name>ip</param-name>
<param-value>127.0</param-value>
</init-param>
<init-param>
<param-name>port</param-name>
<param-value>8888</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>config</filter-name>
<url-pattern>/abc/*</url-pattern>
</filter-mapping>
过滤器作业、
java
<%--
Created by IntelliJ IDEA.
User: 韩顺平
Version: 1.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>发表对阿凡达电影评论</h1>
过滤词: 苹果, 香蕉 ${errorInfo}
<form method="post" action="<%=request.getContextPath()%>/topic/showTopic.jsp">
用户: <input type="text" name="username"><br/>
评论: <textarea rows="10" name="content" cols="20"></textarea><br/>
<input type="submit" value="发表评论">
</form>
</body>
</html>
java
package com.hspedu.filter;
import javax.servlet.*;
import java.io.IOException;
public class TopicFilter implements Filter {
//属性-> 存放禁用词
private String[] forbiddenWords = null;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//获取禁用词
String forbiddenword = filterConfig.getInitParameter("forbid");
forbiddenWords = forbiddenword.split(",");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//解决从topic.jsp 提交的中文乱码问题
servletRequest.setCharacterEncoding("utf-8");
//判断评论是不是有禁用词
String content = servletRequest.getParameter("content");
//循环遍历一把,看看有没有禁用词
for (String forbiddenWord : forbiddenWords) {//java基础
if (content.contains(forbiddenWord)) {
//返回topic.jsp
servletRequest.setAttribute("errorInfo", "你输入的有禁用词");
servletRequest.getRequestDispatcher("/topic.jsp")
.forward(servletRequest, servletResponse);
return;//返回
}
}
//继续到目标
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
过滤链
java
package com.hspedu.filter;
import javax.servlet.*;
import java.io.IOException;
public class AFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("AFilter---> 线程id=" +
Thread.currentThread().getId());
System.out.println("AFilter doFilter 的前置代码...");
System.out.println("执行 AFilter doFilter()");
filterChain.doFilter(servletRequest, servletResponse);
System.out.println("AFilter doFilter 的后置代码...");
}
@Override
public void destroy() {
}
}
java
package com.hspedu.filter;
import javax.servlet.*;
import java.io.IOException;
public class BFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("BFilter---> 线程id=" +
Thread.currentThread().getId());
System.out.println("BFilter doFilter 的前置代码...");
System.out.println("执行 BFilter doFilter()");
filterChain.doFilter(servletRequest, servletResponse);
System.out.println("BFilter doFilter 的后置代码...");
}
@Override
public void destroy() {
}
}