Filter简单过滤器的实现
Posted 太快的幸福,措手不及
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Filter简单过滤器的实现相关的知识,希望对你有一定的参考价值。
1.过滤器简单编写
package cn.buaa.core.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.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.buaa.core.constant.Constant; public class LoginFilter implements Filter { @Override public void destroy() { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse)servletResponse; String uri = request.getRequestURI(); //判断当前请求地址是否是登录的请求地址 if(!uri.contains("sys/login_")){ //非登录请求 if(request.getSession().getAttribute(Constant.USER) != null){ //说明已经登陆过,放行 chain.doFilter(request, response); }else{ //没有登录,跳转到登录页面 response.sendRedirect(request.getContextPath() + "/sys/login_toLoginUI.action"); } }else{ //登录请求,直接放行 chain.doFilter(request, response); } } @Override public void init(FilterConfig arg0) throws ServletException { } }
2.xml中进行配置(注意:必须配置在struts的前边,要不然不起作用)
<filter> <filter-name>loginFilter</filter-name> <filter-class>cn.buaa.core.filter.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>loginFilter</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping>
以上是关于Filter简单过滤器的实现的主要内容,如果未能解决你的问题,请参考以下文章