期待IllegalStateException,但从servlet容器获取回复

时间:2014-02-19 01:45:30

标签: java servlets

我正在尝试练习Servlets的概念。我已经编写了一个示例代码,根据我应该抛出IllegalStateException。但是,我收到来自servlet容器(Apache Tomcat 7)的回复。谁能解释一下发生了什么?

提前致谢。

修改

这是HeadFirstServlets中给出的示例。我认为,这是本书第249页的错误。根据API,该方法永远不会使会话无效。这是不一致API的另一个例子。

代码段:

import java.io.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/SessionTest3")
public class SessionTest3 extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        session.setAttribute("foo", "42");
        session.setMaxInactiveInterval(0);   //Invalidate session immediately.
        String foo = (String) session.getAttribute("foo");

        if (session.isNew()) {       //should cause a runtime exception.
            out.println("This is a new Session.");
        } else {
            out.println("Welcome back!");
        }
        out.println("Foo = " + foo);
    }
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

1 个答案:

答案 0 :(得分:0)

以下是tomcat的API:

void setMaxInactiveInterval(int interval)

Specifies the time, in seconds, between client requests before the servlet 
container will invalidate this session. A zero or negative time indicates 
that the session should never timeout.

Parameters:
    interval - An integer specifying the number of seconds

你现在明白为什么吗?