servlet不会将会话属性转发给jsp [英] servlet not forwarding session attribute to jsp

查看:103
本文介绍了servlet不会将会话属性转发给jsp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用嵌入式tomcat,此代码有效:

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") %>

它设置属性 test 然后打印它出自servlet / example 的jsp页面 example.jsp

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

但是,如果我尝试在会话中设置属性,那么我得不到相同的结果,相反,我得到 null 使用时:

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") %>


推荐答案

在JSP方面,你不需要说 request.getSession(),只是 session.getAttribute();
你的问题在于你的问题创建servlet上下文时的Main.java(使用嵌入式Tomcat的技巧);你没有通过将webapp添加到tomcat来创建上下文,你还有其他一些上下文。

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

这篇关于servlet不会将会话属性转发给jsp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆