1

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

ZakiMak
  • 2,072
  • 2
  • 17
  • 26

2 Answers2

0

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

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

Community
  • 1
  • 1
Ofer Lando
  • 814
  • 7
  • 12
  • Been there, done that. Didn't work. Besides the framework default search for that name in several implicit objects included requestScope – Giuseppe Manzo Jan 14 '15 at 10:15
0

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>
ZakiMak
  • 2,072
  • 2
  • 17
  • 26