我來自.NET背景並嘗試Java(Servlets/JSP)中的一些基礎知識。在.NET中,我們有ViewState,Session,Application變量。從我讀的內容來看,應用程序變量在Java中有一個叫做ServletContext的兄弟。所以,我創建了一個簡單的Servlet程序ServletContext變量不保留價值
public class SimpleServlet 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();
String userName = request.getParameter("userName");
ServletContext context = request.getServletContext();
context.setAttribute("savedContextUserName", userName);
out.println("Hello! " + context.getAttribute("savedContextUserName"));
}
我打開瀏覽器,並通過以下並得到正確的輸出中,即您好! Stuart
http://localhost:8080/ServletProject/SimpleServlet?userName=Stuart
然後,我打開另一個瀏覽器實例,並通過以下,但得到你好! null
http://localhost:8080/ServletProject/SimpleServlet
當我打開新的瀏覽器實例時,上下文是否不保留值Stuart? .NET的應用程序變量肯定會保留它。有什麼我在這裏失蹤?
哦謝謝@Petr。我知道了 :) –