send json and html at the same time - java

I implemented a SOA service using other services(I'm using java language). I use servlet to display an html table with the processed results. Is it also possible to send json with html? or in other words is it possible to send two different things in the response of the doPost method of httpservlet?

If you want your html page to access the json you could embed the data within a script tag:
<script type="application/javascript">
var mydata = {"foo":"bar"};
</script>

Related

How to access API controller from Spring in HTML

This is my controller:
#GetMapping("/getRandomWildSwimming")
public List<WildSwimming> getRandomWildSwimming() {
return wildSwimmingService.getRandomWildSwimming();
}
How I can access it with HTML? I'm confused, I saw some tutorials where I set return index.html for example, but I'm returning here actually service that show me collection data from Mongo in JSON when I send request for example: http://localhost:8080/wildswimming/getRandomWildSwimming page show me one collection from mongo in JSON format, how I can show that via html and stylize it a bit?
If you want to use this approach, you need a client. For example, you can use JS or PHP for it.
Then you need to create HTML pages, add scripts (using JS or PHP) to send requests, get responses and show it to user.
This looks like: user opens page -> client sends request to your spring controller -> spring controller returns response -> client gets and shows it to user.
OR
You can use Spring MVC if you do not how to launch client server.
You will need to add a dependency to your project so that spring boot knows how to convert an object into json. If you're using maven, add com.fasterxml.jackson.core:jackson-databind to your pom file.
Then, add the #ResponseBody annotation to the getRandomWildSwimming method so that it ends up looking like this...
#GetMapping("/getRandomWildSwimming")
public #ResponseBody List<WildSwimming> getRandomWildSwimming() {
return wildSwimmingService.getRandomWildSwimming();
}
This will make the controller respond with json when it is called in a web browser.
Assuming that it returns JSON that looks like this...
[{"rating":89},{"rating":24},{"rating":68}]
You can using the $.get function (from the jquery library), to make a call to the /getRandomWildSwimming api method, which will fetch the JSON and automatically convert it into a javascript array of objects...
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="resources/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Wild Swimming Records</h1>
<ul id="canvas">
</ul>
<script type="text/javascript">
$(document).ready(function(){
$.get("./getRandomWildSwimming", function(data) {
console.log(data[0].rating);
console.log("JSON: " + JSON.stringify(data));
$.each(data, function(index, value) {
$("#canvas").append("<li>" + value.rating + "</li>");
});
});
});
</script>
</body>
</html>
This should result in a page that looks something like this...
Wild Swimming Records
- 89
- 24
- 68
The first console.log line will take the rating property of the first object in the data array and print it to the browser console. The second console.log line will convert the entire array back into a json string and print it to the browser console.

Sending HTML to backend

I'm trying to send some rendered HTML to the backend, through ajax, using javascript or jquery, but I can't find the way to do it.
I'm trying to export that html to pdf using itext.
Is there any way that I can achieve this, sending the data as a String?.
Many thanks.
(I'm using Java and Spring on the backend)
You can send you HTML as a JSON object. Here a quick example.
var elm = document.getElementById('yourElement');
var value = elm.innerHTML;
var objToSend = JSON.stringify(value);
// now send using ajax
...

Passing json object via ajax from jsp to javascript

How can pass json values from jsp to javascript as object via ajax?
I can not use global js variables in jsp because this will lead to json content to be visible in page's source
Here is the scenario that I want to achieve:
url of jsp is opened in browser.
Data is being created in scriptlet and coverted to JSON format
json is "sent" to javascript as object
From above scenario, i understand that javascript must initiate the ajax call to jsp.
The issue with this, that jsp's code will be invoked 2 times:
When page is opened in browser - data is prepared
on each ajax call same code will be called again
Constrains: No jquery, no other libs, no servlets, no additional jsps. :(
EDIT:
There is additional problem, I need to pass multiple json objects to javascript.
I wont be able to do it with response.getWriter().write();
I don't think concatenating all json objects and sending is the correct solution.
The parsing of the received object in javascript http.responseText will be overwhelming.
Why do you need ajax here? If you know that you need to populate some things from server onto jsp page you can do that through scriplets itself:
EX
<%# page import="com.mypackage.PersonDAO" %>
<html>
<body>
<table>
<th>Name</th><th>Email</th><th>Contact</th>
<%
List<Person> myList = PersonDAO.getAllPersons();
for(Person person:myList)
{
%>
<tr>
<td><%=person.getName()%></td>
<td><%=person.getEmail()%></td>
<td><%=person.getContact()%></td>
</tr>
<%}%>
</table>
</body>
</html>
This is a very simple example. You can do more complex things using JSTL.. :)
So there is no jquery, no Servlets, no ajax and no extra jsp's :)
UPDATE
Since you want data in your javascript before page loads you can use jQuery's holdReady() method.
$.holdReady( true );
$.get( url, function() {
// Perform something
$.holdReady( false );
});
See but all modern browsers have developer tools like firebug for mozilla, so any ajax call made will be trapped by them. The only way you can secure them is my encrypting them.. which will complicate things for you... IF you can explain the scenario you are trying to implement may be I can come up with it..

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.

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