java session().getAttribute 返回 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29968481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:11:27  来源:igfitidea点击:

session().getAttribute is returning null

javajspsessionservlets

提问by user1407668

I have a servlet which calls a jsp page. In the servlet I am retrieving the username provided at the login correctly. But after setting the same in session, when i access the called jsp page, its returning null.

我有一个调用jsp 页面的servlet。在 servlet 中,我正在正确检索登录时提供的用户名。但是在会话中设置相同后,当我访问被调用的jsp页面时,它返回null。

Servlet Code:

服务程序代码:

public class AdminServlet extends HttpServlet {
/**
 * 
 */
private static final long serialVersionUID = -4244742541587179390L;

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String userName =  request.getParameter("name");
    System.out.println("UserName: " + userName); // Here it prints the username properly
    request.getSession(true).setAttribute(request.getParameter("name"), userName );
    RequestDispatcher rd = request.getRequestDispatcher("upload.jsp");
    rd.forward(request, response);
//  response.sendRedirect("upload.jsp");
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    doGet(request,response);
}
}

JSP Code snippet where I am accessing this:

我正在访问的 JSP 代码片段:

<label class="message">Welcome <%= session.getAttribute("userName") %></label>

What am I doing wrong here? Can anyone help please

我在这里做错了什么?任何人都可以帮忙吗

采纳答案by Verdi

I think you inverted the two params. It should be like this:

我认为你颠倒了两个参数。应该是这样的:

   request.getSession(true).setAttribute("userName", userName );

回答by Nimesh

you should get session value from the value of

您应该从以下值中获取会话值

request.getParameter("name");

or in servlet you need as follow:

或者在 servlet 中你需要如下:

request.getSession(true).setAttribute("userName",request.getParameter("name") );

request.getSession(true).setAttribute("userName",request.getParameter("name"));

回答by Stefan Beike

this is wrong:

这是错误的:

request.getSession(true).setAttribute(request.getParameter("name"), userName ); 

I think it should be

我认为应该是

request.getSession(true).setAttribute("userName", userName );

回答by Verdi

Just had a quick look I think this might be a little similar and might help: JSP Session.getAttribute() value return null

快速浏览一下,我认为这可能有点相似,可能会有所帮助:JSP Session.getAttribute() value return null