简体   繁体   English

servlet没有将会话属性转发给jsp

[英]servlet not forwarding session attribute to jsp

Using embedded tomcat, this code works: 使用嵌入式tomcat,此代码有效:

Servlet : Servlet

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

JSP : JSP

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

It sets the attribute test and then prints it out on the servlet /example 's jsp page example.jsp . 它设置属性test ,然后在servlet /example的jsp页面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: 但是,如果我尝试在会话中设置属性,那么我得不到相同的结果,相反,我使用它时得到一个null

Servlet : Servlet

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

JSP : JSP

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

On the JSP side, you don't need to say request.getSession() , just session.getAttribute(); 在JSP方面,您不需要说request.getSession() ,只需说session.getAttribute();
And you had a problem in your Main.java when creating the servlet context (a trick of using embedded Tomcat); 在创建servlet上下文时,你在Main.java中遇到了问题(使用嵌入式Tomcat的技巧); you were not getting the context created by adding the webapp to tomcat, you had some other context. 你没有通过将webapp添加到tomcat来创建上下文,你还有其他一些上下文。

//          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) {

You may want to compare the session id in the servlet and the jsp. 您可能希望比较servlet和jsp中的会话ID。 If they are different maybe check your session and cookie configuration in tomcat 如果它们不同,可以在tomcat中检查您的会话和cookie配置

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

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