1. 程式人生 > 實用技巧 >13、過濾器、監聽器的常見應用

13、過濾器、監聽器的常見應用

監聽器:GUI程式設計中經常使用;

package com.kuang.listener;

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

public class TestPanel {
    public static void main(String[] args) {
        Frame frame = new Frame("萬聖節快樂");//新建一個窗體
        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(new Color(0,255,0));//設定背景顏色 frame.add(panel); frame.setVisible(true);
//監聽事件,監聽關閉事件 frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } }

使用者登入之後才能進入主頁!使用者登出後就不能進入主頁了

1.使用者登入之後,向Sessison中放入使用者的資料

2.進入中野的時候要判斷使用者是否已經登入;要求在過濾器中實現!

package com.kuang.filter;

import com.kuang.util.Constant;

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

public class SysFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        /*
        if (request.getSession().getAttribute(Constant.USER_SESSION).Level==VIP1){
            response.sendRedirect("/vip1/index.jsp");
        }
        if (request.getSession().getAttribute(Constant.USER_SESSION).Level==VIP2){
            response.sendRedirect("/vip2/index.jsp");
        }
        if (request.getSession().getAttribute(Constant.USER_SESSION).Level==VIP3){
            response.sendRedirect("/vip3/index.jsp");
        }
         */

        //ServletRequest   HttpServletRequest

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;



        if (request.getSession().getAttribute(Constant.USER_SESSION)==null){
            response.sendRedirect("/error.jsp");
        }

        chain.doFilter(request,response);

    }

    @Override
    public void destroy() {

    }
}