在一些网站中,必须要经进行登陆才能查看其他网页,所以就要加入过滤器来筛选
基本的格式如下
package com.text.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;
public class DenoFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
package com.sxt.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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sxt.pro.UserInfo;
@WebFilter("/*")
public class LoginInAccessFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain)
throws IOException, ServletException {
//基于Http
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
// 得到请求的路径
String url = request.getRequestURI(); // 站点名/资源路径
//如果路径包含登录的路径名则方放行
if(url.contains("/jsp/login.jsp")){
chain.doFilter(request, response);
return;
}
// 2、静态资源 放行 (statics目录下的资源都放行;js文件、css文件、图片等;)
if (url.contains("/statics")) {
// 放行
chain.doFilter(request, response);
return;
}
if(url.contains("/ul")){
//得到用户的登录的行为
String actionName = request.getParameter("actionName");
if("login".equals(actionName)){
chain.doFilter(request, response);
return;
}
}
UserInfo fiterUser = (UserInfo) request.getSession().getAttribute("fiterUser");
if(fiterUser!=null){
chain.doFilter(request, response);
return;
}
System.out.println(url);
//如果用户不登陆直接想进入其他页面则开启拦截也就是自动跳转到登陆页面
response.sendRedirect("/al/jsp/login.jsp");
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}