这几天做的项目中一直纠结判断用户是否登录的问题,心想:如果在每个页面中都添加用户是否登录判断,这样的话要加载的代码太多,而且也容易出错!那能加过
滤器嘛……?该怎么加呢……纠结了很久,最后过滤器些好了,但又是死循环。最后在各种修改后还是成功了!下面是我在这次项目中用到的判断是否登录的过滤器
的代码,希望能帮到大家:
import java.io.IOException;
import java.io.PrintWriter;
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 javax.servlet.http.HttpSession;
import com.ph.entil.Users;
public class LoginFilter implements Filter {
public LoginFilter() {
// TODO Auto-generated constructor stub
}
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest) request;
HttpServletResponse res=(HttpServletResponse) response;
//获得请求的URL
String url=req.getRequestURL().toString();
//获得session中的对象
HttpSession session= req.getSession();
Users user=(Users) session.getAttribute("user");
//使用endsWith()判断url结尾的字符串
if(url.endsWith("login.jsp") || user!=null || url.endsWith("number1.jsp") || url.endsWith(".css") ||
url.endsWith(".js")|| url.endsWith(".gif")|| url.endsWith(".png")|| url.endsWith(".jpg")||url.endsWith("SSH_market/")){
//满足条件就继续执行
chain.doFilter(request, response);
}else{
//不满足条件就跳转到其他页面
PrintWriter out=res.getWriter();
out.print("<script language>alert('请登录!…………');top.location.href='login.jsp'</script>");
res.sendRedirect(req.getContextPath() + "/login.jsp");
}
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
web.xml配置文件:
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>com.ph.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
该贴由koei转至本版2014-5-2 16:22:05