简体   繁体   English

获取JSP Servlet会话,返回空值

[英]Getting a JSP servlet session, returns a null value

I am using jsp/servlets for a basic ajax application. 我正在将jsp / servlet用于基本的ajax应用程序。 I am setting a session with a servlet, but i am getting a null returned. 我正在设置与Servlet的会话,但返回的是null。 My code snippets as follow: 我的代码片段如下:

Servlet: Servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response)         throws  ServletException, IOException {

    String name=null;
    String sessionStrSet = null;


    if(request.getParameter("session").toString().equals("setSession")){

         name = request.getParameter("user");

         HttpSession session = request.getSession(true);
         session.setAttribute("sessionPw", name);
         sessionStrSet = session.getAttribute("sessionPw").toString();

         response.setContentType("text/plain");  
         response.setCharacterEncoding("UTF-8"); 
         response.getWriter().write(sessionStrSet + " " + "data write");

    }

    if(request.getParameter("session").toString().equals("getSession")){
        //how do i retrieve the session data here?
        response.setContentType("text/plain");  
        response.setCharacterEncoding("UTF-8"); 
        response.getWriter().write(sessionStrSet + "get session");
    }


}

The ajax works fine it is just the session retrieving that seems to be an issue. Ajax可以正常工作,只是会话检索似乎是一个问题。 I can pull the data once its been set in the first if(). 一旦在第一个if()中设置了数据,就可以提取数据。 But when I do another post request it comes back as null. 但是当我执行另一个发布请求时,它返回为null。 Do I need another HttpSession? 我需要另一个HttpSession吗? Any help much appreciated, I am a PHP dev not JSP so its very new to me! 非常感谢任何帮助,我是PHP开发人员,而不是JSP,因此对我来说是个新手!

Do you really need separate ifs? 您是否真的需要单独的if?

getSession(true) returns current session or create new if there is no current. getSession(true)返回当前会话,如果没有当前会话,则创建新会话。

See at the documentation http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getSession%28boolean%29 请参见文档http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getSession%28boolean%29

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM