过滤器监听器的常见应用

监听器:GUI编程中经常应用
利用监听器控制窗口的关闭

package com.lding.listener;

import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

/**
 * @program: javaweb-filter
 * @description:
 * @author: 王丁
 * @date: 2021-11-03 10:44
 **/
public class TestPanel {
    public static void main(String[] args) {
        Frame frame = new Frame("hello 世界");
        Panel panel=new Panel(null);
        frame.setLayout(null);
        frame.setBounds(300,300,500,500);
        frame.setBackground(new Color(0,0,255));
        panel.setBounds(50,50,300,300);
        panel.setBackground(Color.YELLOW);
        frame.add(panel);
        frame.setVisible(true);
        //监听事件,关闭事件
        frame.addWindowListener(new WindowListener() {
            public void windowOpened(WindowEvent e) {
                System.out.println("打开");
            }

            public void windowClosing(WindowEvent e) {
                System.out.println("关闭ing");
                System.exit(0);
            }

            public void windowClosed(WindowEvent e) {
                System.out.println("关闭ed");
            }

            public void windowIconified(WindowEvent e) {

            }

            public void windowDeiconified(WindowEvent e) {

            }

            public void windowActivated(WindowEvent e) {
                System.out.println("激活");
            }

            public void windowDeactivated(WindowEvent e) {
                System.out.println("未激活");
            }
        });
    }
}

我们利用过滤器再做一个小Demo
做一个网页登录的功能,但是需要控制管理员admin登录后才能进入主页,如果不是管理员则不能进去,登陆后注销用户,或者不是管理员登陆,这两种情况都需要重新回到登录页面。
实现思路
用户登录之后,向Sesison中放入用户的数据
2. 进入主页的时候要判断用户是否已经登录;在过滤器中实现!

编写登陆页面,提交表单后跳转到loginServlet 处理登录请求
login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>登陆页面</h1>
<form action="/s/login" method="get">
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="submit">
</form>
</body>
</html>

LoginServlet
判断请求参数中的usernames是否为管理员,如果建立一个session,并跳到登录成功的页面
如果不是 则跳转到错误页面

package com.lding.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: javaweb-filter
 * @description:
 * @author: 王丁
 * @date: 2021-11-03 11:06
 **/
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前段请求的参数
        String username = req.getParameter("username");
        if(username.equals("admin")){
            req.getSession().setAttribute("USER_SESSION",req.getSession().getId());
            resp.sendRedirect("/sys/success.jsp");
            System.out.println("登陆成功");
        }else{
            System.out.println("登陆失败");
            resp.sendRedirect("/error.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

SysFilter
过滤器,判断请求有没有带session,如果没有则跳转到错误页面
如果有session则继续运行,这就防止了我们直接访问登陆成功页面,

package com.lding.listener;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @program: javaweb-filter
 * @description:
 * @author: 王丁
 * @date: 2021-11-03 12:04
 **/
public class Sys implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //ServletRequest HttpServletRequest
        HttpServletRequest request1=(HttpServletRequest) servletRequest;
        HttpServletResponse response1=(HttpServletResponse)servletResponse;

        if(request1.getSession().getAttribute("USER_SESSION")==null){
            response1.sendRedirect("/error.jsp");
        }
        filterChain.doFilter(servletRequest,servletResponse);

    }
    public void destroy() {

    }
}

登陆成功页面
success.jsp

<%--
  Created by IntelliJ IDEA.
  User: apple
  Date: 2021/11/3
  Time: 11:03 AM
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<%--<%--%>
<%--    Object user_session = request.getSession().getAttribute("USER_SESSION");--%>
<%--    if(user_session==null){--%>
<%--         response.sendRedirect("/login.jsp");--%>
<%--    }--%>
<%--%>--%>
<h1>主页</h1>
<%--<p><a href="/s/logout">注销</a> </p>--%>
<form action="/s/logout" method="get">
<input type="submit" value="注销">
</form>
</body>
</html>

错误页面 error.jsp

<%--
  Created by IntelliJ IDEA.
  User: apple
  Date: 2021/11/3
  Time: 11:10 AM
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>错误</h1>
<h3>没有权限</h3>
<form action="/login.jsp" method="get">
    <input type="submit" value="返回登陆页面">
</form>
</body>
</html>

错误页面中有一个返回登陆页面的按钮,点击后我们可以返回到登陆页面,成功页面有一个注销按钮,点击后我们跳转到logoutServlet,处理注销。
注销的方法位移除请求中Session中的USER_SESSION属性,没有这个属性也就不能再访问登陆成功页面,并且处理后跳转到重新登陆到页面
logoutServlet

package com.lding.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* @program: javaweb-filter
* @description:
* @author: 王丁
* @date: 2021-11-03 11:26
**/
public class LoginOutServlet extends HttpServlet {
   @Override
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       Object user_session = req.getSession().getAttribute("USER_SESSION");
       if(user_session!=null){
           req.getSession().removeAttribute("USER_SESSION");
           resp.sendRedirect("/login.jsp") ;
       }
   }

   @Override
   protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      doGet(req, resp);
   }
}

如果对您有帮助,免费的三连第一个 感谢🙏~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值