码迷,mamicode.com
首页 > 其他好文 > 详细

第三十五章——过滤器和监听器

时间:2017-07-03 12:12:53      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:http   分享   com   default   示例   attr   import   let   ret   

过滤器代码示例:

package com.hanqi.maya.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class SessionFilter
 */
@WebFilter(filterName="sessionFilter", 
    value={"/*"}, initParams={@WebInitParam(name="initp", value="message.jsp;login.jsp;LoginOrRegisterServlet")})
public class SessionFilter implements Filter {

    private String initParams;
    
    /**
     * Default constructor. 
     */
    public SessionFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        
        String[] ss = initParams.split(";");
        
        String reqUrl = request.getRequestURI();
        for(String s : ss) {
            if(reqUrl.indexOf(s)!=-1) {
                chain.doFilter(request, response);
                return;
            }
        }
        
        Object obj = request.getSession().getAttribute("currentUser");
        if(obj==null) {
            response.sendRedirect("login.jsp");
        } else {
            chain.doFilter(request, response);
        }
    }

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
        initParams = fConfig.getInitParameter("initp");
    }

}

监听器:

技术分享

第三十五章——过滤器和监听器

标签:http   分享   com   default   示例   attr   import   let   ret   

原文地址:http://www.cnblogs.com/yuanlaihenkuang/p/7109612.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!