idea:JavaWeb(maven)Servlet 04

1.cookie访问页面时间:注意,在web刷新即可显示时间


import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class cookie extends HelloServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer=resp.getWriter();

        writer.write("上次访问时间:");

        Cookie[] cookies=req.getCookies();
        if(cookies!=null){
            //遍历cookies,取出lastAccessTime这个cookie
            for (int i = 0; i < cookies.length; i++) {
                Cookie c=cookies[i];
                if("lastAccessTime".equals(c.getName())){
                    //取值上次访问时间,并显示出来
                    String time=c.getValue();
                    time=new Date(Long.parseLong(time)).toLocaleString();
                    writer.write(String.valueOf(time));
                }
            }
        }

        //获取当前时间,并存储到Cookie中
        Long currentTime=System.currentTimeMillis();
        Cookie cookie=new Cookie("lastAccessTime", currentTime.toString());
        cookie.setMaxAge(5*60);//设置Cookie有效时间,5min内关闭再打开浏览器Cookie会一直存在
        resp.addCookie(cookie);


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}

2.session 创建id


import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class session extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //得到session
        HttpSession session=req.getSession();
        //给session中存东西
        session.setAttribute("name", "清宵");
        //获取session的东西
        String sessionId=session.getId();
        //判断session是否为新建
        if(session.isNew()) {
            resp.getWriter().write("session创建成功,ID:"+sessionId);
        }else {
            resp.getWriter().write("session创建失败,id在服务器中存在,ID:"+sessionId);
        }
        //session创建时做了什么
        Cookie cookie=new Cookie("JSESSIONID", sessionId);
        resp.addCookie(cookie);
    }
}

你可能感兴趣的:(intellij-idea,maven,servlet)