actually I am developing a application using Spring MVC, in one case I have to make the user to wait for the results by displaying a page..and once the back end processes the request..the results will be loaded. Can anyone please tell me how can I achieve that?
I'd say this is more of a javascript solution than necessarily a Spring one.
Lets say you're waiting on a request from the back end process, you could use the solution here to wait for a response while your back end produces the data you require.
The code below would show the code within the loaderImage id (say it's a div in html), then hide it when the success is loaded. The ajax request would just be whatever POST or GET you use to get to your back end controller.
$('#loaderImage').show();
$.ajax({
// Other ajax parameters
success: function () {
// hiding the image here
$('#loaderImage').hide();
}
});
You can use
window.onload();
<!doctype html>
<html>
<head>
<title>onload test</title>
<script>
function load() {
alert("load event detected!");
}
window.onload = load;
</script>
</head>
<body>
<p>The load event fires when the document has finished loading!</p>
</body>
</html>
SO there you can remove your loading div or html.
https://developer.mozilla.org/en-US/docs/DOM/window.onload
Related
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.
Environment: IE7, jQuery 1.1 , Struts 1
Context: Making an ajax call to a Java method which, and the end, reloads the same jsp.
The steps are: jsp A -->request to java method-->doing some stuff-->ActionForward to jsp A, which is returned in the response.
Actually I'm doing this with a single request using location.href and it's working properly.
Now I need to handle multiple requests and conditions and the only way I thought was by using nested ajax calls with async:false, but that's not the point.
The problem is ajax does not reloads the jsp like location.href does.
This jsp is just a smaller part of the main jsp, so I'm not reloading the whole jsp. I guess I have to handle the response in some way, but how?
Call with location.href:
<script>
function myFunction(){
location.href = 'path/to/java/method=with_some_parameters';
}
</script>
Call with ajax:
<script>
function myFunction(){
jQuery.ajax({
url:'path/to/java/method=with_some_parameters'
async:false,
success:function(data){
//nested ajax
}
});
}
</script>
There is a similiar question:
Reload a page after jquery ajax call,
but it didn't help.
Another: How to manage a redirect request after a jQuery Ajax call, this looks better. I'm trying some things.
As I got the full html in the response ('data' in my case), It worked using
function myFunction(){
jQuery.ajax({
url:'path/to/java/method=with_some_parameters'
async:false,
success:function(data){
document.open();
document.write(data);
document.close();
//nested ajax
}
});
}
Source Replacing Entire Page Including Head Using Javascript
I have a basic html file which is attached to a java program. This java program updates the contents of part of the HTML file whenever the page is refreshed. I want to refresh only that part of the page after each interval of time. I can place the part I would like to refresh in a div, but I am not sure how to refresh only the contents of the div. Any help would be appreciated. Thank you.
Use Ajax for this.
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Relevant function:
http://api.jquery.com/load/
e.g.
$('#thisdiv').load(document.URL + ' #thisdiv');
Note, load automatically replaces content. Be sure to include a space before the id selector.
Let's assume that you have 2 divs inside of your html file.
<div id="div1">some text</div>
<div id="div2">some other text</div>
The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.
You can, however, communicate between the server (the back-end) and the client.
What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.
Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.
setInterval(function()
{
alert("hi");
}, 30000);
You could also do it like this:
setTimeout(foo, 30000);
Whereea foo is a function.
Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.
A classic AJAX looks like this:
var fetch = true;
var url = 'someurl.java';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'fetch' : fetch // You might want to indicate what you're requesting.
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
$('#div1').html(res1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.
I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
Usefetch and innerHTML to load div content
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
btn.disabled = true;
dynamicPart.innerHTML = "Loading..."
dynamicPart.innerHTML = await(await fetch(url)).text();
setTimeout(refresh,2000);
}
<div id="staticPart">
Here is static part of page
<button id="btn" onclick="refresh()">
Click here to start refreshing every 2s
</button>
</div>
<div id="dynamicPart">Dynamic part</div>
$.ajax(), $.get(), $.post(), $.load() functions of jQuery internally send XML HTTP request.
among these the load() is only dedicated for a particular DOM Element. See jQuery Ajax Doc. A details Q.A. on these are Here .
I use the following to update data from include files in my divs, this requires jQuery, but is by far the best way I have seen and does not mess with focus. Full working code:
Include jQuery in your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Create the following function:
<script type="text/javascript">
function loadcontent() {
$("#test").load("test.html");
//add more lines / divs
}
</script>
Load the function after the page has loaded; and refresh:
<script type="text/javascript">
$( document ).ready(function() {
loadcontent();
});
setInterval("loadcontent();",120000);
</script>
The interval is in ms, 120000 = 2 minutes.
Use the ID you set in the function in your divs, these must be unique:
<div id="test"></div><br>
new to angularjs. I am sure i am missing something.
I am unable to render the response send by server on jsp page if i hit server with angularjs's $http directive.
angularcode
// Read button Handler
$scope.readAll=function(){
readTable($scope.clnfamilyArray);
//send data to server
testAddItem=function(){
$http({
'url' : 'http://localhost:9090/QuantumM/orbital/sendstatement/',
'method' : 'POST',
'headers': {'Content-Type' : 'application/json'},
'data' : $scope.clnfamilyArray
}).success(function(data){
console.log(data);
})
}//end of function
testAddItem();
}////end of readAll
spring code
#RequestMapping(value = "/sendstatement/", method = RequestMethod.POST)
public ModelAndView welcome(#RequestBody String map) {
ModelAndView model = new ModelAndView();
// BL
model.addObject("name",hTable.toHtml());
model.setViewName("test");
return model;
}
test.jsp
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<h1>Gradle - Spring MVC Hello World</h1>
<h2>Hello ${name}</h2>
</body>
</html>
Instead of rendering test.jsp. I am landing on the same page. But on console I can see the expected output..
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<h1>Gradle - Spring MVC Hello World</h1>
<h2>Hello <table border=1><tr><td colspan=2>s</td></tr><tr><td colspan=1>f</td><td colspan=1>d</td></tr></table></h2>
</body>
</html>
Is there anything which I am missing ???
I wanted to landed on test.jsp not on my current calling page...
You are missing something, as you guessed. The purpose of the $http call is to fetch the results of an HTTP call and provide it to your AngularJS application's model. It is not meant to redirect you to a new page on another server.
The reason you see the page output in the console is due to the .success() portion of the http call:
$http({
'url' : 'http://localhost:9090/QuantumM/orbital/sendstatement/',
'method' : 'POST',
'headers': {'Content-Type' : 'application/json'},
'data' : $scope.clnfamilyArray
}).success(function(data){ // The data is passed here when received
console.log(data);
})
It's an async call handled by a promise. So your app makes the http call, and then goes on its merry way. When the data from that http call is available, it is passed to your .success() call and then you log it to the console. Here's a Plunk demo I did showing how promises work in serial and parallel so you can see some of their benefit.
This is not the Angular way. What you should be doing for a single-page-app in AngularJS is fetch the DATA from the server, not a rendered page, and then display it to the user with AngularJS views.
Instead of having your SpringMVC app render the view, have it pass the model back as JSON data. That way, you will be able to easily show it to the user in your AngularJS view.
My guess is that if you took your example and had it return JSON, it would return something like:
{
"name": "Bob"
}
Then you would change the .success() call to do something like this:
.success(function(data) {
$scope.name = data.name;
})
And in your view, you would show it with:
<p>Hi {{name}}</p>
Hope this helps.
I have a application that invokes a servlet through the URL
> "http://server:port/context-root/myservlet"
The servlet then calls the Java Class which returns the query result back to servlet.The servlet then renders the data to the user through a JSP page(response.redirect)
Now it hapens so, when all this happens Page Cannot be displayed is rendered to the useruntil the JSP page is ready to show the data.
How can I show a loading gif or a messgae as soon as the servlet is invoked until the JSP page is loaded with all the required data:
NOTE: As mentioned above, I am first calling the servlet, then Java Class, then JSP.
#Sankalp - The invoking application (HTML page ) is solely responsible for making an AJAX Call to your servlet. If you dont have control over the invoking application here is a little trick you can do - Ask the invoking application to re-direct to an html file say an index.html file of your application . In the index.html file , export jQuery javascript library and make appropriate ajax call , show a loading image , and upon success you may re-direct the page to desired jsp. There is a lot of work to be done here.
Question : Does the invoking application pass you any parameters ?
Does it POST data to you ?
Does your application open in an IFRAME of the invoking application or its a pure re-direct ?
All these answers , would help you decide your next course of action. There are lots of post on AJAX calls and showing images on stack overflow but that does not solve your essential problem . You have to decide on the flow and where to put the AJAX code. The AJAX part would be the easiest one. :)
----- Editing after the last comment
Visit : jQuery
In your HTML
<html>
<head>
<script src="jquery.min.js"></script> <!-- where you keep your resource file -->
<script language="javascript" type="text/javascript">
$(document).ready(function() { //This call will be made when DOM
//hierarchy has been fully constructed
// Handler for .ready() called.
//Make AJAX Call here so that this simple HTML page
///directly calls the AJAX
// and decide the future action based on AJAX success / failure
});
</script>
</head>
<body>
</body>
</html>