[英]Cannot get attribute (in request scope) set by Servlet and forwarded to JSP
I tried several solution even here on StackOverflow but none seems to work: I want to pass a string from a Servlet to a JSP and show it with EL. 即使在StackOverflow上,我也尝试了几种解决方案,但似乎没有任何效果:我想将一个字符串从Servlet传递到JSP并用EL显示。
I created a simple plain project on Netbeans and this is the code I added: 我在Netbeans上创建了一个简单的普通项目,这是我添加的代码:
Servlet Code: Servlet代码:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String message = "Hello";
request.setAttribute("message", message);
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request, response);
}
JSP Code: JSP代码:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<h2 style="border: 2px solid brown; width: 20%"> Message is: ${message} </h2>
</body>
</html>
What get me frustated is that even for the documentation (Oracle Api Reference and a HeadFirst O'Reilly Guide) this should be straightforward, but I simply get no text, even if I use a scriptlet. 让我感到沮丧的是,即使对于文档(《 Oracle Api参考》和《 HeadFirst O'Reilly指南》)来说,这也应该很简单,但是即使我使用scriptlet,我也不会得到任何文本。 I tried both Glassfish and TomEE 我尝试了Glassfish和TomEE
Instead of ${message}, try using ${requestScope.message} 尝试使用$ {requestScope.message}代替$ {message}
(Based on https://stackoverflow.com/a/4912797/1843508 ) (基于https://stackoverflow.com/a/4912797/1843508 )
I am more or less certain your problem is that your Servlet is not being invoked. 我或多或少可以确定您的问题是您的Servlet没有被调用。 Put a console(System.out.println) output in your Servlet and see if the output is printing. 在您的Servlet中放置一个console(System.out.println)输出,并查看输出是否正在打印。
Do not try to access the JSP page directly. 不要尝试直接访问JSP页面。 Rather hit the URL mapped for your Servlet. 而是点击为您的Servlet映射的URL。
Your Servlet can be mapped in two ways: 1. Annotation 2. Deployment Descriptor (web.xml) 您的Servlet可以通过两种方式映射:1.注释2.部署描述符(web.xml)
@WebServlet("/processForm")
public class UploadServlet extends HttpServlet {
// implement servlet doPost() and doGet()...
}
In the case above if you hit /processForm relative to your webapp the UploadServlet will be called and any processing by the Servlet will be carried out and forwarded if dispatcher is used. 在上述情况下,如果您相对于您的Web应用程序命中/ processForm ,则将调用 UploadServlet,并且如果使用了调度程序,则将执行并转发Servlet的任何处理。
A descriptor equivalent is shown below: 等效的描述符如下所示:
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.bla.bla.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/processForm</url-pattern>
</servlet-mapping>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.