Send list with ajax to my Spring Controller - java

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
}

Related

Asynchronous AJAX return after page loads

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

How can I set response type in runtime (Spring MVC)

I'm developing a Spring MVC application where I need to validate a form. My problem is next: I want to change the processing of returning data from my method in depending on some logic.
For example, I have a registration user page! If the user fields are valid I need to send a message to ajax on the registration page. But if they aren't valid I need to return the view name (or do redirect). How can I do it? Here is my code:
#RequestMapping(value = "save_user", method = RequestMethod.POST)
public String saveUser(#Valid User user, BindingResult result) {
if(result.hasErrors()) {
return "common/add_user"; // Here I need to return the view name or do redirect
} else {
userManager.add(user);
return "success... bla bla bla"; // Here I need to return some message.
}
}
I think you can do like:
#RequestMapping(value = "save_user", method = RequestMethod.POST)
#ResponseBody
public String saveUser(#Valid User user, BindingResult result) {
if(result.hasErrors()) {
return "common/add_user"; // Here I need to return the view name or do redirect
} else {
userManager.add(user);
return "success... bla bla bla"; // Here I need to return some message.
}
}
in your ajax, you can get the response data
$.ajax({
type: "POST",
url: "save_user",
data: $("#user").serialize(),
success: function(data) {
//get response data and process it
...
}
});
Hope this help!

How to pass JSON object from ajax to controller in spring mvc?

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

java spring boot HTTP POST request not working

For my application I am writing a POST request to send array of parameters from a checkbox list. Its working for get request but not working for post request. What is the error in my code.
My code on the client side for sending ajax request to the server.
$(".add").click(function(){
monitoring.length=0;
nonMonitoring.length=0;
$('.modal-body input:checked').each(function() {
monitoring.push($(this).val());
});
$('.addkeywords input:checked').each(function() {
nonMonitoring.push($(this).val());
});
// alert(monitoring[2]+ " " + nonMonitoring[2]);
var monitoringLength=monitoring.length;
var nonMonitoringLength=nonMonitoring.length;
$.ajax({
type : "POST",
url : '/rest/channelstats/my/rest/controller',
data : {
// monitoring : monitoring,
// nonMonitoring: nonMonitoring,
monitoringLength: monitoringLength,
nonMonitoringLength: nonMonitoringLength,
},
success : function(data) {
// var keywordsList=data
//console.log(keywordsList);
// htm = "" ;
}
});
})
My java code on the server side.
#RequestMapping(value="/rest/channelstats/my/rest/controller",method = RequestMethod.POST)
public void monitorKeywords(#RequestParam(value="monitoringLength",required=true)int monitoringLength,#RequestParam(value="nonMonitoringLength",required=true)int nonMonitoringLength){
System.out.println("MonitoringLength =>" +monitoringLength);
System.out.println("NonMonitoringLength=>" +nonMonitoringLength);
}
}
Its working for HTTP GET requests but not working for POST requests.How should I solve this problem?
According to your jquery post request, you should use DAO(Data Access Object) to parse the request data. So you should add class Request
public class Request {
private int monitoringLength;
private int nonMonitoringLength;
//getters and setters
}
And change controller to
#RequestMapping(value="/rest/channelstats/my/rest/controller",method = RequestMethod.POST)
public void monitorKeywords(#RequestBody Request request){
System.out.println("MonitoringLength =>"+request.getMonitoringLength());
System.out.println("NonMonitoringLength=>"+request.getNonMonitoringLength());
}

Spring MVC Controller never called from ajax Post

I have the page about.ftl which is invoked when I type localhost:8080/ui/about
and I have put the following block of code inside. Through SendToServlet() function I am trying to send the user info to my controller which is the OAuthController.java
function SendToServlet(){
$.ajax({
url: "localhost:8080/ui/about",
type: "POST",
data: JSON.stringify({ user:jsonObj}),
contentType: 'application/json',
success: function(result) {
alert(done);
},
error: function(xhRequest, ErrorText, thrownError) {
alert(JSON.stringify(jsonObj));
}
});
}
</script>
My Spring MVC Controller class code has the following implementation - all that it does is that it accepts the user's information and then sets up current user:
#Controller
#RequestMapping("/about")
public class OAuthController {
#RequestMapping(method = RequestMethod.POST)
#ResponseBody
public String post( #RequestBody String items, HttpServletRequest request, HttpServletResponse response)
{
String jsonResp = items;//sb.toString();
ArrayList<String> usercredentials = new ArrayList<String>();
usercredentials = parseJson(jsonResp);
UserMethods usermethods = new UserMethods();
usermethods.setCurrentUser (usercredentials);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
return "{\"success\":\"\"}";
}
public ArrayList<String> parseJson(String json){
}
}
My problem is that the controller is never invoked and actually I never see a Post request to be sent anywhere through Firebug. I've spent several days on it, but still no luck. Do you have any suggestions?
You need to bind value with your function. Your url localhost:8080/ui/about/post is just used to locate the controller but it will not execute any function because you didn't make a call to any function.
To call the function, you have to do like this :
#RequestMapping(method = RequestMethod.POST, value ="/anyValue")
public String anyFunctionName(anyParam){...}
Above function will bind to url localhost:8080/ui/about/anyValue.
Don't you need to call it like this?
url: "localhost:8080/ui/about/post",
but first do this:
#RequestMapping(method = RequestMethod.POST, value = "/post")
How about try to add .html?Application won't add it automatically.

Categories

Resources