Passing value from servlet to html [duplicate]

时光毁灭记忆、已成空白 提交于 2019-12-23 17:14:43

问题


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


回答1:


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

  • Servlet
  • JSP



回答2:


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!




回答3:


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.




回答4:


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.




回答5:


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>



来源:https://stackoverflow.com/questions/10594919/passing-value-from-servlet-to-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!