Servlet中的过滤器
在web.xml中配置:(用eclipse工具,可以在创建filter的时选择,web.xml中的配置可以自动生成)
<filter>
<display-name>LoginFilter</display-name>
<filter-name>LoginFilter</filter-name>
<filter-class>cn.web.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/jsps/admin/*</url-pattern> //过滤admin目录下的文件,
</filter-mapping>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<servlet-name>AdminManageServlet</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/jsps/AdminManage/*</url-pattern>
</filter-mapping>
2.Filter代码:
public class LoginFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
Object user = req.getSession().getAttribute("sessionUser");
if(user == null) {
req.setAttribute("msg", "您还没有登录,不能访问本资源");
req.getRequestDispatcher("/jsps/err.jsp").forward(req, response);
} else {
chain.doFilter(request, response);//放行
}
}
public void init(FilterConfig fConfig) throws ServletException {
}
}