如何访问JSP中的servlet设置的请求属性?

Ale*_*lex 22 java jsp servlets el

我正在尝试在JSP页面中检索由servlet设置的属性值,但我只是运气参数${param}.我不确定我能做些什么不同.也许它很简单,但我无法管理它.

public void execute(HttpServletRequest request, HttpServletResponse response) {

    //there's no "setParameter" method for the "request" object
    request.setAttribute("attrib", "attribValue");

    RequestDispatcher rd = request.getRequestDispatcher("/Test.jsp");
    rd.forward(request,response);
}
Run Code Online (Sandbox Code Playgroud)

在JSP中我一直试图检索"attribValue",但没有成功:

<body>
    <!-- Is there another tag instead of "param"??? -->
    <p>Test attribute value: ${param.attrib}
</body>
Run Code Online (Sandbox Code Playgroud)

如果我通过一个参数传递所有进程(调用页面,servlet和目标页面),它的效果非常好.

Bal*_*usC 28

它已经在默认的EL范围内可用,所以只是

${attrib}
Run Code Online (Sandbox Code Playgroud)

应该做.

如果您想明确指定范围(EL将按顺序搜索与属性名称匹配的第一个非null属性值的页面,请求,会话和应用程序范围),那么您需要通过范围映射来引用它,这是${requestScope}针对请求范围的

${requestScope.attrib}
Run Code Online (Sandbox Code Playgroud)

这仅在页面范围中可能具有完全相同名称的属性时才有用,否则该属性将优先(但这种情况通常表示设计不佳).

也可以看看:


smw*_*dia 9

也许EL语法和scriptlet语法之间的比较将帮助您理解这个概念.

  • param 就好像 request.getParameter()
  • requestScope 就好像 request.getAttribute()

你需要告诉request attributerequest parameter.