Java学习第59天--过滤器应用之敏感词屏蔽,监听器,监听器应用案例之在线人数显示

本文详细介绍了如何在Web应用程序中实现敏感词过滤,利用Java Proxy机制增强request对象的getParameter方法,确保用户输入不包含敏感词汇。同时,深入探讨了Servlet监听器的概念、分类及其实现方式,包括请求、会话、上下文监听器的使用,以及监听器在事件源上的绑定和事件响应。
摘要由CSDN通过智能技术生成

1,过滤器引用之敏感词过滤

代码实现

@WebFilter(filterName = "SensitiveWordsFilter",urlPatterns = "/*")
public class SensitiveWordsFilter implements Filter {
    List<String > sensitiveWords = new ArrayList<>();

    public void init(FilterConfig config) throws ServletException {
        Enumeration<String> parameterNames = config.getInitParameterNames();
        while (parameterNames.hasMoreElements()){
            String sensitiveWord = config.getInitParameter(parameterNames.nextElement());
            sensitiveWords.add(sensitiveWord);
        }
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        //增强request下的getParameter方法
        HttpServletRequest requestProxy = (HttpServletRequest) Proxy.newProxyInstance(
                request.getClass().getClassLoader(),
                request.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //增强getParameter方法
                        Object returnValue = null;
                        String methodName = method.getName();
                        if("getParameter".equals(methodName)){
                            //returnValue就是getParameter方法的返回值,可能存在敏感词
                            String returnValue1 = (String) method.invoke(request,args);
                            //开始处理敏感词
                            for (String sensitiveWord:sensitiveWords){
                                if (returnValue1.contains(sensitiveWord)){
                                    //getParameteer方法的返回值包含敏感词
                                    returnValue1 =returnValue1.replace(sensitiveWord,"***");
                                }
                            }
                            return returnValue1;
                        }else {
                            returnValue = method.invoke(request,args);
                        }
                        return returnValue;
                    }
                }
        );
        chain.doFilter(requestProxy, resp);
    }

(断点应用:打关键代码,可用于检查修正错误代码)

2,监听器

在这里插入图片描述
(课堂案例)
在这里插入图片描述
1,监听器概念

  • 事件源:事件发生的源头
  • 监听器:监听事件发生
  • 绑定:将监听器绑定到事件源
  • 事件:能够触发监听器的事

2,Servlet监听器

  • 事件源:request域对象,session域对象,ServletContext域对象
  • 监听器:Servlet三种监听器
  • 绑定:配置web.xml
  • 事件:域对象发生改变

3,监听器分类

  • 一类监听器:监听域对象创建和销毁
  • 二类监听器:监听域对象中的属性变更(属性设置,属性替换,属性移除)
  • 三类监听器:监听域对象的java的绑定

4,一类监听器的基本使用

1,一类监听器:

  • ServletRequestListener:监听ServletRequest域对象的创建和销毁
  • HttpSessionListener:监听HttpSesssionListener域对象的创建和销毁
  • ServletContextListener:监听ServiceContextListener域对象的创建和销毁

2,开发步骤:

  • 自定义类实现一类监听器
  • 重写监听器中的方法
  • 配置web.xml

3,代码实现
监听器:

public class MyListener02 implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

        System.out.println("session创建");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        System.out.println("session销毁");
    }
}

web.xml

<listener>
        <listener-class>listener.MyListener01</listener-class>
    </listener>
  • 事件源:ServletContext域对象
  • 监听器:ServletContextListener
  • 绑定:web.xml配置
  • 事件:ServletContext域对象发生的创建和销毁

5,二类监听器的基本使用

1,分类:

  • ServletRequestAttributeListener
    监听ServletRequest域对象中的属性变更
  • HttpSessionAttributeListener
    监听HttpSession域对象中的属性变更
  • ServletContextAttributeListener
    监听ServletContext域对象中的属性变更

2, 代码实现

监听器:

public class MyServletContextAttributeListener implements ServletContextAttributeListener {
    @Override
    public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {
        //监听ServletContext域对象中的属性添加
        System.out.println("ServletContext added");
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {
        //监听ServletContext域对象中的属性值被替换
        System.out.println("ServletContext removed");
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {
        //监听ServletContext域对象中的属性值移除
        System.out.println("ServletContext replaced");
    }
}

web.xml:

<listener>
        <listener-class>listener.MyServletContextAttributeListener</listener-class>
    </listener>

6,三类监听器的基本使用

  • HttpSessionBindingListener
    监听session 域中的java对象的状态(绑定与解绑)
    绑定:将java对象存储到session域对象
    解绑:将java对象从session域对象移除

  • 监听器组成
    事件源:java对象
    监听器:HttpSessionBindingListener
    绑定:java对象实现HttpSessionBindingListener接口
    事件:java对象在session中状态改变

  • 代码实现

public class User implements HttpSessionBindingListener {

    @Override
    public void valueBound(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println("UserBound");
    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println("UserUnound");
    }
    ......
  • 注意事项:
    不需要在web,xml进行绑定,因为已经通过实现接口实现绑定

7,监听器的综合案例

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
代码实现:
LoginServlet

@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if("root".equals(username) && "root".equals(password)){
            //登录成功,修改登录状态,跳转ShowIndexServlet
            User existUser = new User();
            existUser.setUsername(username);
            existUser.setPassword(password);
            request.getSession().setAttribute("existUser",existUser);
            response.sendRedirect("/day59/showIndex");
        }else {
            //登陆失败,转发到登录页面,重新登陆
            request.getRequestDispatcher("login.html").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

ShowIndexServlet

@WebServlet(name = "ShowIndexServlet",urlPatterns = "/showIndex")
public class ShowIndexServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User existUser = (User)request.getSession().getAttribute("existUser");

       StringBuffer responseBody = new StringBuffer();
        if(null == existUser){
            //不在登录状态,提示
            responseBody.append("您还没有登陆:<a href='/day59/login.html'>请登录</a>");
        }else {
            //在登陆状态
            responseBody.append("欢迎回来,"+existUser.getUsername()+"   <a href='/day59/logout'>注销</a>");
        }
        ServletContext servletContext = getServletContext();
        //获取在线人数
        Integer count = (Integer) servletContext.getAttribute("count");
        if (null == count){
            //没有人在登陆状态,在线人数为0人
            count = 0;
        }else{
            //有人在登陆状态,直接输出在线人数count人
        }
        responseBody.append("在线人数为:"+count);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(responseBody.toString());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

LogoutSevlet

@WebServlet(name = "LogoutServlet",urlPatterns = "logout")
public class LogoutServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //注销登录,将existUser从session域中基础
//        request.getSession().removeAttribute("existUser");
        //注销登录
        //注销成功,也可以直接将session销毁
        request.getSession().invalidate();
        request.getRequestDispatcher("showIndex").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

User

public class User implements HttpSessionBindingListener {

    @Override
    public void valueBound(HttpSessionBindingEvent httpSessionBindingEvent) {
        //有人登录成功,在线人数加1
        //判断是否是第一个登录成功的人
        //获取ServletContext
        ServletContext servletContext = httpSessionBindingEvent.getSession().getServletContext();
        Integer count = (Integer) servletContext.getAttribute("count");
        if(null == count){
            //就是第一个登录成功的人
            count = 1;

        }else {
            //不是第一个登录成功的人
            count++;

        }
        servletContext.setAttribute("count",count);
    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent httpSessionBindingEvent) {
        //有人注销登录,在线人数减1
        System.out.println("UserUnound");
        ServletContext servletContext = httpSessionBindingEvent.getSession().getServletContext();
        Integer count = (Integer) servletContext.getAttribute("count");
        count--;
        servletContext.setAttribute("count",count);
    }

login.html

<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
    <form action="/day59_02/login" method="get">

        账户:<input type="text" name="username"/><br>
        密码:<input type="text" name="password"/><br>
        <button type="submit">登录</button>

    </form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值