0

I am trying a simple example of sending values from a servlet Servlet1.java to client-side JSP page client1.jsp.

But I am getting null Here is the code Server1.java:

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.util.*;


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

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

    String name="Rahul";
    request.setAttribute("myname",name);

    //Servlet JSP communication
    RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("/client1.jsp");
    reqDispatcher.forward(request,response);

}
}

Code for client1.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <% String s=request.getParameter("myname");%>
    Hello friends <%=s%>
</body>
</html>
Würgspaß
  • 4,660
  • 2
  • 25
  • 41
Rahul Choubey
  • 29
  • 1
  • 10

2 Answers2

2

What you do is bad.

First you are mixing attributes and parameters. They are different animals. Parameters is what comes from the client and are set once by the servlet container. Attributes are objects that are used by cooperating elements (filters, servlets and JSP pages) for passing data.

So you should at least read the attributes in JSP:

<% String (String) s=request.getAttribute("myname");%>

You must cast the attribute to String because getAttribute returns an Object.

But that's not all. Scriptlets are deprecated for decades, and should only be used for very special use cases, if any. Here, assuming you have a decent servlet container, you could simply use the ${} JSTL automatic attribute:

<body>
    Hello friends ${myname}
</body>

It is shorter, cleaner and less error prone.

After your comments, there is another possible problem. You only show the override of doPost in your servlet code, when common requests (unless you post from a form) are GET requests and are processed in doGet. If you use a GET request and only set the attribute in doPost your JSP will not find it...

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
1

"myname" you are setting to request.setAttribute

so, you can retrieve as below:

<% String s=(String) request.getAttribute("myname");%>
Durga Prasad
  • 81
  • 1
  • 9