【问题标题】:context object not work in jsp or servlet file上下文对象在 jsp 或 servlet 文件中不起作用
【发布时间】:2014-08-04 08:07:42
【问题描述】:

我正在创建许多 jsp 和 servlet 文件但是,这一次我很困惑......

我有 1 个名为 test.java 的 servlet 文件

ServletContext context =  request.getServletContext();

context.setAttribute("Fname","chintan");
context.setAttribute("Lname","popat");
request.getRequestDispacher("test.jsp").forword(request,response);

在 test.jsp 中

<%
   String fname = (String)context.getAttribute("Fname");  //popat
   String lname = (String)context.getAttribute("Lname");  //popat
%> 

在jsp文件中获取存储在最后一个上下文对象中的所有上下文属性值 所以怎么可能 2 diff 属性在我设置 diff 值时返回样本值

【问题讨论】:

  • 这真的很奇怪。不应该发生。
  • 您是否在“chintan”和“popat”值的集合中使用变量(覆盖)值? IE string value = "chintan" , context.setAttribute("Fname",value);
  • 上下文是“ServletContext”的对象

标签: java jsp servlets


【解决方案1】:

这是我的工作测试:

在 servlet 中:

ServletContext context = request.getServletContext();
context.setAttribute("Fname","chintan");
context.setAttribute("Lname","popat");
request.getRequestDispatcher("/test.jsp").forward(request, response);

test.jsp:

<%
String fname = (String)application.getAttribute("Fname");  //chintan
String lname = (String)application.getAttribute("Lname");  //popat
out.write(fname); out.write(lname);
%> 

正确写入chintanpopat

但是...它同时处理一个请求,因为应用程序上下文在应用程序的所有请求之间共享。在 jsp 中,servlet 上下文可以通过application 而不是context 访问(除非您在其他地方设置了它)。

【讨论】:

    【解决方案2】:

    你做错了,使用 PageContext 中的 forward 方法,而不是 RequestDispatcher 中的方法

           pageContext.forward("/resource.jsp"); 
    

    https://tomcat.apache.org/tomcat-7.0-doc/jspapi/javax/servlet/jsp/PageContext.html#forward(java.lang.String)

    【讨论】:

    • 有同样的问题
    • 尝试 request.setAttribute("attribute-name","attribute-value")。并以“${requestScope['attribute-name']}”的形式从页面获取它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    相关资源
    最近更新 更多