第一步:建工程 建包建servlet类
第二步:编写servlet类
public class cookie extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决中文乱码
req.setCharacterEncoding("utf8");
resp.setCharacterEncoding("utf8");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
//Cookie 服务器从客户端获取
Cookie[] cookies = req.getCookies();
if (cookies != null) {
out.write("您上次所访问的时间:\n");
//遍历cookies
for (int i = 0; i <cookies.length ; i++) {
if(cookies[i].getName().equals("time")){
String timeStr = cookies[i].getValue();
//转换为时间
long time = Long.parseLong(timeStr);
Date date = new Date(time);
out.write(date.toLocaleString());
}
}
}else{
out.write("第一次见面 请多多关照");
}
//服务器给客户端响应一个Cookie
Cookie cookie = new Cookie("time", String.valueOf(System.currentTimeMillis()));
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
第三步:在web.xml中注册servlet
<!-- 注册servlet-->
<servlet>
<servlet-name>cookie</servlet-name>
<servlet-class>com.csnz.servlet.cookie</servlet-class>
</servlet>
<!-- 配置servlet的映射-->
<servlet-mapping>
<servlet-name>cookie</servlet-name>
<url-pattern>/see</url-pattern>
</servlet-mapping>
第四步:配置tomcat 启动服务器访问
第一次访问
cookie已经存进去了
此时刷新页面