using Spring MVC and ajax to handle list of objects - java

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 :-(

Related

Form binding back with List of multiple select options

I'am trying to bind model in spring form multiple select using Select2 jquery library
but selected options are always null,
first i display form correctly with the available options, then user can update (add or remove) other choice which i fetch them remotely with an ajax request.
i am using next dto to bind form data :
DTO :
#Setter
#Getter
public class MyDto{
private List<Contact> agences;
private Contact banque;
spring mvc form to display avaliable user option :
...
<form:select path="agences" items="${MyDto.agences}" itemValue="id" itemLabel="name" />
...
select2 initialization to format and fetch additional options with an ajax request
Select 2 :
$("#agences").select2({
language: "fr",
multiple: true,
width: '100%',
ajax: {
url: "/fetchData.html",
method: "POST",
dataType: 'json',
delay: 250,
data: function (params) {
return {
query: params.term,
banque : $("#IdBanque").val()
};
},
processResults: function (data, params) {
return {
results: $.map(data, function (item) {
return {
"id" : item.id,
"text" : item.name,
}
})
};
}
}
});
Controllor
#RequestMapping(method = RequestMethod.POST, value = "/update")
#ResponseBody
public ResponseEntity<?> updateIntranet(#ModelAttribute(value = "myDto") myDto, BindingResult result, HttpServletRequest zRequest) throws JSONException {
....
the problem is when i receive the request i can't find selected options and the List is null
how i can binding back the dto which include list of element using spring mvc

Spring MVC #ModelAttribute is not getting populated with AJAX Post request [duplicate]

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>

How display Java Object by ajax calls

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));});
}

Fill in Bootstrap table after Ajax request (JSP and Spring MVC)

Hi I try to fill in my tables in my JSP view after having send a variable into an Ajax function.
<script type="text/javascript">
function filterByDate() {
var count = 680;
$.ajax({
url : 'filterOnDate',
data : {
"count" : count
}, //here you send the daterange over an Ajax request and by default it's sended with a GET method
success : function(data) {
//alert(data); //here you will see an alert displaying the callback result coming from your spring controller
console.log("Request succeeded!");
console.log(data);
},
error : function(xhr, ajaxOptions, thrownError) {
if (xhr.status == 404) {
alert(thrownError);
}
}
});
}
</script>
This Ajax request is send to a UserController who receive this variable and send it to the Model for performing an Hibernate search criteria in database.
#RequestMapping(value = "/eblinb2b/filterOnDate", method = RequestMethod.GET)
public #ResponseBody List<EblInvB2B> filterByDate(Model model, #RequestParam("count") int count) {
// Fetch data from the DAO
List<EblInvB2B> eblinb2b_filter_counting = accountSservice.findByDateRangeEB2B(count);
// We add to the model (JSP page the list of EBLINVB2B)
model.addAttribute("eblinb2b_filter_counting", eblinb2b_filter_counting);
return eblinb2b_filter_counting;
}
I already checked if the hibernate query retrieve the information from the COLUMN table after I put a Debug breakpoint i see my List with objects.
This is the DAO method with Hibernate criteria:
#SuppressWarnings("unchecked")
#Override
public List<EblInvB2B> findDateRange(int count) {
Criteria criteria = createEntityCriteria();
criteria.add(Restrictions.eq("count", count));
return (List<EblInvB2B>) criteria.list();
}
What i'd like to do is to fill my table with a response to my Ajax only with the rows where i applied the criteria which is count that comes from my Ajax request it is equal to 680 it is an integer and should fill in my jsp table with only one row.
Just for information: I have a Different JSP view where I have and Update Button for populating mySql database it is in fact a batch that unmarshall XML files and put them into database. This is the usercontroller method :
#RequestMapping(value = "/eblinb2b/OutInCompare", method = RequestMethod.GET)
public String eblinb2bOutInCompare(Model model) {
// Fetch data from the DAO
List<EblInvB2B> eblinb2b_list = accountSservice.findAllEblInvB2B();
// We add to the model (JSP page the list of EBLINVB2B)
model.addAttribute("eblinb2b_list", eblinb2b_list);
return "eblinb2bCompare";
}
Here i want to display in my view the list passed by my Controller method onto my JSP view. I don't know if it is correct? : BOOTSTRAP PAGE
https://jsfiddle.net/eaL38ejr/
Thanks to all for your help!
You should've load the bootstrap table again after getting data from ajax.
<script type="text/javascript">
function filterByDate() {
var count = 680;
$.ajax({
url : 'filterOnDate',
type: 'GET',
dataType:'json',
data : {
"count" : count
}, //here you send the daterange over an Ajax request and by default it's sended with a GET method
success : function(data) {
//alert(data); //here you will see an alert displaying the callback result coming from your spring controller
console.log("Request succeeded!");
console.log(data);
$('#tableID').bootstrapTable('load', data);
},
error : function(xhr, ajaxOptions, thrownError) {
if (xhr.status == 404) {
alert(thrownError);
}
}
});
}
</script>
Or do a refresh,
$('#tableID').bootstrapTable('refresh', {
url: 'filterOnDate?count='+count
});
Edit
Ajax 406 indicates your request is not acceptable, hence you need to update your controller method like below.
#RequestMapping(value = "/eblinb2b/OutInCompare", method = RequestMethod.GET,
headers="Accept=*/*",produces = "application/json")
public #ResponseBody List<EblInvB2B> filterByDate(Model model, #RequestParam("count") int count) {
// Fetch data from the DAO
List<EblInvB2B> eblinb2b_filter_counting = accountSservice.findByDateRangeEB2B(count);
// We add to the model (JSP page the list of EBLINVB2B)
model.addAttribute("eblinb2b_filter_counting", eblinb2b_filter_counting);
return eblinb2b_filter_counting;
}
As well include type and dataType parameter's in your ajax request. Let me know if it helps.

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.

Categories

Resources