servlet not forwarding session attribute to jsp

那年仲夏 提交于 2019-12-02 07:09:37

问题


Using embedded tomcat, this code works:

Servlet:

String test = "test";
request.setAttribute("test", test);
request.getRequestDispatcher("/index.jsp").forward(request, response);

JSP:

<%= request.getAttribute("test") %>

It sets the attribute test and then prints it out on the servlet /example's jsp page example.jsp.


However, if I try to set the attribute within the session then I don't get the same result, instead, I get a null when using this:

Servlet:

String test = "test";
request.getSession().setAttribute("test", test);
request.getRequestDispatcher("/index.jsp").forward(request, response);

JSP:

<%= session.getAttribute("test") %>

回答1:


On the JSP side, you don't need to say request.getSession(), just session.getAttribute();
And you had a problem in your Main.java when creating the servlet context (a trick of using embedded Tomcat); you were not getting the context created by adding the webapp to tomcat, you had some other context.

//          File base = new File("src/main/webapp");
//          context = tomcat.addContext("", base.getAbsolutePath());
//          tomcat.addWebapp(null, "/", base.getAbsolutePath());

        context = tomcat.addWebapp("/", new File("src/main/webapp").getAbsolutePath());
        context.setSessionTimeout(10080);

I commented out your code and changed the context handling and now things work. And a new exception to be caught.

        } catch (ServletException | InterruptedException | LifecycleException exception) {



回答2:


You may want to compare the session id in the servlet and the jsp. If they are different maybe check your session and cookie configuration in tomcat



来源:https://stackoverflow.com/questions/23167654/servlet-not-forwarding-session-attribute-to-jsp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!