Filter用作安全登陆
上一篇文章写到用springmvc拦截器来做登陆验证(http://blog.youkuaiyun.com/make__it/article/details/78840576),但是它有不足的地方。
这篇用filter来做安全登陆,何为安全登陆,简单点说就是登陆之后才能访问页面,不登陆什么页面都访问不了。也可以看出springmvc的拦截器之拦截对controller的访问,而filter拦截所有的访问
代码如下
一:后台代码
public class LoginFilter implements Filter{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest request=(HttpServletRequest) servletrequest;
HttpServletResponse response=(HttpServletResponse) servletresponse;
String servletPath = request.getServletPath();
System.out.println(servletPath);
//如果是去登陆页面直接放行。
if(servletPath.contains("login")){
System.out.println("go");
chain.doFilter(request, response);
return;//这个return是必须的,不然可能无法跳转
}
// if(servletPath.contains("index")){
// chain.doFilter(request, response);
// return;
// }
HttpSession session=request.getSession();
String username=(String) request.getAttribute("username");
if(username!=null){
chain.doFilter(request, response);
}
response.sendRedirect("/WEB-INF/views/login.jsp");
//request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);
return;
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
二:配置
在web.xml中配置
<filter>
<filter-name>myfilter</filter-name>
<filter-class>com.students.controller.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myfilter</filter-name>
<url-pattern>/*</url-pattern> //表示所有路径
</filter-mapping>
还需要配置过滤掉静态资源
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/js/*</url-pattern> //这个根据自己的实际位置来写
<url-pattern>/css/*</url-pattern>
<url-pattern>/images/*</url-pattern>
<url-pattern>/static/*</url-pattern>
</servlet-mapping>
在springmvc.xml需要配置
<mvc:default-servlet-handler/>