Passing value from servlet to html [duplicate] - java

This question already has answers here:
Generate an HTML Response in a Java Servlet
(3 answers)
Closed 6 years ago.
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

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!

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

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.

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.

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>

Related

Redirecting the page with Servlets Java

I have a jsp page with a form that when it’s submitted goes to a Servlet that inserts the form data into the database.
When the data is inserted into the database, I’m trying to get the browser back to my jsp page and show a javascript alert saying that the data was inserted successfully, my code is the following:
RequestDispatcher rd;
if(dao.insertClient(client)) {
rd = getServletContext().getRequestDispatcher("/pages/clients.jsp");
rd.include(request, response);
out.print(
"<script type=\"text/javascript\">"
+ "alert("Client inserted successfully!");"+
"</script>"
);
}
This code is doing exactly what I want, but this method getRequestDispatcher() redirects the page to the servlet itself, and the URL is like http://localhost:8080/Servlet, this way I can’t access any intern link of the page, since the links to the other pages obviously are outside of the servlet context, and the glassfish returns the 404 error.
Instead of using getRequestDispatcher(), I’ve tried using the response.sendRedirect(), this way I can insert the data into the database and access the intern links, but the javascript alert isn’t shown.
Somebody has a suggestion on how I can redirect the page to the clients.jsp and display the javascript alert?
Thanks!
you can try another approach :
Set parameter from servlet like this :
RequestDispatcher rd;
if(dao.insertClient(client)) {
rd = getServletContext().getRequestDispatcher("/pages/clients.jsp");
request.setAttribute("isSuccess", "success");
rd.include(request, response);
}
access the parameter in jsp to check whether to show alert or not.
<%
String result = request.getParameter("isSucess");
if("success".equals(result)){
%>
<script type="text/javascript" >
alert("Client inserted successfully!");
</script>
<%
}
%>

return from servlet to jsp to specific id in index page

I am working on java servlet project
I have index.jsp page that take input from user and send it withe post method to readXml servlet page that process the input then return the result to index.jsp
I wont to return to specific id in index.jsp
I used this code for foreword response to index.jsp
request.setAttribute("message", span );
request.setAttribute("Sent", input );
request.getRequestDispatcher("/indexjsp.jsp#color").forward(request, response);
request.getRequestDispatcher("/indexjsp.jsp#color").forward(request, response);
when I use this code I get resource error
and when I remove #color it will return the response to index.jsp but not with id I wont.
are there any way to return to specific id from servlet?
DO it something like this
instead of using #color try ?id=color.
Populate this parameter in the hidden input tag on 'index.jsp'. Now you have your tag id on client side. you can do what you want using javascript after onload event triggers.

How to use struts tag in javascript

I'm trying to get value from Action using Ajax request, but I'm having problem in using struts tag in javascript to show the value.
Javascript code:
dojo.xhrPost({
url: "dashboard"
,content: myParameterscomp
, handle: function(response, ioargs) {
if (ioargs.xhr.status == 200)
{
var data = "<s:property value='#request.consumptionData'/>"
console.log(data);
}
}
,error: function (data) {
handleError(data.description);
}
});
Java code:
Map request = (Map)context.get("request");
request.put("consumptionData", 43);
I'm getting the value of data as <s:property value='#request.consumptionData'/> on console instead of 43. I'm using struts2. My javascript code is in JSP file. Could anyone please tell me how can I show the value?
You seems to be calling /dashboard page via Ajax from your homepage. And expecting it to send you request attribute consumptionData. This won't work as your JSP does not contain required data. You need to put data in JSP and then fetch the same in Ajax. Convert your response to JSON. The simplest way of doing this would be to put following like of code in your Ajax response JSP.
Dashboard.jsp
{"consumptionData": < "<s:property value='#request.consumptionData'/>"}
And in main page when you load this JSP via ajax, you can parse this JSON output and use data in Javascript.
var json = JSON.parse(response);
var data = eval(json.consumptionData);
Code in browser accepts JSON. You could serialize you request as JSON and embed in you JavaScript file. For example:
var data = <%= toJson(request.get("consumptionData")) %>
If the data is simplely Integer values, you can even directly put the value in the code:
var data = <%= request.get("consumptionData") %>
The syntax could be vary (I'm not familiar with struts tag), but the idea is the same.

How can we tell jQuery to access a Java arraylist in JavaServlets?

I am using Java servlets and JSP in my web application. My question is that how can i tell jQuery to access a java arraylist. For example i want to show a list of books in my page and i am getting list of those books using java servlet. Now i want to tell jQuery that if a specific button is clicked then show these books in that page. How can i do that? Or is there any other way to do that? Thanks in advance.
jQuery is a client side framework, it can not access the arraylist. Servlets/JSP are server side. When jQuery sees the page, its just plain html.
What you can do is, convert your arraylist to JSON, and then output the json string in your JSP. jQuery can use the json string to display data on page.
You can have a look at http://code.google.com/p/google-gson/, which is one of the best Java-JSON library available.
You should use Json Library in order to serialize your ArrayList to JSON:
String json = (new JSONArray(yourList)).toString();
And use this on mouseclick in jquery like :-
var list= <%= json %>;
Here is an Ajax solution: In the servlet side, you have to write a logic in doGet or doPost method, which returns the contents of the list in XML, JSON or HTML.
In client-side you have to write a logic which interprets and displays this data. In case of HTML, you just have to put the content into a DIV. In case of JSON or XML, you have to use further JQuery components (plugins) for example jqGrid. A simple example on client side for the HTML-based solution:
$.get('getlist', function(data) {
$('#Listdiv').html(data);
});
Listdiv is the id of a DIV where the list will be displayed. getlist is the URI which your servlet will respond for.
Generating HTML content into String and write it into the HttpServletOutputStream isn't an issue:
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String result = null;
//TODO generate HTML into 'result' here
Writer out = new OutputStreamWriter(resp.getOutputStream(), "utf-8");
resp.setContentType("text/html");
out.write(result);
out.close();
}
If you don't want to create a separated servlet, you can also use HTML content generated by JSP. In this case, you can put the JSP uri into the Ajax call: $.get('getlist.jsp'...)

Sending multiple parameters to servlets from either JSP or HTML

I need to send a particular parameters to Servlet from JSP page. E.g: if I click on the Facebook icon on the web page, then I should send "facebook" as parameter to my Servlet and my Servlet will respond according to the parameter received from JSP file or HTML file.
This is a very open ended question, but the easiest way is to specify parameters in a query string.
If you have the following servlet:
/mysite/messageServlet
Then you can send it parameters using the query string like so:
/mysite/messageServlet?param1=value1&param2=value2
Within the servlet, you could check your request for parameters using getParameter(name) if you know the name(s), or getParameterNames(). It's a little more involved, specifically with consideration to URL Encoding and statically placing these links, but this will get you started.
String message = request.getParameter("message");
if ("facebook".equals(message))
{
// do something
}
Storing links with multiple parameters in the querystring requires you to encode the URL for HTML because "&" is a reserved HTML entity.
Send Messages
Note that the & is &.
Just wrap the icon in a link with a query string like so
<img src="facebook.png" />
In the doGet() method of the servlet just get and handle it as follows
String name = request.getParameter("name");
if ("facebook".equals(name)) {
// Do your specific thing here.
}
See also:
Servlets info page
One way is to have hidden form variables in your jsp page that get populated on click.
<form action="post" ....>
<input type="hidden" id="hiddenVar" value="">
<a hfref="#" onclick="doSomething();">Facebook</a>
</form>
<script>
function doSomething() {
var hiddenVar= document.getElementById('hiddenVar');
hiddenVar.value = "facebook";
form.submit();
}
</script>
This gives you flexibility to control what gets passed to your servlet dynamically without having to embed urls in your href

Categories