首页 > 代码库 > 第三十五章——过滤器和监听器
第三十五章——过滤器和监听器
过滤器代码示例:
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="http://www.mamicode.com/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"); } }
监听器:
第三十五章——过滤器和监听器
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。