• 20220719_Filter_Listener_AJAX_Axios的用法


    特性部分过于简单不介绍了直接上小案例
    过滤和监听功能部分,在本文项目MVC三层架构登录注册案例基础上扩展
    首先清空浏览器的缓存数据,清楚办法各浏览器不一,不必清空cookie,清也可以
    在基础案例的web包下添加一个filter包,写一个filter

    package com.diy.web.filter;
    
    import javax.servlet.*;
    import javax.servlet.annotation.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    import java.io.IOException;
    import java.net.http.HttpRequest;
    
    @WebFilter("/*")
    public class LoginFilter implements Filter {
        public void init(FilterConfig config) throws ServletException {
        }
    
        public void destroy() {
        }
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
            // get a HttpServletRequest ob, convert type form args
            HttpServletRequest hsr = (HttpServletRequest) req;
    
            /**
             * Block B
             */
            //get a session, judge if session contains a user
            HttpSession sess = hsr.getSession();
            Object User = sess.getAttribute("user");
    
            if (User != null){
                //let it pass
                chain.doFilter(req, resp);
            }else {
                hsr.setAttribute("loginFailedMsg","You didn't log on");
                hsr.getRequestDispatcher("/login.jsp").forward(hsr, resp);
                //hsr is instead of req, no problem usable
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    运行tomcat后直接访问资源而非登录页,如果浏览器缓存清空,会看见
    请添加图片描述
    请添加图片描述
    登录后还是可以访问的,不过登录页和注册页会呈现这种效果,因为登录注册相关的资源,除了jsp静态的部分,都被拦截了,要放行,即使还没登录,所以,改造上面的filter代码

    package com.diy.web.filter;
    
    import javax.servlet.*;
    import javax.servlet.annotation.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    import java.io.IOException;
    import java.net.http.HttpRequest;
    
    @WebFilter("/*")
    public class LoginFilter implements Filter {
        public void init(FilterConfig config) throws ServletException {
        }
    
        public void destroy() {
        }
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
            // get a HttpServletRequest ob, convert type form args
            HttpServletRequest hsr = (HttpServletRequest) req;
            /**
             * block A
             */
            //judge visit path whether related with login or register, yes, let them pass
            String[] urls = {"/login.jsp","/css/","/imgs/","register.jsp","loginServlet","registerServlet","/checkCodeServlet"};
            //get the requested visit path
            String url = ((HttpServletRequest) req).getRequestURL().toString();
    
            //judge whether url included in urls
            for (String s : urls) {
                if (url.contains(s)){
                    chain.doFilter(req,resp);
                    //if contains, return, the code under won't run
                    return;
                }
            }
    
            /**
             * Block B
             */
            //get a session, judge if session contains a user
            HttpSession sess = hsr.getSession();
            Object User = sess.getAttribute("user");
    
            if (User != null){
                //let it pass
                chain.doFilter(req, resp);
            }else {
                hsr.setAttribute("loginFailedMsg","You didn't log on");
                hsr.getRequestDispatcher("/login.jsp").forward(hsr, resp);
                //hsr is instead of req, no problem usable
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56

    按这个filter,如果用户已经登录,不是访问登录注册的相关资源,那么会执行Block B部分的代码后放行
    如果用户没登录,会执行Block B部分的代码,不放行,但转到登录页,又收到登录或注册的访问请求,执行Block A的代码,允许页面效果资源response
    然后return,不会执行下面的代码,不然就循环了

    效果图
    请添加图片描述
    登录后正常
    请添加图片描述

    文章目录


    监听器Listener
    在web包下建一个listener包,写一个自定义的listener

    package com.diy.web.listener;
    
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    import javax.servlet.annotation.WebListener;
    
    @WebListener
    public class MyListener implements ServletContextListener {
        @Override
        public void contextInitialized(ServletContextEvent sce) {
    //        ServletContextListener.super.contextInitialized(sce);
    
            System.out.println("My listener has initialized ~~~");
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            ServletContextListener.super.contextDestroyed(sce);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    这个listener监听整个ServletContext,就是整个服务,所以服务器启动就会加载,控制台看见打印输出
    请添加图片描述
    listener已经不常用,这里不研究用法,将来在spring框架中会再遇到

    文章目录


    AJAX的使用
    建一个AjaxServlet

    package com.diy.web.servlet;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.annotation.*;
    import java.io.IOException;
    
    @WebServlet("/ajaxServlet")
    public class AjaxServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //simulate a need 3000 millis request
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            resp.getWriter().write("

    Hello AJAX

    "
    ); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    建一个静态html,但

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>欢迎注册title>
        <link href="css/register.css" rel="stylesheet">
    head>
    <body id="body">
    
    <div class="form-div">
        <div class="reg-content">
            <h1>欢迎注册h1>
            <span>已有帐号?span> <a href="login.html">登录a>
        div>
        <form id="reg-form" action="/AJAX_Demo/ajaxServlet" method="get">
    
            <table>
    
                <tr>
                    <td>用户名td>
                    <td class="inputs">
                        <input name="username" type="text" id="username">
                        <br>
                        <span id="username_err" class="err_msg" style="display: none">用户名太受欢迎了span>
                    td>
    
                tr>
    
                <tr>
                    <td>密码td>
                    <td class="inputs">
                        <input name="password" type="password" id="password">
                        <br>
                        <span id="password_err" class="err_msg" style="display: none">密码格式有误span>
                    td>
                tr>
    
    
                <tr>
                    <td>验证码td>
                    <td class="inputs">
                        <input name="checkCode" type="text" id="checkCode">
                        <img src="imgs/fakeCheckCode.jpg">
                        <a href="#" id="changeImg">看不清?a>
                    td>
                tr>
    
            table>
    
            <div class="buttons">
                <input value="注 册" type="submit" id="reg_btn" />
            div>
            <div class="buttons">
                <input value="发送异步请求" type="button" id="btn" />
            div>
            <br class="clear">
        form>
    
    div>
    
    <script>
        document.getElementById("btn").onclick = function (){
            //1.get core object
            var xmlhttp
            if (window.XMLHttpRequest){
                //for new explorer
                xmlhttp = new XMLHttpRequest()
            }else {
                //for old IE
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
            }
    
            /**
             * 2.transit request,
             * use the long path name,
             * because, in reality, font end html and back end servlet may be deployed on different server
             */
            xmlhttp.open("GET","/AJAX_Demo/ajaxServlet")
            xmlhttp.send()
    
            //3.receive response
            xmlhttp.onreadystatechange = function (){
                if (this.readyState == 4 && this.status == 200){
                    document.getElementById("body").innerHTML = xmlhttp.responseText
    
                }
            }
        }
    script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91

    运行tomcat,访问register.html
    请添加图片描述
    正常点击注册,会等3000毫秒重加载网页并显示hello ajax标题语句,但我这代码有问题,可能是该代码不适用我的浏览器,反正不知不知为啥,不显示
    点击发送异步亲求后3000毫秒,会正确显示hello ajax语句

    文章目录


    AJAX实现用户名输入后即可检验是否已被占用
    后台代码

    package com.diy.web.servlet;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.annotation.*;
    import java.io.IOException;
    
    @WebServlet("/checkUserExistServlet")
    public class CheckUserExistServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //1.receive username input by user
            req.getParameter("username");
    
            // 2. assume the username already exists, instead of invoke database
            boolean flag = true;
    
            //response
            resp.getWriter().write("" + flag);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            this.doGet(req, resp);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    前台代码

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>欢迎注册title>
        <link href="css/register.css" rel="stylesheet">
    head>
    <body id="body">
    
    <div class="form-div">
        <div class="reg-content">
            <h1>欢迎注册h1>
            <span>已有帐号?span> <a href="login.html">登录a>
        div>
        <form id="reg-form" action="/AJAX_Demo/ajaxServlet" method="get">
    
            <table>
    
                <tr>
                    <td>用户名td>
                    <td class="inputs">
                        <input name="username" type="text" id="username">
                        <br>
                        <span id="username_err" class="err_msg" style="display: none">用户名太受欢迎了span>
                    td>
    
                tr>
    
                <tr>
                    <td>密码td>
                    <td class="inputs">
                        <input name="password" type="password" id="password">
                        <br>
                        <span id="password_err" class="err_msg" style="display: none">密码格式有误span>
                    td>
                tr>
    
    
                <tr>
                    <td>验证码td>
                    <td class="inputs">
                        <input name="checkCode" type="text" id="checkCode">
                        <img src="imgs/fakeCheckCode.jpg">
                        <a href="#" id="changeImg">看不清?a>
                    td>
                tr>
    
            table>
    
            <div class="buttons">
                <input value="注 册" type="submit" id="reg_btn" />
            div>
            <div class="buttons">
                <input value="发送异步请求" type="button" id="btn" />
            div>
            <br class="clear">
        form>
    
    div>
    
    <script>
        document.getElementById("username").onblur = function (){
    
            var username = this.value
    
            var xmlhttp
            if (window.XMLHttpRequest){
                xmlhttp = new XMLHttpRequest()
            }else {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
            }
    
            xmlhttp.open("GET","http://localhost:8080/AJAX_Demo/checkUserExistServlet?username="+username)
            xmlhttp.send()
    
            xmlhttp.onreadystatechange = function (){
                if (this.readyState == 4 && this.status == 200){
                    // alert(this.responseText)
                    if (this.responseText == "true"){
                        //username exists
                        document.getElementById("username_err").style.display = ''
                    }else {
                        //username not exists
                        document.getElementById("username_err").style.display = 'none'
                    }
                }
            }
        }
    script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91

    效果,访问这个新的register.html,输入任意名字,鼠标离开输入框,看见提示信息,并且发送为xhr,xmlhttp request
    请添加图片描述

    请添加图片描述

    文章目录


    axios的用法
    后台

    package com.diy.web.servlet;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    @WebServlet("/axiosServlet")
    public class AxiosServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println("get method ~~~");
            //receive request parameters
            System.out.println(req.getParameter("username"));
            //transit response data
            resp.getWriter().write("Hello Axios ~~");
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println("post method ~~~");
    
            this.doGet(req, resp);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    前台

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
    head>
    <body>
    
      <script src="/js/axios-0.18.0.js">script>
    
        <script>
            //1.GET
            // axios({
            //     method:"get",
            //     url:"http://localhost:8080/AJAX_Demo/axiosServlet?username=luoxiang"
            // }).then(function (resp){
            //     alert(resp.data)
            // })
    
            //axios request method alias GET
            // axios.get("http://localhost:8080/AJAX_Demo/axiosServlet?username=luoxiang").then(function (resp){
            //     alert(resp.data)
            // })
    
            //2.POST
            // axios({
            //     method:"post",
            //     url:"http://localhost:8080/AJAX_Demo/axiosServlet",
            //     data:"username=luoxiang"
            // }).then(function (resp){
            //     alert(resp.data)
            // })
    
            //axios request method alias POST
            axios.post("http://localhost:8080/AJAX_Demo/axiosServlet","username=luoxiang").then(function (resp){
                alert(resp.data)
            })
    
        script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    正常来说,访问这个axiosDemo.html就能在后台输出username,并网页弹出hello语句,但我这里,可能浏览器的原因,弹不出来

    用axios实现注册页面鼠标移开用户名输入框即可验证用户名是否存在
    后台还是之前的后台,但script部分改写,建一个新的axios_register.html

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>欢迎注册title>
        <link href="css/register.css" rel="stylesheet">
    head>
    <body id="body">
    
    <div class="form-div">
        <div class="reg-content">
            <h1>欢迎注册h1>
            <span>已有帐号?span> <a href="login.html">登录a>
        div>
        <form id="reg-form" action="#" method="get">
    
            <table>
    
                <tr>
                    <td>用户名td>
                    <td class="inputs">
                        <input name="username" type="text" id="username">
                        <br>
                        <span id="username_err" class="err_msg" style="display: none">用户名太受欢迎了span>
                    td>
    
                tr>
    
                <tr>
                    <td>密码td>
                    <td class="inputs">
                        <input name="password" type="password" id="password">
                        <br>
                        <span id="password_err" class="err_msg" style="display: none">密码格式有误span>
                    td>
                tr>
    
    
                <tr>
                    <td>验证码td>
                    <td class="inputs">
                        <input name="checkCode" type="text" id="checkCode">
                        <img src="imgs/fakeCheckCode.jpg">
                        <a href="#" id="changeImg">看不清?a>
                    td>
                tr>
    
            table>
    
            <div class="buttons">
                <input value="注 册" type="submit" id="reg_btn" />
            div>
            <div class="buttons">
                <input value="发送异步请求" type="button" id="btn" />
            div>
            <br class="clear">
        form>
    
    div>
    <script src="/js/axios-0.18.0.js">script>
    <script>
        document.getElementById("username").onblur = function (){
    
            var username = this.value
    
            axios.get("http://localhost:8080/AJAX_Demo/checkUserExistServlet?username="+username).then(function (resp){
                if (resp.data == true){
                    document.getElementById("username_err").style.display = ''
                }else {
                    document.getElementById("username_err").style.display = 'none'
    
                }
            })
    
            // axios.post("http://localhost:8080/AJAX_Demo/checkUserExistServlet","username="+username).then(function (resp){
            //     if (resp.data == true){
            //         document.getElementById("username_err").style.display = ''
            //     }else {
            //         document.getElementById("username_err").style.display = 'none'
            //     }
            // })
    
        }
    script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86

    这代码有问题,我不管怎么写 if判断的条件,也不能像原来xmlhttp写的那样,实现鼠标移出,用户名已占用的提示

  • 相关阅读:
    如何创建自定义前端组件?
    2022谷粒商城学习笔记(二)人人开源逆向工程
    10. 结束语
    IDEA全局搜索快捷键(ctrl+shift+F)失效修复
    k8s~envoy上添加wasm插件
    机器学习总结
    ROS1 学习11 坐标系tf 管理系统 简介及demo示例
    linux 用户不在sudoers文件中,此事将被报告
    HCIA数据通信——交换机(Vlan间的通信与安全)
    微信小程序可拖拽视频播放案例
  • 原文地址:https://blog.csdn.net/ClarkGable/article/details/125873917