//反复实验的时候注意数据库数据的更新
//将数据存储到cookie里面
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
HttpSession se = request.getSession();
String username = request.getParameter("username");
String password = request.getParameter("password");
UserService ser=new UserService();
User1 user=null;
try {
user=ser.login(username,password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("您好");
if(user!=null){
String autoLogin=request.getParameter("autoLogin");
if(autoLogin!=null){
System.out.println("0");
Cookie cookie_username=new Cookie("cookie_username",username);
Cookie cookie_password=new Cookie("cookie_password",password);
System.out.println(username);
System.out.println(password);
//设置cookie持续化时间
cookie_username.setMaxAge(60*10);
cookie_password.setMaxAge(60*10);
//设置路径
cookie_username.setPath(request.getContextPath());
cookie_password.setPath(request.getContextPath());
//发送cookie
response.addCookie(cookie_username);
response.addCookie(cookie_password);
System.out.println("0.1");
}
//非自动登录部分
se.setAttribute("user", user);
response.sendRedirect(request.getContextPath());
}else{
request.setAttribute("logininfo", "用户名密码错误");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
//拦截器部分代码
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest)request;
HttpServletResponse resp=(HttpServletResponse)response;
HttpSession session = req.getSession();
String cookie_username=null;
String cookie_password=null;
System.out.println("1");
Cookie[] cookies = req.getCookies();
if(cookies!=null){
for(Cookie cookie:cookies){
if("cookie_username".equals(cookie.getName())){
cookie_username=cookie.getValue();
}
if("cookie_password".equals(cookie.getName())){
cookie_password=cookie.getValue();
}
}
}
System.out.println("3");
if(cookie_username!=null&&cookie_password!=null){
UserService ser = new UserService();
User1 user=null;
try {
user=ser.login(cookie_username, cookie_password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
session.setAttribute("user", user);
if(user!=null){
request.getRequestDispatcher("index.jsp").forward(req,resp);
}
}
chain.doFilter(req, resp);
System.out.println("5");
}
//web.xml的配置
<filter>
<display-name>Myservlet2</display-name>
<filter-name>Myservlet2</filter-name>
<filter-class>cn.jy.web.Myservlet2</filter-class>
</filter>
<filter-mapping>
<filter-name>Myservlet2</filter-name>
<url-pattern>/*</url-pattern> //注意 /*
</filter-mapping>