3

I have a servlet that processes some content from the web and generates a String value. I need to display this String value in a html page within a table tag.

How do I pass this string value from servlet using the setAttribute method and getrequestdispatcher method?

Thanks Abhishek S

London guy
  • 27,522
  • 44
  • 121
  • 179

5 Answers5

9

In your Servlet, set data as attribute in request:

RequestDispatcher dispatcher = request.getRequestDispatcher("yourJspPage.jsp");
request.setAttribute("Name", "Temp"); // set your String value in the attribute
dispatcher.forward( request, response );

In your jsp page, access the request attribute like this:

<table>
    <tr>
        <td><%=request.getAttribute("Name")%></td>
    </tr>
</table>

Hope this helps!

HashimR
  • 3,803
  • 8
  • 32
  • 49
3

You can pass the data from servlet to JSP (not HTML) using request forward and by setting data as attribute in request and then on JSP you can render those data to generate HTML


See

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
0

First create a PrintWriter object, which will produce the output on HTML page.
Here response is HttpServletResponse object from doGet or doPost method.

response.setContentType("text/html");  
PrintWriter out = response.getWriter();  
out.println("<html-code>")

If you want to use table tag then you can do this as

out.println("<html><body><table>...your code...</table></body></html>");

The result will be displayed on HTML page.

Jainendra
  • 24,713
  • 30
  • 122
  • 169
0

Suppose you sent ajax get request from html using jquery. This is in html script

$.get('HelloServlet', {a:'abc',b:'abc'}, function (data) {  
   alert(data);  
});

This code in Servlet

String str = "abc";
PrintWriter out = response.getWriter();  
out.write(str);

When your servlet successfully executes you get 'str' variable value in alert 'data' variable.

0

You can do this by passing the servlet value as HTML-JavaScript-content and then access that content in the script tag.

You can try this: In Servlet method

PrintWriter out = response.getWriter(); out.print("var xyz = 20;");

In HTML Page Inside script tag:

var abc = xyz;

But you will have to execute the servlet in the HTML page. In tomcat, if you have the servlet mapping just type:

"<\script src="/servlet-name"></script>