过滤器过滤页面,实现自动登录
若系统登录成功一次,则再次启动不需要填写用户名密码,直接跳转首页。
思路
传一个值确定是否满足自动登录条件,若满足加一个过滤器,将登录页面过滤即可。
代码
- 自动登录传值
//保存当前的用户信息
User user = new User(username, password, 1);
request.getSession().setAttribute("user", user);
- 过滤器过滤login.html页面
package 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.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import bean.User;
/**
* Servlet implementation class LoginFilter
*/
@WebFilter("/login.html")
public class LoginFilter implements Filter {
/**
* @see HttpServlet#HttpServlet()
*/
public LoginFilter() {}
@Override
public void destroy() {
System.out.println("已销毁");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
HttpSession session = req.getSession();
//根据User对象去取
User user = (User)session.getAttribute("user");
//判断
if(user!= null){
if(user.getIsAutoLogin()!= 0){ //说明勾选了自动登陆
if("tom".equals(user.getUsername())&&"123".equals(user.getPassword())){
//判断帐号密码是否正确
//正确之后内部跳转主页index.html
req.getRequestDispatcher("index.html").forward(request, response);; //用来过滤单个页面
}else {
//帐号密码不正确
//跳转到密码错误的一个界面
//res.sendRedirect("/Day03Html/passwderror.html");
chain.doFilter(request, response);
}
}else { //说明不需要自动登陆,也不需要过滤器
chain.doFilter(request, response);
//chain.doFilter(req, res);
}
}else {
chain.doFilter(request, response);
}
}
@Override
public void init(FilterConfig fConfig) throws ServletException {
System.out.println("初始化");
}
}