I'm trying to make a form that will post a CardRequestResource:
public class CardRequestResource extends ResourceSupport{
private Long cardRequestId;
private String deliveryMethod;
private String address;
private boolean isHomeDelivery;
private String requestDate;
private String expectedDate;
private String comments;
private Long statusId;
private PersonResource person;
//Getters and Setters
}
In my controller, I first load the JSP and add an empty CardRequestResource to the ModelMap:
#RequestMapping(value = { "", "/approval" }, method = RequestMethod.GET)
public String getApproval(ModelMap map) {
map.put("cardRequestResource", new CardRequestResource());
return "cardoffice/approval";
}
My JSP builds the form with the cardRequestResource model attribute:
<form:form id="detailForm" name="detailForm" modelAttribute="cardRequestResource">
<form:input path="statusId" type="hidden" id="statusId" name="statusId" />
<form:textarea path="comments" name="comments" id="commentTextarea" rows="7" cols="81" style="font-style: normal;"/>
</form:form>
A Javascript function makes an AJAX call to populate the form values:
function getCardRequestDetails(cardRequestUrl) {
$.ajax({
type : "GET",
url : cardRequestUrl,
dataType : "json",
success : function(response) {
loadCardRequestDetails(response);
},
error : function(response) {}
});
};
function loadCardRequestDetails(cardRequest) {
$("#statusId").attr("value", cardRequest.statusId);
$("#commentTextarea").val(cardRequest.comments);
}
At this point a user may update the comment text area, and the hidden input may change conditionally on what the user enters in the field. Then when the form is submitted, I call the following Javascript function:
function postCardRequest(url) {
var serialized = $("#detailForm").serialize();
alert(serialized);
$.ajax({
type: "POST",
url: url,
data: serialized,
contentType: "application/json",
dataType: "json"
});
}
The alert shows that the fields are populated correctly with the data that was either originally loaded by AJAX/Javascript, or by the user. However when I get to the handler in my controller that processes the post, the CardRequestResource is non-null, but EVERY SINGLE field in it is NULL!
Handler code:
#RequestMapping(value = "/approval/submit", method = RequestMethod.POST)
public #ResponseBody Map<String, Object> postCardRequest(#ModelAttribute(value = "cardRequestResource") CardRequestResource cardRequestResource) {
Map<String, Object> responseMap = new HashMap<String, Object>();
final String success = "success";
Boolean isSuccessful = Boolean.FALSE;
if(cardRequestResource != null){
isSuccessful = Boolean.TRUE;
}
//TODO
System.out.println("Status: " + cardRequestResource.getStatusId() + ", Comments: " + cardRequestResource.getComments());
responseMap.put(success, isSuccessful);
return responseMap;
}
So I think I found the perp!
This lil' guy right here in the POST AJAX call:
contentType: "application/json",
I was originally sending JSON to my controller, then I learned that Spring MVC had that nifty ModelAttribute annotation, so I wouldn't have to worry about converting to/from JSON during my POST. Unfortunately, I didn't think to remove that contentType line, and one would think that it would throw an error or something with it still in there... apparently not. Just NULL values in the binding and hours of fruitless debugging...
After I removed that line, I started getting data in the CardRequest attributes instead of NULLs!
Try to put the following code in the aplication-context.xml. This could be the solution if you are having your form encType='multipart/form-data'.
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10000000"/>
</bean>
Related
I'm trying to send an array of
this Json data
data using this Ajax in a JSP:
$.ajax({
url: 'agregarSeleccion',
type: 'POST',
dataType:'json',
data: JSON.stringify(lista),
success:function(dataP){
//Successs
error: function (jqXhr) {
swal("Error","","error");
}
});
To this controller in Java (Spring framework):
private List<Seleccion> seleccionados = new ArrayList<Seleccion>();
#RequestMapping("/agregarSeleccion")
#ResponseBody
public List<Seleccion> agregar(Seleccion obj) {
seleccionados.add(obj);
return seleccionados;
}
The "Seleccion" object it's an entity that has some of the attributes of the JSON that I sent from Ajax, the "seleccionados" is a list that saves the array received, but when I send it, the obj param always return a null object and Ajax sends the error function, I think the problem is that I'm sending an array to an Object, but I can't figure how to solve it
Seleccion object model:
public class Seleccion {
private int idProducto;
private String nombre;
private double precio;
private int cantidad;
private double totalParcial;
//Getters and setters
}
Try using ResponseEntity and update you controller like the below snippet;
Test Data
[
{
idProducto : 1,
nombre : 'Test1',
precio : 1.5,
cantidad : 1,
totalParcial : 2.5
}
]
Your Ajax (I changed datatype back to json);
$.ajax({
url: 'agregarSeleccion',
type: 'POST',
contentType: "application/json",
data: JSON.stringify(lista),
success:function(dataP){
console.log(dataP);
},
error: function (jqXhr) {
swal("Error","","error");
}
});
Your Controller (Notice a variable is declared outside method as well , added allAll method to add list , Changed return type at the end)
List<Seleccion> seleccionados;
#RequestMapping("/agregarSeleccion")
public ResponseEntity<?> agregar(#Valid #RequestBody List<Seleccion> obj) {
seleccionados = new ArrayList<Seleccion>();
System.out.println("result"+ obj.toString());
seleccionados.addAll(obj);
return new ResponseEntity<>(seleccionados, HttpStatus.OK);
}
I have Spring 4 MVC web app, I would like to do a GET call with Ajax that returns a list of simple object. Suppose that the object is something like this:
class Categories {
String name;
}
and calls is like this:
function getCategories() {
$.ajax({
type: "GET",
url: "categoryFilter.html",
dataType: "json",
success: function (result) {
alert(result);
},
error: function (result) {
alert("error");
}
});
}
Than I would like to display this object inside a Spring form like this:
<form:form method="post" action="searchShop.html" modelAttribute="Categories">
<c:forEach var="cat" items="${result}">
<span><form:input path="nome" value="${cat.name}" /></span>
</c:forEach>
</form:form>
I googling around and I see that I can append the result into a div or something similar but I can do something like that?
Thanks for your reply. My controller is:
#RequestMapping("/categoryFilter")
public Response showCategory() {
List<Categoria> categoryList = categoryService.getAllCategories();
Response response = new Response("Done", categoryList);
return response;
}
and the Object response:
public class Response {
private String status;
private Object data;
....
}
I have tried many different ways, with #GetMapping and so on.. but I always received 404 bad request.
Thanks a lot
Yes yes my question was how convert the pojo automatically with jackson library but after Spring 3 I needs a lot of bean configuration and than I modify my controller as follows:
#ResponseBody
#RequestMapping("/categoryFilter")
public String showCategory() {
List<Categoria> catList = categoryService.getAllCategories();
JSONArray json = new JSONArray(catList);
return json.toString();
}
Your code:
var resObjs= JSON.stringify(result);
var cats= JSON.parse(resObjs);
$("#category-form").append('<form:form method="post" action="searchShop.html" modelAttribute="Categoria">');
$.each(JSON.parse(cats), function(i, obj) {
$("#category-form").append('<form:input path="nome" value="'+obj.nome+'" />' + obj.nome); // this line
});
$("#category-form").append('<input type="submit" value="Submit"/>');
$("#category-form").append('</form:form>');
Please take a look to the line inside the $.each, that line visualiza an input type with value the string +obj.name+ follows by the effective value of variable (the name of category).. why I can't put dinamically value right there?? I'm going mad..
Thank you
yes you can append the json values to a div, this is what i did for populating selection dropdown with json data, something similar can be done for forms as well.
success: function (responseJson) {
var responseObjects= JSON.stringify(responseJson);
var categories= JSON.parse(responseObjects);
$('#divid').empty();
$('#divid').append($('<option value="0">').text("Select Variant"));
$.each(categories, function(i, obj) { $("#divid").append(('<option>
</option>').val(obj.id).html(obj.value));});
}
I am using spring mvc. I need to pass a json object from my jsp page to controller.
My ajax code:
function createJSON() {
jsonObj = [];
item = {};
$(".values").each(function() {
var code = $(this).attr('id');
item[code] = $('#' + code).val();
});
var content=JSON.stringify(item)
$.ajax({
type: 'POST',
contentType : 'application/json; charset=utf-8',
url: "/pms/season/submit",
data: content,
dataType: "json",
success : function(data) {
alert(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
}
My controller code:
#RequestMapping(value = "/submit", method = RequestMethod.POST)
public void saveNewUsers( #RequestParam ("json") String json) {
System.out.println( "json ::::"+json );
}
But it's not working.
#RequestParam("json") means that you are intending to include a request parameter called json in the URI, i.e. /submit?json=...
I think you intend to get the request body, i.e. #RequestBody.
I would then suggest that, unless you really need the raw JSON string, you would have the #RequestBody translated to a Java object for you:
public void saveNewUsers(#RequestBody MyDto myDto) {
...
}
where MyDto would have getters/setters and fields matching the JSON class.
You can over omit the #RequestBody annotation if you annotate the controller with #RestController, instead of #Controller.
If you definitely want the raw JSON string, then take a look at this previous question: Return literal JSON strings in spring mvc #ResponseBody
How many ways are to pass JSON data to a spring controller?
I followed this tutorial and they pass the data using the following syntax:
data: "{\"name\":\"hmkcode\",\"id\":2}",
This works but since I need to retrieve the data from a user using a text input I don't know how to put my variable in that string.
I tried doing using the following syntax:
data: "{\"name\":\name\}"
But it returns the following error:
status: parsererror er:SyntaxError: Unexpected tokken a
I have seen other sites that uses the following syntax:
data: {"name":name}
But that gives me the same error.
This works but I don't know if is the best approach.
var json = {"name" : name};
...
data: JSON.stringify(json),
I manage to pass the JSON string to one of my controllers but I get the string like this:
{"name": Joe, "lastname": Smith}
Is there a way to only get that info in a Person Object or at least get only Joe in a string and Smith in another one?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type="text/javascript">
function doAjaxPost()
{
// get the form values
var name = $('#name').val();
var lastname = $('#lastname').val();
var json = {"name" : name, "lastname" : lastname};
//console.log(json);
$.ajax(
{
type: "POST",
url: "formShow",
data: JSON.stringify(json),
//data: "{\"name\":name}",
//data: {"name":name},
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
beforeSend: function(xhr)
{
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data)
{
//console.log(data);
console.log(data.name);
//var data = $.parseJSON(JSON.stringify(response));
//alert(data);
alert( "name: "+data.name);
//$('#name').val('');
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
/* error: function (xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}*/
});
}
</script>
<fieldset>
<legend>Name in view</legend>
Name in view: <input type="text" id="name" name="name">
<br>
Last Name in view: <input type="text" id="lastname" name="lastname">
<br>
Show modify name in view: <input type="text" id="modifyname" name=""modifyname"">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</fieldset>
<br>
And these are my controllers:
#RequestMapping(value = "formShow", method = RequestMethod.GET)
public String formularioIncidencia (Model model) {
return "formShow";
}
#RequestMapping(value = "formShow", method = RequestMethod.POST)
public #ResponseBody String getTags(#RequestBody String name)
{
String variableAjax= name;
System.out.println("controller variable is " + variableAjax);
//that prints me this "{name: Joe, lastname: Smith}"
return variableAjax;
}
EDITED****
this is my User class
public class Userimplements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String lastname;
public User(){}
}
I edited my controllers to the following
#RequestMapping(value = "formShow", method = RequestMethod.GET)
public String formShow(Model model) {
return "formShow";
}
#RequestMapping(value = "formShow", method = RequestMethod.POST)
public #ResponseBody User getTags(#RequestBody final User user, Model model)
{
//what should i do here parse my user to JSON how??
user.setName("name changed");
model.("modifyname", user.getName() );
return User;
}
From Ajax you can also pass data as data:'name='+ name+'&lastname='+ lastname,
And at controller end you can make use of #RequestParam annotation to get this value passed from ajax call.
Ajax code looks as follows:
$.ajax({
type: 'POST',
url:'your controller url',
data:'name='+ name+'&lastname='+ lastname,
success: function(msg){
alert('wow' + msg);
}
});
Controller code:
#RequestMapping(value = "formShow", method = RequestMethod.POST)
public String getTags(#RequestParam("name") String name, RequestParam("lastname") String lastname)
{
System.out.println("name: " + name+ " lastname: "+lastname);
String fullName = name + lastname;
return fullName;
}
Hope this helped you.
Cheers:)
For sending the input data to controller, you don't have to necessarily use json as a format. You can simply pass them as request param and extract it on controller using #RequestParam annotation. If you want to post json data you can use JSON.stringify(json). if you to bind object to your model object, try using #Modelattribute on controller and pass the data in your ajax post. There are plenty of examples for this.
Use #RequestParam or #RequestBody to get your data on your controller based on what approach you choose based on point 1.
Use #ResponseBody to send the data back and if you send json data back, use Json.parseJson to convert to js object or if you send a Map, you would get a JS object back in your ajax handler. You can use Dot notation to populate the data.
A few observations will be enlighten ( i hope ).
In JAVA: it is always better to specify your "request" object and your response object like this:
#RequestMapping(method = RequestMethod.POST, value = "/rest/path/to/action",
consumes = "application/json", produces = "application/json")
#ResponseStatus(value = HttpStatus.OK)
public #ResponseBody
List<?> action(#RequestBody List<?> requestParam) {
List<String> myret = new ArrayList<String>();
for (int i=0; i < requestParam.size() ;i++){
myret.add(requestParam.get(i).toString());
}
}
In this case i defined the same object "List" as my request and my response object, but that it's up to your definitions. If you want to represent a user object, you must define your user object and specify the fields u want with Jackson lib. It is a little tricky, but once you got it, you can pass any object you want.
And then you can just pass your data in AJAX as defined in your controller. So in this case would be:
var postData = ["Somedata", "Someotherdata"];
$.ajax(
{
type: "POST",
url: "/rest/path/to/action",
data: postData, // i can do this, because it is defined this way in my controller
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
//etc etc
I hope it helps :)
Cheers
using AJAX and spring MVC , How to return List of objects from Spring Controller and using Jquery display them .
making Ajax request below:
$.ajax({
type: "POST",
url: "allUser.html",
dataType:'json',
data: "select=" + selectedCheckboxArray,
success: function(data){
var userListContent="";
var json =data.message;
$.each(json, function(i, obj) {
userListContent=userListContent+"<tr>";
userListContent=userListContent+"<td><input type='checkbox' value='"+obj.id+"' id='select' name='select'/></td> ";
userListContent=userListContent+"<td id='NameColumn'>"+obj.firstName+" "+obj.lastName +"</td>";
userListContent=userListContent+"<td id='genderColumn'>"+ obj.gender +"</td>";
userListContent=userListContent+"<td id='userNameColumn'>"+ obj.userName +" </td>";
userListContent=userListContent+"<td id='userTypeColumn'> "+ obj.userType +"</td>";
userListContent=userListContent+"<td id='statusColumn'>"+ obj.status +"</td>";
userListContent=userListContent+"<td id='emailIdColumn'>"+ obj.emailId +"</td>";
userListContent=userListContent+"<td id='addressColumn'>"+ obj.address +"</td>";
userListContent=userListContent+"<td id='contactnoColumn'>"+ obj.contactNo +"</td>";
userListContent=userListContent+"</tr>";
});
$('#rounded-corner tbody').html(userListContent);
//console.log(userListContent);
},
error: function(e){
alert('Error: ' + e.responseText);
}
});
MVC Contrller
#RequestMapping(value="/deleteUser",method= RequestMethod.POST)
public #ResponseBody Map<String, Object> deleteUser(UserDetails user,HttpServletRequest request,HttpServletResponse response )throws ServletException,IOException
{
System.out.println("Ajax Request Received for delete User...............");
Map<String, Object> model = new HashMap<String, Object>();
JsonResponse js=new JsonResponse();
js.setResult("pass");
js.setStatus("active");
// String operation=request.getParameter("operation");
String[] selectedUserIdParameter = request.getParameterValues("select");
System.out.println("Length:"+selectedUserIdParameter.length);
/* Code Description:
* Array "selectedUserIdParameter" above has ID like {1,2,3,.....},
* we need to use array like {1 2 3 4 } without (,).so first we must convert.
* Following code doing the same.
* After Conversion Array "selectedUserId" will have ID like {1 2 3 4 }
* If You Know PHP explode()" function ,following is doing something like what explode() function does .
*/
String msg="hello";
List<UserDetails> usersList = userService.getAllUser();
int no=usersList.size();
System.out.println("Size:"+no);
model.put("message", usersList);
model.put("jso", js);
return model;
}
You are going to accept and return objects in the form of JSON, so add the jackson mapper bean in spring dispatcher servlet xml. Jackson mapper does it all. You don't need to do mapping or conversion manually.
<beans:bean id="jacksonMessageChanger" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<beans:property name="supportedMediaTypes" value="application/json" />
</beans:bean>
<beans:bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<beans:property name="messageConverters">
<util:list id="beanList">
<beans:ref bean="jacksonMessageChanger" />
</util:list>
</beans:property>
</beans:bean>
Now your controller would be like this :
#RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
public #ResponseBody
List<UserDetails> deleteUser(#RequestBody UserDetails userDetails) {
// fetch the userid to be deleted from the userDetails
// remebmer the id of user to be deleted will be set in the ajax call
userService.deleteUser(userDetails.getUserId());
// again populate the user list to display on page
List<UserDetails> userList = userService.getAllUser();
return userList;
}
Now you ajax call will be something like this :
function deleteUser() {
// set variables into javascript object which you need to send to spring controller
// the variable name here should be same as it is in your java class UserDetails.java
var user = new Object();
user.userId = 120; // id of user to be deleted
$.ajax({
type : 'POST',
url : '/${your project context path here}/deleteUser',
dataType : 'json',
data : JSON.stringify(user),
contentType : 'application/json',
success : function(data) {
//here in data variable, you will get list of all users sent from
// spring controller in json format, currently its object
// iterate it and show users on page
showUsers(data);
},
error : function() {
alert('error');
}
});
}
function showUsers(data) {
// and here you show users on page
//following code just example
$('#allUsers').append("<option value='-1'>Select User</option>");
for ( var i = 0, len = data.length; i < len; ++i) {
var user = data[i];
$('#allUsers').append("<option value=\"" + user.userId + "\">" + user.userName+ "</option>");
}
}
This will work.
Returning the ArrayList directly should work...
#RequestMapping(value="/deleteUser",method= RequestMethod.POST)
public #ResponseBody ArrayList<UserDetails> deleteUser(UserDetails user,HttpServletRequest request,HttpServletResponse response )throws ServletException,IOException
{
System.out.println("Ajax Request Received for delete User...............");
// String operation=request.getParameter("operation");
String[] selectedUserIdParameter = request.getParameterValues("select");
System.out.println("Length:"+selectedUserIdParameter.length);
/* Code Description:
* Array "selectedUserIdParameter" above has ID like {1,2,3,.....},
* we need to use array like {1 2 3 4 } without (,).so first we must convert.
* Following code doing the same.
* After Conversion Array "selectedUserId" will have ID like {1 2 3 4 }
* If You Know PHP explode()" function ,following is doing something like what explode() function does .
*/
String msg="hello";
List<UserDetails> usersList = userService.getAllUser();
int no=usersList.size();
System.out.println("Size:"+no);
return usersList;
}
This might be too late now, but just to show you how to call an action through spring by using jQuery Ajax I provide here whatever I had done in my project : (Ajax call For user validation)
Ajax function to be written in *.js file :
function validateUserBeforeCreatingUser(email){
var url='validateUser.htm?'&email='+email;
$.ajax({
url: url,
cache: false,
success: function(response){
$("#errors").html(jQuery.trim(response));
//if errors not present
if(jQuery.trim(response)==''){
createUser();
}
},
error: function(response){
}
});
}
And this is the action I wrote in controller : (I had created errors.jsp page for rendering errors)
public ModelAndView validateUser(HttpServletRequest request,
HttpServletResponse response) throws Exception {
/* write code to validate user,
if user with specified email not found
then create error
else
keep errors page blank
*/
return new ModelAndView("partial", "errors", errors);
}
Hope this provides you the answer and sorry for indentation, I can't do t properly :-(