package com.test;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.test.util.cookieUtil;
public class demo_04 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String username=request.getParameter("username");
String passwd=request.getParameter("passwd");
if("admin".equals(username)&& "123".equals(passwd)) {
Cookie[] cookies = request.getCookies();
Cookie cookie= cookieUtil.findCookie(cookies, "last");
if(cookie == null) {
Cookie c = new Cookie("last",System.currentTimeMillis()+"");
c.setMaxAge(60);
response.addCookie(c);
response.getWriter().write("welcome, "+ username);
}else {
// String vaule = cookie.getValue();
long lastVisit= Long.parseLong(cookie.getValue());
response.getWriter().write("welcome, "+ username+"上次登录时间是:"+new Date(lastVisit));
cookie.setValue(System.currentTimeMillis()+"");
response.addCookie(cookie);
}
System.out.println("success");
//response.getWriter().write("welcome, "+ username);
}else {
System.out.println("falid");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
###################################################################################
package com.test.util;
import javax.servlet.http.Cookie;
public class cookieUtil {
public static Cookie findCookie(Cookie[] cookies,String name) {
if(cookies !=null) {
for (Cookie cookie : cookies) {
if(name.equals(cookie.getName())) {
return cookie;
}
}
}
return null;
}
}
Insert title here请输入一下内容:
账号:密码: