Strut2中Filter过滤器的编写和注册

在Struts2中编写过滤器需要创建一个类,继承 import javax.servlet.Filter; 下面,创建一个判断用户是否登录的Filter:

public class UserLoginValidateFilter implements Filter {

@Override
public void destroy() {
}

@Override
public void doFilter(ServletRequest req, ServletResponse res,
        FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest)req;
    User user = WebUtil.getUser(request);
    if(user == null){
        HttpServletResponse response = (HttpServletResponse)res;
        response.sendRedirect(request.getContextPath() + "/user/Login.action");
    }else{
        filterChain.doFilter(req, res);
    }
}

@Override
public void init(FilterConfig arg0) throws ServletException {
}

}

接下来在web.xml文件中注册,设置需要过滤的URL:


UserLoginValidateFilter
com.itzhai.action.filter.UserLoginValidateFilter


UserLoginValidateFilter
/customer/*

arthinking wechat
欢迎关注itzhai公众号