JAVA Web学习(12)___第9章 过滤器和监听器

2019-08-20  本文已影响0人  岁月静好浅笑安然

第9章 过滤器和监听器

9.1 Servlet过滤器

9.1.1 什么的过滤器

9.1.2 过滤器核心对象

public class LogFilter implements Filter  {}
方法声明 说明
public void init(FilterConfig config) throws ServletException 过滤器初始化方法,该方法在过滤器初始化时调用
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException 对请求进行过滤处理
public void destory 销毁方法以便释放资源

*FilterConfig 接口

方法声明 说明
public String getFilterName() 获取过滤器名字
public ServletContext getServletContext 或是 Servlet上下文
public String getInitParameter(String arg0) 获取过滤器初始化参数值
public Enumeration getInitParameterNames() 获取过滤器所有初始化参数
public void doFilter(ServletRequest arg0, ServletResponse arg1,
            FilterChain arg2) throws IOException, ServletException {
        
    }

9.1.3 过滤器创建和配置

public class MyFilter  implements Filter{

    @Override
    public void destroy() {
        
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
            FilterChain arg2) throws IOException, ServletException {
        
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        
            
    }

}

<?xml version="1.0" encoding="UTF-8"?>  
<web-app>  
<filter>
  <filter-name>LogFilter</filter-name>
  <filter-class>com.runoob.test.LogFilter</filter-class>
  <init-param>
    <param-name>Site</param-name>
    <param-value>菜鸟教程</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>LogFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>  

示例代码
统计站点访问次数,初始化访问值为5000
*MyFilter.java

package com.hwp.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;
import javax.servlet.http.HttpServletRequest;

public class MyFilter implements Filter{
    private int count;
    @Override
    public void destroy() {
        
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
            FilterChain arg2) throws IOException, ServletException {
            //访问量自增
            count++;
            HttpServletRequest httpServletRequest=(HttpServletRequest)arg0;
            ServletContext context= httpServletRequest.getSession().getServletContext();
            //将来访数量传递到 ServletContext中
            context.setAttribute("count", count);
            //向下传递过滤器
            arg2.doFilter(arg0, arg1);
    }   

    @Override
    public void init(FilterConfig arg0) throws ServletException {
            //初始化参数
            String param=arg0.getInitParameter("count");
            //将字符串转换为 int   
            count=Integer.valueOf(param);
    }

}

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
    <filter>
        <filter-name>MyFilter</filter-name>
        <filter-class>com.hwp.filter.MyFilter</filter-class>
        <init-param>
        <param-name>count</param-name>
        <param-value>5000</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>MyFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    

</web-app>

web.xml配置各节点说明

<%@ page language="java" import="java.util.*" 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 href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    
  </head>
  
  <body>
   <h2>
   您是本站第<%= application.getAttribute("count")%>位访客!
   </h2>
</html>

9.1.4 字符编码过滤器

<%@ page language="java" import="java.util.*" 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 href="<%=basePath%>">
    
    <title>图书添加</title>
    
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
   <form action="BookServlet" method="post">
   <table border="1" bordercolor="#66B3FF">
   <tr >
   <td align="center" colspan="2">图书添加信息</td>
   </tr>
   <tr>
   <td>图书编号:</td>
   <td><input type="text" name="num"/></td>
   </tr>
   <tr>
   <td>图书名称:</td>
   <td><input type="text" name="name"/></td>
   </tr>
   <tr>
   <td>作者:</td>
   <td><input type="text" name="author"/></td>
   </tr>
   <tr>
   <td>价格:</td>
   <td><input type="text" name="price"/></td>
   </tr>
   <tr>
   <td align="center" colspan="2"><input type="submit" value="添加"/></td>
   </tr>
   </table>
   </form>
  </body>
</html>

package com.hwp;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BookServlet extends HttpServlet {

    
    private static final long serialVersionUID = 1L;
    public BookServlet() {
        super();
    }

    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        
    }


    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request, response);
    }

    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        PrintWriter printWriter = response.getWriter();
        String num=request.getParameter("num");
        String name=request.getParameter("name");
        String author=request.getParameter("author");
        String price=request.getParameter("price");
        printWriter.print("<h2>图书信息添加成功</h2><hr>");
        printWriter.print("图书编号:"+num+"<br>");
        printWriter.print("书名:"+name+"<br>");
        printWriter.print("作者:"+author+"<br>");
        printWriter.print("价格:"+price+"<br>");
        printWriter.flush();
        printWriter.close();
    }

    
    public void init() throws ServletException {
        
    }

}

*AddFilter.java

package com.hwp;


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 AddFilter implements Filter {

    String encoding = null;

    public void destroy() {
        encoding = null;
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain arg2) throws IOException, ServletException {
        if (encoding != null) {
            request.setCharacterEncoding(encoding);
            response.setContentType("text/html; charset=" + encoding);
        }
        arg2.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        encoding = arg0.getInitParameter("encoding");
    }



}

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>

    <filter>
        <filter-name>AddFilter</filter-name>
        <filter-class>com.hwp.AddFilter</filter-class>
        <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>AddFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  <servlet>
    <servlet-name>BookServlet</servlet-name>
    <display-name>This is the display name of my J2EE component</display-name>
    <description>This is the description of my J2EE component</description>
    <servlet-class>com.hwp.BookServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>BookServlet</servlet-name>
    <url-pattern>/BookServlet</url-pattern>
  </servlet-mapping>
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

9.2 Servlet监听器

9.2.1 Servlet监听器简介

序号 接口
1 ServletContextListener
2 ServletContextAttributeListener
3 HttpSessionListener
4 HttpSessionActivationListener
5 HttpSessionAttributrListener
6 HttpSessionBindingListener
7 ServletRequestListener
8 ServletRequestAttributeListener
序号 接口
1 ServletContextEvent
2 ServletContextAttributeEvent
3 HttpSessionEvent
4 HttpSessionRequestEvent
5 HttpSessionAttributeEvent
6 HttpSessionBindingEvent

9.2.2 Servlet监听器原理

9.2.3 Servlet上下文监听

public class MyListener implements ServletContextListener {
    //通知正在收听的对象,应用程序已经被载出,即关闭
    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
        
    }
    //通知正在收听的对象,应用程序已经被加载,即初始化
    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
        
    }

}
 <listener>
  <listener-class>com.hwp.MyListener</listener-class>
  </listener>
上一篇下一篇

猜你喜欢

热点阅读