我正在阅读有关该HttpSession.isNew()
方法的“Head First JSP And Servlets”。有一种我无法理解的奇怪行为。
这是一些示例代码。
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class TestSessionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
doPost(httpServletRequest,httpServletResponse);
}
@Override
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
httpServletResponse.setContentType("text/html");
PrintWriter out = httpServletResponse.getWriter();
HttpSession session = httpServletRequest.getSession();
if(session.isNew()){
out.println("this is a new session");
} else{
out.println("Welcome Back Ben:");
}
}
}
现在,当我在 Tomcat 中部署应用程序并第一次点击 servlet 时,if
它没有转到块,而是转到else
块。当我第一次从另一个浏览器访问同一个 servlet 时,它会进入if
块。
当应用程序刚刚启动并且我第一次点击 servlet 时,它不应该转到if
块而不是else
? 有人可以详细说明一下吗?