zoukankan      html  css  js  c++  java
  • Servlet过滤器创建与配置

    例1 创建一个过滤器,实现网站访问计数器的功能,并在web.xml文件的配置中,将网站访问量的初始值设置为5000。

    (1)创建名称为CountFilter的类,该类实现javax.servlet.Filter接口,是一个过滤器对象,通过该过滤器实现统计网站访问人数的功能。关键代码如下:

    package com.cn.gao;
    
    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 CountFilter implements Filter {
        //来访数量
        private int count;
        public void destroy() {
            // TODO Auto-generated method stub
    
        }
    
        public void doFilter(ServletRequest request, ServletResponse response,
                FilterChain chain) throws IOException, ServletException {
            count++;  //访问数量自增
            //将ServletRequest转换成HttpServletRequest
            HttpServletRequest req = (HttpServletRequest) request;
            //获取ServletContext
            ServletContext context = req.getSession().getServletContext();
            context.setAttribute("count", count);   //将来访数量值放入到ServletContext中
            chain.doFilter(request, response);  //向下传递过滤器
    
        }
    
        public void init(FilterConfig filterConfig) throws ServletException {
            String param = filterConfig.getInitParameter("count"); //获取初始化参数
            count = Integer.valueOf(param); //将字符串转换为int
        }
    
    }

    计数器count变量的值在CountFilter类的doFilter()方法中被递增,因为客户端在请求服务器中的Web应用时,过滤器拦截请求通过doFilter()方法进行过滤处理,所以,当客户端请求Web应用时,计数器count的值将自增1。为了能够访问计数器中的值,实例中将其放置于Servlet上下文中,Servlet上下文对象通过将ServletRequest转换为HttpServletRequest对象后获取。

    (2)配置已创建的CountFilter对象,此操作通过配置web.xml文件进行实现。关键代码如下:

    <?xml version="1.0" encoding="gbk"?>
    <web-app version="2.5" 
        xmlns="http://java.sun.com/xml/ns/javaee" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      <!-- 过滤器声明 -->
      <filter>
          <filter-name>CountFilter</filter-name> 
          <filter-class>com.cn.gao.CountFilter</filter-class>
          <init-param>
              <param-name>count</param-name>
              <param-value>5000</param-value>
          </init-param>
      </filter>
          <filter-mapping>
              <filter-name>CountFilter</filter-name>
              <url-pattern>/index.jsp</url-pattern>
          </filter-mapping>
    </web-app>

    注意:如果直接对过滤器对象中的成员变量进行赋值,那么在过滤器被编译后将不可修改,所以,实例中将过滤器对象中的成员变量定义为过滤器的初始化参数,从而提高代码的灵活性。

    (3)创建程序中的首页index.jsp页面,在该页面中通过JSP内置对象Application获取计数器的值。关键代码如下:

    <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
    <%
    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">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
      </head>
      
      <body>
        <h2>
            欢迎光临,<br/>
            您是本站的第【
            <%=application.getAttribute("count") %>
            】位访客!
        </h2>
      </body>
    </html>

    由于在web.xml文件中将计数器的初始值设置为5000,所以实例运行后,计数器的数值变为大于5000的数,每次刷新页面都会增加1,多次刷新页面后,实例运行结果如下图所示:

  • 相关阅读:
    java8 file转base64
    springboot下maven分环境打包
    maven加载src下的xml文件
    ue正则
    springboot 深坑
    解压版mysql 错误-mysql启动失败
    spring整合activeMQ
    maven分环境 打包
    logger日志配置
    hadoop安装
  • 原文地址:https://www.cnblogs.com/gaopeng527/p/4437089.html
Copyright © 2011-2022 走看看