HttpSession& ServletContext没有给出期望的结果

时间:2014-02-07 14:33:39

标签: java servlets

我是servlet的新手。我的代码执行没有错误,但我没有得到预期的结果。

@WebServlet(description = "A simple", urlPatterns = { "/SimpleServlet" })
public class SimpleServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter wr = response.getWriter();
        String uname = request.getParameter("unam");
        HttpSession ses = request.getSession(); 
        ServletContext cont = request.getServletContext();

        if (uname != "" && uname != null)

        {
            ses.setAttribute("userses", uname); 
            cont.setAttribute("userses", uname);
        }

        wr.println("In RequestHttp method your name is "+ uname);
        wr.println("In Sesssion method  your name is " + (String)ses.getAttribute("userses"));
        wr.println("In Context  method  your name is " + (String)cont.getAttribute("userses"));
    }

}

所以当我在Eclipse IDE中运行时,

http://localhost:8080/SimpleServletProject/SimpleServlet?unam=1

结果

In RequestHttp method your name is 1
In Sesssion method your name is 1
In Context method your name is 1

这没什么不对。

所以当我在Chrome中运行时,

http://localhost:8080/SimpleServletProject/SimpleServlet

结果

In RequestHttp method your name is null
In Sesssion method your name is null
In Context method your name is null

我期待上下文方法,你的名字是1

我回到Eclipse IDE,这次我在下面做了

http://localhost:8080/SimpleServletProject/SimpleServlet

结果

In RequestHttp method your name is null
In Sesssion method your name is null
In Context method your name is null

我希望 Session方法是1

我犯的错误是什么?

0 个答案:

没有答案