package lesson.j2ee.ex2;import javax.servlet.*;
import javax.servlet.http.*;import java.io.*;public class Login extends HttpServlet {
public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException ,IOException{ String name = req.getParameter("name");
//HttpSession session=req.getSession();
boolean judge = true;
System.out.println(name);
Cookie cookies[] = req.getCookies();
    if (cookies != null)
    {
     for (int i = 0; i < cookies.length; i++)
        {
            if (cookies[i].getName().equals("name"))
            {
             cookies[i].setValue(name);
             judge = false;
            }
        }
    }
    
    if(judge)
    {
     Cookie cookie = new Cookie("name", name);
    //不设置的话,则cookies不写入硬盘,而是写在内存,只在当前页面有用,以秒为单位
    cookie.setMaxAge(24*60*60);
    res.addCookie(cookie);
    }
    
    PrintWriter out=res.getWriter();
res.setContentType("text/html"); out.println("<html>");
out.println("<title>");
out.println("User list");
out.println("</title>");
out.println("<body><h4>User List:</h4><hr><br><br>");
    if (cookies != null)
    {
        for (int i = 0; i < cookies.length; i++)
        {
            if (cookies[i].getName().equals("name"))
            {
             out.print(cookies[i].getValue());
            }
        }
    }
out.println("</body>");
out.println("</html>");
                 //这一段是session超时的设置
req.getSession().setMaxInactiveInterval(30);
if(req.getSession(false)==null){
if(req.getSession(true).isNew()==true){
}
else {
//res.sendRedirect("/UserLogin.html");
System.out.println("Session has been invalidated!");
}
}
out.close();
}
}

解决方案 »

  1.   

    session超时通常在web.xml中设置的,你可以试试  <session-config>
        <session-timeout>60</session-timeout>
      </session-config>
      

  2.   

    java代码是运行在服务端的浏览器自动登出意义不大,如果真要做,那用js吧还有必须搞清楚服务端和客户端的边界
      

  3.   

    需要设置页面刷新,因为session失效后没有发送请求到服务端进行验证,客户端就没有反应
      

  4.   

    先查有没有session,session'为null的话直接跳; 写在req.getSession().setMaxInactiveInterval(30);之前,或者把这句话写在if里
      

  5.   

    在web.xml中设置超时时长就好了,页面往后台请求时,设置过滤器,在过滤器里面给予返回,返回的如果是session超时,那么就跳转页面就好了,因为ajax的请求会有问题,