I'm using Spring MVC and I need to make an asynchronous call to the server only once when the JSP page has loaded completely.
What I actually have is a Controller that returns a List. I call the Controller using AJAX. The problem with my solution is that I'm not able to get the data of List after load JSP page.
#RequestMapping(method=RequestMethod.GET, value="/myList")
public ModelAndView getSubView(Model model)
{
model.addAttribute("list", userServiceI.getAllUsers());
return new ModelAndView( "myList" );
}
<script type="text/javascript">
function ajaxPost() {
$.ajax({
type: "GET",
url: "myList",
success: function(list) {
alert(list.get(0).name);
}
});
}
</script>
Is there any way to return a List After page loaded or how to load asynchronously? Thanks in advance.
Just return List of User instead of ModelAndView and give annotation on List object #ResponseBody. User should be Serializable and you can call ajax function either on wiondwos.onload or document.ready it will load list asynchronously .Do not return ModelAndAiew, it is used for redirecting on page in case of form submit.
You need to return Json you can try it as follows
#RequestMapping(method=RequestMethod.GET, value="/myList")
public String getSubView(Model model)
{
JSONObject json = new JSONObject();
return json.put("list", userServiceI.getAllUsers());
}
or you can use #ResponseBody as
#RequestMapping(method=RequestMethod.GET, value="/myList")
#ResponseBody
public ArrayList getSubView(Model model)
{
return userServiceI.getAllUsers();
}
Related
Situation:
I have a jsp within a jsp. I load another jsp into a div of the outer jsp using .html(). I want to redirect my url into an entirely new url mapping from a controller.
Sample controller:
#RequestMapping(value = { "/main/submit" }, method = RequestMethod.POST)
public String main(ModelMap model) {
System.out.println("In controller");
return "redirect:/anotherJSP";
}
#RequestMapping(value = { "/anotherJSP" }, method = RequestMethod.POST)
public String anotherJSP(ModelMap model) {
System.out.println("In another");
return "anotherJSP";
}
Jsp within a jsp:
$.ajax({
type : "POST",
url : "/main/submit",
success : function(msg) {
console.log('redirect');
},
error : function() {
alert("Error.");
}
});
Now, the problem is that the outer jsp stays, and the /anotherJSP url only gets loaded in the innerJSP. I wanted to leave the two jsps and go to the new request mapping URL. Is there anyway I can do it? Thanks a lot in advance!
You can't redirect a POST.
When you return redirect:/anotherJSP, the server sends a redirect instruction back to the web browser, and the browser then sends a new GET request for the given URL.
The GET request will be for the URL given, with any query parameters. This means that and POST payload (data) will be lost.
Change #RequestMapping(value = { "/anotherJSP" }, method = RequestMethod.POST) to #GetMapping("/anotherJSP") (assuming Spring 4.3 or later).
Since an ajax call is asynchronous the effect of return "redirect:/anotherJSP"; is not affecting the browser window, instead you should use window.location.href in your ajax call like this:
$.ajax({
type : "POST",
url : "/main/submit",
success : function(msg) {
console.log('redirect');
window.location.href = /anotherJSP;
},
error : function() {
alert("Error.");
}
});
I have a simple JSP file with some radios, one text input and one button.
In the button onClick I am doing an Ajax request to a Spring controller as you can see bellow:
function callFiltrarViaAJAX() {
var filtro = $("#filtro").val();
var optFiltro = $('input[name=optFiltro]:checked').val();
$.ajax({
type : "GET",
url : "filtrar",
//dataType : "json",
data : {
filtro : filtro,
optFiltro : optFiltro
},
success: function(data) {
console.log("SUCCESS: ", data);
},
error: function(e) {
console.log("ERROR: ", e);
},
done: function(e) {
console.log("DONE");
}
});
}
In the Spring controller I am receiving this request with success with the following code:
#Controller
public class FiltroController {
#RequestMapping(value = "/filtrar", method = RequestMethod.GET)
public #ResponseBody String filtrarVacina(FiltroTO filtro, HttpServletResponse response, ModelAndView model) {
VacinaTO v = new VacinaTO();
v.setId(new Long(10));
v.setLote("Lote 1");
v.setNome("BCG");
model.addObject("vacina", v);
response.setStatus(200);
return "TEST OK";
}
}
As you can see in the code above, I'm adding a POJO object in the ModelAndView that I'am trying to use in the JSP to show the return of the Ajax request in a table.
My Ajax request returns with success too but the problem is that even returning with success I can't use the POJO object, when I try to access the object by expression language I got nothing.
I've been searching about this situation and I found a lot of contents but none of the solutions that I've found works for me, but I found an interesting answer:
JSP inside ListItems onclick
So, is it means that I can't get a new parameter in the same JSP file with a Ajax request ? If yes, would be a JSON file the better way to get the return from the Spring controller ?
You can't access the model because you're returning an arbitrary string from controller instead of the view in which you want to access model.
If you're trying to access vacine from some.jsp, then you should return some from the controller method.
Of course, what I said is valid if you have proper ViewResolver configuration.
I have index.jsp. This jsp calls the controller:
#Controller
public class CustomerController {
//Other code..
//..
String customerJSON = null;
ModelAndView model = new ModelAndView("index", "customerJSON", customerJSON);
return model;
}
customerJSON is a string that contains JSON information.
Controller returns customerJSON to jsp.
Now, in jsp, I want to show customerJSON into an alert.
In jsp I add:
<script>
var customer = "<c:out value='${customerJSON}'/>";
alert(customer);
</script>
The problem is that, this alert, starts when the page is loaded and not when the controller returns to jsp.
How can I show the alert after controller call and not when the page is loaded?
I would implement your controller method (and requestmapping) something like this:
#RequestMapping(value = "/getCustomer")
public #ResponseBody Customer getCustomer() {
Customer c = new Customer();
//do whatever is needed to init customer data
return c;
}
If you have jackson as dependency that will take care of json-serializing for you.
Then your javascript (using jquery) code could look something like this:
<script>
$.getJSON("getCustomer", data, function (result)
{
alert(result);
});
</script>
I am trying to POST to a Spring MVC controller method via ajax. Using Chrome's developer tools, I can tell that the values from the form are being sent, but in the method, the form values are null.
Here is the jquery call:
var form = $('#renegotiationForm').serialize();
$.ajax({
method:'POST',
url:'/renegotiate/wizard/startRenegotiation',
data:{'renegotiationForm': form},
success: function(data) { this.transitionTo(data); }
});
Here is the Spring MVC method (meant to return only a single string):
#RequestMapping(value="wizard/startRenegotiation", method = RequestMethod.POST)
public #ResponseBody String processStart(#ModelAttribute("renegotiationForm") RenegotiationForm form, BindingResult bindingResult) {
log.debug("Entered showStart(), method=POST");
RenegotiationType type = RenegotiationType.valueOf(form.getRenoType().trim().toUpperCase());
RenegotiationActivity activity = RenegotiationActivity.valueOf(form.getRenoActivity().trim().toUpperCase());
String result = "";
if (type == RenegotiationType.TYPE1 && activity == RenegotiationActivity.ACTIVITY1) {
result = "deleteType1";
}
return result;
}
The values are bound using the Spring Form taglib, and I have confirmed that the path attributes of the form tags match the fields of the RenegotiationForm.
I think it's because you are trying to send an "string" from ajax and you want to get and Object (RenegotiationForm), try to change it to String and Format in Server-side. I recommend you to add the type you are sending from client-side, too.
#RequestMapping(value = "wizard/startRenegotiation", method = RequestMethod.POST, produces="application/json")
Found the answer. Further on in my code, I had a function like this:
var ajaxcall = function() { $.ajax({
// ajax settings
});
}
Unfortunately, setting it up this way doesn't make it work as a jquery deferred, and specifically I couldn't use the .then() function to process of ajax requests.
Thanks for the help.
I'm having a problem with Spring MVC and Ajax. I'm trying to send a javascript list to my Spring Controller, but I can't. I've to do a search and I need to send a list with some parameters.
You will have to convert to the list to json if you sending via ajax, this From the spring blog itself :
$("#account").submit(function() {
var account = $(this).serializeObject();
$.postJSON("account", account, function(data) {
$("#assignedId").val(data.id);
showPopup();
});
return false;
});
#RequestMapping(method=RequestMethod.POST)
public #ResponseBody Map<String, ? extends Object> create(#RequestBody Account account, HttpServletResponse response) {
Set<ConstraintViolation<Account>> failures = validator.validate(account);
if (!failures.isEmpty()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return validationMessages(failures);
} else {
accounts.put(account.assignId(), account);
return Collections.singletonMap("id", account.getId());
}
}
You have to convert your list to JSON String , before using it as an AJAX parameter
This answer in SO might help
jquery ajax on client side
$.ajax({
type: "POST",
url: "submit",
data:JSON.stringify(detailsArr),
success: function(html){
alert( "Submitted");
}
});
and on server side
#RequestMapping(value = "/search", method=RequestMethod.POST)
public String yourMethod(#RequestBody String body){
//convert body to array using JSONLib, FlexJSON or Gson
}