Cannot display data from servlet on the jsp page with request.getAttribute (it returns null)

28 views Asked by At

I try to send a short text from a servlet to a jsp, and display the text on the jsp page. But on the jsp page I see "null".

I have a jsp file: show.jsp :

  <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>   
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
Here is some text

<%
Object message=request.getAttribute("message");
out.println(message);
%>

</body>
<%= request.getAttribute("message") %>
</html>

And I have a servlet: DataServlet.java :

package com.servlettojsp;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/DataServlet")
public class DataServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;       
 
    public DataServlet() {
        super();      
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String mes="This is a message from the servlet";
        request.setAttribute("message", mes);
        RequestDispatcher rd= request.getRequestDispatcher("show.jsp");
        rd.forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {      
    }
}

Why I can't pass data from servlet to jsp ?

0

There are 0 answers