简体   繁体   中英

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.

I created a simple plain project on Netbeans and this is the code I added:

Servlet Code:

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:

<%@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. I tried both Glassfish and TomEE

Instead of ${message}, try using ${requestScope.message}

(Based on https://stackoverflow.com/a/4912797/1843508 )

I am more or less certain your problem is that your Servlet is not being invoked. Put a console(System.out.println) output in your Servlet and see if the output is printing.

Do not try to access the JSP page directly. Rather hit the URL mapped for your Servlet.

Your Servlet can be mapped in two ways: 1. Annotation 2. Deployment Descriptor (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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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