11、Filter(重点)

Filter:过滤器,用来过滤网站的数据;

  • 处理中文乱码
  • 登陆验证...

Filter开发步骤:

  1. 导包

  2. 编写过滤器

    1. 导包不要错

    2. 实现Filter接口,重写对应的方法即可

      public class CharacterEncodingFilter implements Filter {
      
          //初始化:web服务器启动,就已经初始化了,随时等待过滤对象出现!
      public void init(FilterConfig filterConfig) throws ServletException {
      System.out.println("CharacterEncodingFilter初始化");
      } //Chain : 链
      /*
      1. 过滤器中的所有代码,在过滤特定请求的时候都会执行
      2. 必须要让过滤器继续通行
      filterChain.doFilter(servletRequest,servletResponse);
      */
      public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
      servletRequest.setCharacterEncoding("utf-8");
      servletResponse.setCharacterEncoding("utf-8");
      servletResponse.setContentType("text/html;charset=UTF-8"); System.out.println("CharacterEncodingFilter执行前...");
      filterChain.doFilter(servletRequest,servletResponse); //让我们的请求继续走,如果不写,程序到这里就被拦截停止!
      System.out.println("CharacterEncodingFilter执行后...");
      } //销毁:web服务器关闭的时候,过滤器会销毁
      public void destroy() {
      System.out.println("CharacterEncodingFilter销毁");
      }
      }
    3. 在web.xml中配置 Filter

      <servlet>
      <servlet-name>ShowServlet</servlet-name>
      <servlet-class>com.kuang.servlet.ShowServlet</servlet-class>
      </servlet>
      <servlet-mapping>
      <servlet-name>ShowServlet</servlet-name>
      <url-pattern>/servlet/show</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
      <servlet-name>ShowServlet</servlet-name>
      <url-pattern>/show</url-pattern>
      </servlet-mapping> <filter>
      <filter-name>CharacterEncodingFilter</filter-name>
      <filter-class>com.kuang.filter.CharacterEncodingFilter</filter-class>
      </filter>
      <filter-mapping>
      <filter-name>CharacterEncodingFilter</filter-name>
      <!--只要是 /servlet的任何请求,都会经过这个过滤器-->
      <url-pattern>/servlet/*</url-pattern>
      <!--<url-pattern>/*</url-pattern>-->
      </filter-mapping>

12、监听器

实现一个监听器的接口; (有N中)

  1. 编写一个监听器

    实现监听器的接口...

    //统计网站在线人数 : 统计session
    public class OnlineCountListener implements HttpSessionListener { //创建session监听:看你的一举一动
    //一旦创建一个session就会触发一次这个事件!
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
    ServletContext context = httpSessionEvent.getSession().getServletContext(); System.out.println(httpSessionEvent.getSession().getId()); Integer onlineCount = (Integer) context.getAttribute("OnlineCount"); if (onlineCount==null){
    onlineCount = new Integer(1);
    }else {
    int count = onlineCount.intValue();
    onlineCount = new Integer(count+1);
    } context.setAttribute("OnlineCount",onlineCount);
    } //销毁session监听
    //一旦销毁session就会触发一次这个事件!
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
    ServletContext context = httpSessionEvent.getSession().getServletContext();
    Integer onlineCount = (Integer) context.getAttribute("OnlineCount"); if (onlineCount==null){
    onlineCount = new Integer(0);
    }else {
    int count = onlineCount.intValue();
    onlineCount = new Integer(count-1);
    } context.setAttribute("OnlineCount",onlineCount);
    } /*
    Session销毁:
    1. 手动销毁 getSession.invalidate()
    2. 自动销毁 在web.xml中设置session过期时间
    */
    }
  2. web.xml中注册监听器

    <!--注册监听器-->
    <listener>
    <listener-class>com.kuang.listener.OnlineCountListener</listener-class>
    </listener>
  3. 看情况是否使用!

13、过滤器、监听器常见应用

监听器:GUI编程中经常使用;

public class TestPanel1 {
public static void main(String[] args) {
Frame frame = new Frame("中秋节快乐"); //新建一个窗体
Panel panel = new Panel(null); //面板
frame.setLayout(null); //设置窗体的布局 frame.setBounds(50,50,300,300);
frame.setBackground(Color.blue); //设置背景颜色 panel.setBounds(70,70,70,70); //设置背景颜色
panel.setBackground(Color.GREEN); frame.add(panel);
frame.setVisible(true); //监听事件,监听关闭事件,使用适配器
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}

实现:用户登录之后才能进入主页!用户注销后就不能进入主页了!

  1. 用户登陆之后,向Session中放入用户的数据

  2. 进入主页的时候要判断用户是否已经登录;要求:在过滤器中实现!

    //ServletRequest    HttpServletRequest
    HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; if (httpServletRequest.getSession().getAttribute(Constant.USER_SESSION)==null){
    httpServletResponse.sendRedirect("/error.jsp");
    } filterChain.doFilter(servletRequest, servletResponse);

项目全部代码:

public class Constant {
public final static String USER_SESSION = "USER_SESSION";
}
=============================================================
public class LoginServlet extends HttpServlet { @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取前端请求的参数
String username = req.getParameter("username"); if (username.equals("admin")){ //登陆成功
req.getSession().setAttribute(Constant.USER_SESSION,req.getSession().getId());
resp.sendRedirect("/sys/success.jsp");
}else { //登录失败
resp.sendRedirect("/error.jsp");
}
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
==========================================================================
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Object user_session = req.getSession().getAttribute(Constant.USER_SESSION); if (user_session!=null){
req.getSession().removeAttribute(Constant.USER_SESSION);
resp.sendRedirect("/Login.jsp");
}else {
resp.sendRedirect("/Login.jsp");
}
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
===============================================================================
public class SysFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException {
} public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { /*
实现会员分级:
if (req.getSession().setAttribute(Constant.USER_SESSION).level==VIP1){
response.sendRedirect("/vip1/index.jsp");
}
if (req.getSession().setAttribute(Constant.USER_SESSION).level==VIP2){
response.sendRedirect("/vip2/index.jsp");
}
if (req.getSession().setAttribute(Constant.USER_SESSION).level==VIP3){
response.sendRedirect("/vip3/index.jsp");
}
*/ //ServletRequest HttpServletRequest
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; if (httpServletRequest.getSession().getAttribute(Constant.USER_SESSION)==null){
httpServletResponse.sendRedirect("/error.jsp");
} filterChain.doFilter(servletRequest, servletResponse);
} public void destroy() {
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body> <h1>错误</h1>
<h3>没有权限,用户名错误</h3> <p><a href="/Login.jsp">返回登录页面</a></p> </body>
</html>
====================================================================
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body> <h1>主页</h1> <p><a href="/servlet/logout">注销</a></p> </body>
</html>
=======================================================================
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body> <h1>登录</h1> <form action="/servlet/login" method="post">
用户名:<input type="text" name="username"><br>
<input type="submit">
</form> </body>
</html>
========================================================================
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"> <servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.kuang.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/servlet/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.kuang.servlet.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/servlet/logout</url-pattern>
</servlet-mapping>
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.kuang.servlet.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/sys/*</url-pattern>
</filter-mapping> </web-app>

Filter(过滤器)与Listener(监听器)详解的更多相关文章

  1. 15 Filter过滤器和Listener监听器

    1.Filter:过滤器 (1) 概念:生活中的过滤器:净水器,空气净化器,土匪.web中的过滤器:当访问服务器的资源时,过滤器可以将请求拦截下来,完成一些特殊的功能.过滤器的作用:一般用于完成通用的 ...

  2. Java程序员从笨鸟到菜鸟之(二十一)java过滤器和监听器详解 【转】

     过滤器 1.Filter工作原理(执行流程) 当客户端发出Web资源的请求时,Web服务器根据应用程序配置文件设置的过滤规则进行检查,若客户请求满足过滤规则,则对客户请求/响应进行拦截,对请求头和请 ...

  3. java过滤器和监听器详解

    过滤器 1.Filter工作原理(执行流程) 当客户端发出Web资源的请求时,Web服务器根据应用程序配置文件设置的过滤规则进行检查,若客户请求满足过滤规则,则对客户请求/响应进行拦截,对请求头和请求 ...

  4. Java监听器Listener使用详解

    监听器用于监听web应用中某些对象.信息的创建.销毁.增加,修改,删除等动作的发生,然后作出相应的响应处理.当范围对象的状态发生变化的时候,服务器自动调用监听器对象中的方法.常用于统计在线人数和在线用 ...

  5. SpringBoot初始教程之Servlet、Filter、Listener配置详解

    1.介绍 通过之前的文章来看,SpringBoot涵盖了很多配置,但是往往一些配置是采用原生的Servlet进行的,但是在SpringBoot中不需要配置web.xml的 因为有可能打包之后是一个ja ...

  6. javaweb之监听器详解

    在servlet中定义了多种类型的监听器,他们用于监听事件源分别是servletContext,httpsession,servletrequest 这三个域对象. servlet中监听器主要有三类: ...

  7. JavaWeb监听器详解

    1 JavaWeb监听器概述 在JavaWeb被监听的事件源为:ServletContext.HttpSession.ServletRequest,即三大域对象.有监听域对象"创建" ...

  8. Filter及FilterChain的使用详解(转)

    一.Filter的介绍及使用 什么是过滤器? 与Servlet相似,过滤器是一些web应用程序组件,可以绑定到一个web应用程序中.但是与其他web应用程序组件不同的是,过滤器是"链&quo ...

  9. Filter及FilterChain的使用详解

    原文地址:http://blog.csdn.net/zhaozheng7758/article/details/6105749 一.Filter的介绍及使用 什么是过滤器? 与Servlet相似,过滤 ...

随机推荐

  1. 【从小白到专家】收官!Istio技术实践之九:路由控制与灰度发布

    本期是Istio技术实践专题的最后一个模块,主题是Istio的路由控制与灰度发布.上一期我们讲到,虚拟服务(Virtual Service)以及目标规则(Destination Rule)是 Isti ...

  2. JUC之线程池基础

    线程池 定义和方法 线程池的工作时控制运行的线程数量,处理过程中将任务放入队列,然后在线程创建后启动这些任务,如果线程数量超过了最大数量,超出数量的线程排队等候,等待其他线程执行完成,再从队列中取出任 ...

  3. dubbo接口方法重载且入参未显式指定序列化id导致ClassCastException分析

    问题描述&模拟 线上登录接口,通过监控查看,有类型转换异常,具体报错如下图 此报错信息是dubbo consumer端显示,且登录大部分是正常,有少量部分会报类型转换异常,同事通过更换方法名+ ...

  4. 【小记录】cv::cuda::Stream中取出cudaStream_t并用于核函数的计算

    以下是找到的代码 1 cv::cuda::Stream stream; 2 cudaStream_t s = cv::cuda::StreamAccessor::getStream(stream); ...

  5. fidder无法下载证书的最佳解决办法

    为什么有的小伙伴安装fidder不好使,手机无法下载证书? 1.安装一定要去官网安装! 一定要去官网安装! 一定要去官网安装!官方网址:https://www.telerik.com/download ...

  6. Filter-FilterChain多个过滤器执行的细节

    FilterChain过滤器链 Filter   过滤器 Chain  链 FilterChain  就是过滤器链(多个过滤器如何一起工作) 在多个filter过滤器执行时,执行优先顺序由web.xm ...

  7. linux字符编码防止乱码

    一:linux字符编码 en_US.UTF-8 : 美式英文,utf-8 zh_CN.UTF-8 临时优化 export LANG=zh_CN.UTF-8 : 设置编码 永久优化 vim /etc/l ...

  8. 一起玩转玩转LiteOS组件:TinyFrame

    摘要:TinyFrame是一个简单的用于解析串口(如 UART.telnet.套接字等)通信数据帧的库. 本文分享自华为云社区<LiteOS组件尝鲜-玩转TinyFrame>,作者:Lio ...

  9. Loadrunner11录制移动端测试脚本(原文:http://blog.csdn.net/zhailihua/article/details/73610317)

    一.LR配置 1)LR设置代理,利用手机录制脚本 1-协议选择Web(HTTP/HTML)协议即可 2-录制开始前,对Recoding Options中的Port Mapping配置如下 a.新建Ne ...

  10. Codeforces Round #738 (Div. 2)

    Codeforces Round #738 (Div. 2) 跳转链接 A. Mocha and Math 题目大意 有一个长度为\(n\)的数组 可以进行无数次下面的操作,问操作后数组中的最大值的最 ...