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. linux 查看历史命令 history命令

    1.history命令 "history"命令就是历史记录.它显示了在终端中所执行过的所有命令的历史. history //显示终端执行过的命令 history 10 //显示最近 ...

  2. Ubuntu18.04 内核升级

    查看当前版本  在终端输入以下命令并回车 uname -sr  可以发现当前内核为 Linux 4.15.0-88-generic 查看目前最新的稳定内核  访问 The Linux Kernel A ...

  3. 【记录一个问题】opencv官网的opencv android sdk使用opencl并未用到GPU

    UMat u_mat;mat.copyTo(u_mat);cv::cvtColor(u_mat, cv::BGR2GARY);这样的代码反复执行,并未发现GPU占用提升.执行时间与不使用UMat相当. ...

  4. python -m详解

    温馨提示: 本篇演示环境是Python 3.8 先python --help看下python -m参数的解释: -m mod : run library module as a script (ter ...

  5. linux文件压缩与文件夹压缩(打包)

    目录 一:linux文件压缩 1.linux常见的压缩包有哪些? 2.bzip压缩(文件) 二:打包(文件夹压缩) 1.打包命令 2.参数 3.参数解析(实战) 4.注意事项 简介: win中的压缩包 ...

  6. STS中创建 javaweb 项目?

    package com.aaa.readme; /* * 一. * 1.安装Tomcat 版本8.5 * * 2.file---->new------>dynamic java web p ...

  7. MySQL8.0.28安装教程全程参考MySQL官方文档

    前言 为了MySQL8.0.28安装教程我竟然在MySQL官方文档逛了一天,至此献给想入门MySQL8.0的初学者.以目前最新版本的MySQL8.0.28为示例进行安装与初步使用的详细讲解,面向初学者 ...

  8. POJ 1927 Area in Triangle 题解

    link Description 给出三角形三边长,给出绳长,问绳在三角形内能围成的最大面积.保证绳长 \(\le\) 三角形周长. Solution 首先我们得知道,三角形的内切圆半径就是三角形面积 ...

  9. Lesson3——Pandas Series结构

    1 什么是Series结构? Series 结构,也称 Series 序列,是 Pandas 常用的数据结构之一,它是一种类似于一维数组的结构,由一组数据值(value)和一组标签组成,其中标签与数据 ...

  10. opencvsharp 根据row方向和面积筛选连通域的两种方式

    ConnectedComponents cc = Cv2.ConnectedComponentsEx(tempMat);//相当于halcon的connection获取全部连通域 int blobnu ...