Servlet监听器和过滤器基本使用

实验一

使用listener或filter实现session的有效性的判断(例如用户名为null或session失效);修改监听器的代码,实现同一session下的用户名发生改变时,监听器可以对其进行反应,并把新的用户名放入相对应的数组列表中。通过服务器端对客户端的强制刷新达到在线用户列表的在客户端的实时更新。

这里,我们使用Servlet的监听器来实现该功能。

以下是JSP页面代码,实现一个表单页面,用来注册用户。(代码使用了一些bootstrap来美化页面):

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>java webtitle>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <link href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

    
    
    
head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6">
            <h3 class="text-muted">利用监听器判断session是否失效以及判断session变化h3>
            <form style="margin-top: 50px" action="loginConf.jsp" method="post">
                <div class="form-group">
                    <label for="login">注册label>
                    <input type="text" class="form-control" id="login" placeholder="填入用户名:" name="username">
                div>
                <button type="submit" class="btn btn-default">提交button>
            form>
            <a href="UserList.jsp">在线用户列表a>
        div>
    div>
div>

<script src="https://code.jquery.com/jquery.js">script>

<script src="js/bootstrap.min.js">script>
body>
html>

以下为loginConf.jsp,实现将用户名添加进session。

<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>java webtitle>
head>
<body>
  <%
      String username=request.getParameter("username");
      session.setAttribute("username",username);
      /*
      * 以下代码部分实现当用户名发生更改时,通过判断application
      * 中设置的变量状态,执行更新application中用户名集合的功能。
      * */
      String type=(String)application.getAttribute("Usertype");
      if (type!=null){
          String user=(String)session.getAttribute("username");//取出session中username
          ArrayList<String> users=(ArrayList<String>)application.getAttribute("users");//取出用户名集合
          users.add(user);//将username添加进集合
          application.setAttribute("users",users);
          application.setAttribute("Usertype",null);
      }
  %>
<jsp:forward page="index.jsp"/>
body>
html>

以下为UserList.jsp,用来查看在线用户人数及列表(用了JQuery,Ajax部分没有直接用jQuery实现):

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>java webtitle>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <link href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

    
    
    
    <script src="js/jquery-3.2.1.min.js" type="text/javascript">script>

    <%--以下js部分利用ajax实现局部刷新的功能--%>
    <script>
        $(function () {
            setInterval(getnum, 10);//setInterval函数实现每个10毫秒定时执行getnum函数
        });
        function getnum() {
            var xmlhttp;
            var num = 0;
            if (window.XMLHttpRequest) {
                xmlhttp = new XMLHttpRequest();
            }
            else {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    var jsonarray = xmlhttp.responseText;
                    var list = JSON.parse(jsonarray);//将从Servlet中获取的数据转化成json格式
                    var html = "";
                    for (var i = 0; i < list.length; i++) {//遍历json,组合成输出用户名列表的HTML代码
                        if (list[i].length == 0) {
                            html += "
  • 用户为空!
  • "
    ; } else { html += "
  • " + list[i] + "
  • "
    ; } } document.getElementById("list").innerHTML = html;//获取id为list的标签,向其中添加用户名列表的节点 document.getElementById("num").innerHTML = list.length;//获取id为num的标签,向其中添加在线人数 } }; xmlhttp.open("GET", "/servlet/getnum", true); xmlhttp.send(); }
    script> head> <body> <div class="container"> <div class="row"> <div class="col-md-12"> <h3 class="text-muted">在线人数为:<span id="num">span>h3> <ul id="list" class="list-inline text-muted"> ul> <br> <a href="loginOut.jsp">注销sessiona> <a href="remove.jsp">移除usernamea> div> div> div> body> html>

    以下为remove.jsp,用来移除session中的用户名属性:

    <%--
      Created by IntelliJ IDEA.
      User: 23832
      Date: 2017/4/25
      Time: 20:19
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Titletitle>
    head>
    <body>
    <%session.removeAttribute("username");%>
    <jsp:forward page="UserList.jsp"/>
    body>
    html>

    以下为LoginOut.jsp页面,用来注销session:

    <%--
      Created by IntelliJ IDEA.
      User: 23832
      Date: 2017/4/25
      Time: 14:16
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Titletitle>
    head>
    <body>
    <%session.invalidate();%>
    <jsp:forward page="UserList.jsp"/>
    body>
    html>

    以下为Servlet的监听器部分,test.java,实现基本的监听session变化功能:

    package com.servlet;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.ArrayList;
    
    public class test1 implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {
        private ServletContext application = null;
        String Usertype=null;
    
        @Override
        public void contextInitialized(ServletContextEvent servletContextEvent) {
            ArrayList users=new ArrayList();
            application=servletContextEvent.getServletContext();
            application.setAttribute("users",users);
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent servletContextEvent) {
    
        }
    
        @Override
        public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
            //当有新的session属性添加的时候执行,取出session中username,并添加进application中用户名集合
            String user=(String)httpSessionBindingEvent.getValue();
            ArrayList users=(ArrayList)application.getAttribute("users");
            users.add(user);
            application.setAttribute("users",users);
        }
    
        @Override
        public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
            //当session中的属性被移除时执行,取出session中的用户名并从用户集合中删除
            String user=(String)httpSessionBindingEvent.getValue();
            ArrayList users=(ArrayList)application.getAttribute("users");
            for(int i = 0;i < users.size();i++){
                if(users.get(i).equals(user)){
                    users.remove(i);
                    application.setAttribute("users",users);
                }
            }
        }
    
        @Override
        public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
            //当session中的属性发生变化时执行,取出session中的用户名并从用户集合中删除
            String user=(String)httpSessionBindingEvent.getValue();
            ArrayList users=(ArrayList)application.getAttribute("users");
            for(int i = 0;i < users.size();i++){
                if(users.get(i).equals(user)){
                    users.remove(i);
                    application.setAttribute("users",users);
                    Usertype="change";
                    application.setAttribute("Usertype",Usertype);
                }
            }
        }
    
        @Override
        public void sessionCreated(HttpSessionEvent httpSessionEvent) {
    
        }
    
        @Override
        public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
            //当session被销毁时执行,取出session中的用户名并从用户集合中删除
            ArrayList users=(ArrayList)application.getAttribute("users");
            String user=(String)httpSessionEvent.getSession().getAttribute("username");
            for(int i = 0;i < users.size();i++){
                if(users.get(i).equals(user)){
                    users.remove(i);
                    application.setAttribute("users",users);
                }
            }
        }
    }

    以下为Getnum.java部分,用来获取用户名集合:

    package com.servlet;
    
    import net.sf.json.JSONArray;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    
    public class Getnum extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.setContentType("text/xml;charset=UTF-8");
            resp.setHeader("Cache-Control", "no-cache");
            PrintWriter out = resp.getWriter();
            ServletContext application = this.getServletContext();
            ArrayList users = (ArrayList) application.getAttribute("users");//取出application中的用户名集合
            JSONArray jsonArray = JSONArray.fromObject(users);//将用户名集合转化成json(注:这里需要引入实现json功能的相关包)
            out.println(jsonArray.toString());//将json添加到输出流中
            out.flush();
            out.close();
        }
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    

    以下为Servlet的配置部分:

    
    <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_3_1.xsd"
             version="3.1">
        <listener>
            <listener-class>com.servlet.test1listener-class>
        listener>
        <servlet>
            <servlet-name>getnumservlet-name>
            <servlet-class>com.servlet.Getnumservlet-class>
        servlet>
        <servlet-mapping>
            <servlet-name>getnumservlet-name>
            <url-pattern>/servlet/getnumurl-pattern>
        servlet-mapping>
    web-app>

    实验二

    使用过滤器实现敏感词过滤功能,当用户从文本框提交的文字中含有“晕”的时候,提示“发言失败”。

    以下是index.jsp部分,实现文本框的表单(代码包含了一些bootstrap,用来美化页面):

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>java webtitle>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        
        <link href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    
        
        
        
    head>
    <body>
    <div class="container">
        <div class="row">
            <div class="col-md-6">
                <h3 class="text-muted">留言板检测字符h3>
                <form style="margin-top: 50px" method="get" action="success.jsp">
                    <div class="form-group">
                        <label for="text">文本框label>
                        <textarea class="form-control" name="text" id="text" cols="30" rows="10">textarea>
                    div>
                    <button type="submit" class="btn-default btn">提交button>
                    <button type="reset" class="btn-default btn">重置button>
                form>
            div>
        div>
    div>
    
    <script src="https://code.jquery.com/jquery.js">script>
    
    <script src="js/bootstrap.min.js">script>
    body>
    html>
    

    以下为过滤器部分,test2.java,用来实现过滤敏感词的功能:

    package com.servlet;
    
    import javax.servlet.*;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.regex.Pattern;
    
    public class test2 implements Filter{
        protected FilterConfig filterConfig;
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            this.filterConfig=filterConfig;
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            String text=servletRequest.getParameter("text");//获取表单中的数据
            Pattern pattern=Pattern.compile(".*晕.*");//利用正则表达式匹配字符串中是否有“晕”字
            if (text!=null&&pattern.matcher(text).matches()){//如果有则输出“发言失败”
                servletResponse.setContentType("text/html;charset=UTF-8");
                servletResponse.setCharacterEncoding("UTF-8");
                PrintWriter out=servletResponse.getWriter();
                out.println("发言失败,含有非法文字");
            }else {
                filterChain.doFilter(servletRequest,servletResponse);
            }
        }
    
        @Override
        public void destroy() {
    
        }
    }
    
    

    以下为过滤器的配置部分:

    
    <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_3_1.xsd"
             version="3.1">
        <filter>
            <filter-name>test2filter-name>
            <filter-class>com.servlet.test2filter-class>
        filter>
        <filter-mapping>
            <filter-name>test2filter-name>
            <url-pattern>/success.jspurl-pattern>
        filter-mapping>
    web-app>

    你可能感兴趣的:(Servlet)