Resolving view from ajax request using spring 3 - java

Jquery code to call my spring controller:
$.postJSON("/DialogController", myJSON, function(data) {
previewDialog.html(data);
previewDialog.dialog('open');
});
And then my controller code, which causes a http 500 error, I have debugged it and find it all works fine until the return string(view name), what am I doing wrong ?
#RequestMapping(value = "/DialogController", method = RequestMethod.POST)
public String dialogController(Model model, #RequestBody MyClass myClass) {
myClass.setTitle("SUCCESS");
model.addAttribute("myClass", myClass);
return "dialogContent";
}
Using jquery load with get request on the controller works to an extent - in that it returns the view and loads into dialog; but the attribute is not added to model and I can not post json data to the controller.
Any tips ?

Have you tried putting #ResponseBody in your Controller? More information on this annotation is here: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-responsebody

Related

Spring Controller to get both GET and POST variables

Sometimes we send a POST HTTP request with POST payload to an endpoint with URL variable, for example:
[POST] http://example.com/update-item?itemid=123456
To get the POST payload in the Spring controller class, I can do something this:
#RequestMapping(value = "/update-item", method = RequestMethod.POST)
public String updateItem(#RequestBody Item json) {
//some logics
return "/update-item-result";
}
However, at the same time, how can I get the variable from the URL (i.e. itemid in the above example) even for method = RequestMethod.POST?
I see a lot of Spring MVC examples on the web either get the GET variables from the URL or the POST variables from the payload, but I never see getting both in action.
You can use multiple HTTP requests by specifying the method attribute as an array in the #RequestMapping annotation.
#RequestMapping(value = "/update-item", method = {RequestMethod.POST,RequestMethod.GET})
public String updateItem(#RequestBody Item json) {
//some logics
return "/update-item-result";
}

Can I get a POJO in an Ajax Request to a Spring Controller?

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.

Spring MVC JSP Jquery call controller method on button click post redirect error

Assumptions, I am new to Spring MVC, JSP, Scripting/Ajax
Here's my task.
In Spring MVC, I have buttons in my jsp page, on button click, I want to perform some task (controller method), which doesn't return anything. I want to show the same page. It shouldn't reload the page nor should redirect to some other page.
Here's what I am doing...
I have a page with lots of buttons. I am using bootstrap css and button tag.
like,
Start
On this button click, I am calling an Ajax to the method from controller,
$('#startApp').click(function() {
BootstrapDialog.show({
message : 'Sure ?!',
buttons : [ {
label : 'Ok',
cssClass : 'btn-default',
action : function(dialogItself) {
$.ajax({
type : "POST",
url : "/MyApp/startApp",
success : function(response) {
alert("Success");
}
});
dialogItself.close();
}
}, {
label : 'Close',
action : function(dialogItself) {
dialogItself.close();
}
} ]
});
This calls the controller method,
#RequestMapping(value = "/startApp", method = RequestMethod.POST)
public void start() {// some operation.}
However, when I do this, operation is performed but in logs I am getting below error,
root cause dispatcher: com.ibm.ws.jsp.webcontainerext.JSPErrorReport: JSPG0036E: Failed to find resource /WEB-INF/views/startApp.jsp
Questions,
Is it the right way to do ?
I don't want to redirect to startApp.jsp, I want it to return to my index.jsp (where the code resides), how can I achieve this ?
You need to return something to the client. Spring default tries to send back startApp.jsp because that's what in the url (/startApp). Try this: this will send back an HTTP OK status (200).
#RequestMapping("/startApp", method = RequestMethod.POST)
public ResponseEntity start()
{
return new ResponseEntity(HttpStatus.OK);
}
You can also send back a json by returning a POJO (it'll be automatically serialized by the Jackson JSON lib) if that's what you want, or even a simple string as the html content by returning a String.
The purpose of ajax is to refresh a part of page. so re-directing to another page is meaningless, you could make the return type as String in your controller.
#RequestMapping(value = "/startApp", method = RequestMethod.POST)
#ResponseBody
public String start() {
// some operation
return "sucess"
}
Read my answer here Returning Hashmap From controller to JSP in Springmvc to know how to pass parameters in response

Spring MVC #ModelAttribute Not Binding Form

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.

AJAX Call not Getting to Spring MVC Controller

I'm trying to make a simple AJAX call in my Spring MVC project but am running into trouble. I am making my AJAX request by sending an String type argument and I'm wanting to get an ArrayList type back. I've read many tutorials at this point and can't figure out what's wrong with my AJAX/Controller configuration. I am using the ResponseBody annotation when trying to return my needed result back to the view. In this controller I am not returning an updated ModeAndView object, but this shouldn't matter since the page does not need to be refreshed because I'm using AJAX. Below is my AJAX call and controller code. I would really appreciate it if someone could give me a hint on what I'm doing wrong here.
function getdays() {
var monthSelected = $("#monthselect option:selected").text();
alert(monthSelected);
$.ajax({
url : '${pageContext.request.contextPath}/ajaxdays',
data: monthSelected,
success : function(data)
{
$('#daySelect').html(data);
alert(data);
}
});
}
Here is my controller class:
#Controller
#SessionAttributes
public class WorkstationController
{
#RequestMapping(value = "/ajaxdays", method = RequestMethod.GET)
public #ResponseBody
ArrayList<String> getTime(HttpServletRequest request)
{
ArrayList<String> retList = new ArrayList<>();
retList = this.getList();
return retList;
}
}
you have following errors
wrong url
change url : 'ajaxdays.html'to ${pageContext.request.contextPath}/ajaxdays
no parameter passed
you are not passing any data to server side so there is no need to write data: monthSelected
URL mentioned in ajax call should be the context path followed by the controller mapping. And '.html' should not be specified.
url: ${pageContext.request.contextPath}/ajaxdays

Categories

Resources