I am trying to post a json using ajax to my spring mvc controller I am using code like this in my js file:
$('#regist').click(function () {
$.ajax({
url: 'user/regist',
contentType: "application/json; charset=utf-8",
type: 'post',
dataType: 'json',
success: function (data) {
var json = JSON.stringify(data);
alert(json);
},
fail: function (errMsg) {
alert(errMsg);
},
data: JSON.stringify({
'IDCard': '1234567890'
})
})
});
the signature of my controller function is like this:
#RequestMapping(value = "/regist", method = RequestMethod.POST)
#ResponseBody
public ResultJson regist(HttpSession session, #RequestBody RegistFormJson json)
the RegistFormJson goes like this:
public class RegistFormJson {
private String IDCard;
public String getIDCard() {
return IDCard;
}
public void setiDCard(String IDCard) {
this.IDCard = IDCard;
}
}
now when I send my request, and what I get from my controller using
logger.info(json.getIDCard);
is null.When I change my bean propertity to idCard and change my other code as well ,I can get the result successfully. Who can tell me why ? And If I want to use IDCard in my code, how can I get the result .Thanks
Spring comes with Jackson API which uses Standard Java Code Convention to map JSON properties to Java models.
Since IDCard is not in lower camel case, Jackson API is not able to map the JSON property.
To overcome this you need to specify a #JsonProperty("IDCard") annotation on a Java attribute in order to use IDCard for your JSON property.
Likewise, you can set the PropertyNamingStrategy on the ObjectMapper to overcome this issue.
Related
I am trying to fetch parameters from angular JS $http service to rest service using **#queryParam** . I need to fetch lot of parameters(below have shown for 3 as an example ,but I need to use around 12-15 of them which I need to pass to the java side) ,so fetching all with #QueryParam makes the code look pretty bad .I am using GET.
How can I optimize this ?
Example what I am doing -
Angular Js code -
$http({
url: someUrl,
method: "GET",
params: {filter1: $scope.filter1,
filter2:$scope.filter2,
filter3:$scope.filter3
});
Java side -
#path("/getAllData")
#GET
#Produces({..}
public response getAllData(#QueryParam("filter1") final String filter1,
#QueryParam("filter2") final String filter2,
#QueryParam("filter3") final String filter3){
}
Also ,wanted to know the optimization in case when I am building URL instead of params object, and picking the same with #PathParam
$http.get('rest/test/getAllData/?filter1='$scope.filter1 +
'&filter2='$scope.filter2 + '&filter3='$scope.filter3 +
'&filter4='$scope.filter4)
I am able to do it by passing individually in #QueryParam . I am looking for optimized code when we a large number of parameters.
Create a POJO with all the required parameters.
In angular, do this
var obj = {};
obj.filter1 = $scope.filter1;
obj.filter2 = $scope.filter2;
obj.filter3 = $scope.filter3;
$http({
url: someUrl,
method: "GET",
params: obj
});
You can accept all the parameters in you rest like this -
#path("/getAllData")
#GET
#Produces({..}
public response getAllData(MyPojo obj){
//String filter1 = obj.filter1;
}
You can do it in 2 ways:
1) org.json.simple.JSONObject.
2) Bean or POJO Class.
AngularJS Controller:
var URL = appURL+'/adm/addCollProcess.do';
var json = {"col_pro_id":$scope.col_pro_id, "col_code": $scope.col_code, "exam_type_ids": $scope.exam_types.toString().replace("[","").replace("]",""),
"created_by" : "admin", "file_path" : $scope.file_path, "website" : $scope.website, "facebook" : $scope.facebook};
// using JSONObject
$http.post(URL, json).then(function(response){
if(response.data){
// Code
}
});
// using Bean Class
$http.post(URL, JSON.stringify(json)).then(function(response){
if(response.data){
// Code
}
});
Java Controller:
// using JSONObject
#RequestMapping(value="/addCollProcess.do", method=RequestMethod.POST)
public boolean addCollProcess(#RequestBody JSONObject json){
// Code
}
// using Bean Class:
#RequestMapping(value="/addCollProcess.do", method=RequestMethod.POST)
public #ResponseBody boolean addCollProcess(#RequestBody AdmissionProcessBean processBean) {
// Code
}
What I am trying to do is initiate an ajax call from my frontend code by user interaction. This calls a Java Restful service that I have written. And this Java function calls another service.
I need that java service in the middle because I need to send the inputs to other service in the format of "MyModel".
The problem is, the AJAX call works but it cannot get the JSON object that I send. You see in the Java function below I create the "param1" : "asdasd" for the second time there. That's because it cannot get the JSON data from front-end. It should be dynamically created with the argument of sendInputs function.
By the way when I debug the value String input is like this: ""
Javascript AJAX call:
var paramData = {"param1" : "asdasd"};
$.ajax({
type : 'GET',
url : "/api/v2/proxy",
dataType : "json",
headers : {
"Service-End-Point" : "http://localhost:9000/service/myService/sendInputs"
},
statusCode : {
200 : function(data) {
}
},
contentType : "application/json",
data : JSON.stringify(paramData),
error : function(error) {
}
});
Java consume:
#GET
#Path("/sendInputs")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public String sendInputs(String input) {
String result = null;
//define the service endpoint to be added the default URL
String serviceEndpoint = "otherService/tool/runTool";
List<MyModel> modelParameterList = new ArrayList<MyModel>();
MyModel inputParameter = null;
inputParameter = new MyModel("param1", "asdasd");
modelParameterList.add(inputParameter);
//convert the Java Map to a json string using Jackson ObjectMapper
String jsonStringOfInputParameters = toJSON(modelParameterList);
WebClient client = WebClient
.create("http://localhost:9000");
result = client.path(serviceEndpoint)
.query("tool", "myTool")
.query("input", jsonStringOfInputParameters)
.accept("application/json")
//tells cxf to convert the json to a string type upon return
.get(String.class);
// Return the json result as a string
return result;
}
your paramData variable is already a valid json. I do not think you need yo use JSON.Stringify() again.And what is this is the ajax call:
statusCode : {
200 : function(data) {
}
}
Status code is supposed to be coming from the server in response.
First, your ajax header should be like this:
headers: {
Accept: "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
},
url:
url: "http://localhost:9000/service/myService/sendInputs"
Second, you need to have MyModel with param1 field and Also setters and getters. And this can be your service method:
public String sendInputs(MyModel model)
{
//model.getParam1() will be "asdasd"
}
I'm trying to understand principle of interaction between JSP (with JavaScript) and Java controller using JSON. For example, I have an entity
public class Greeting {
private final long id;
private final String content;
// other part omitted
}
And controller
#Controller
public class GreetingController {
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/")
public String redirect() {
return "redirect:/greeting";
}
#RequestMapping(value = "/greeting")
#ResponseBody
public Greeting greeting(#RequestParam("name") String name) {
return new Greeting(counter.incrementAndGet(), String.format("Hello, %s!", name));
}
}
How to modify this code to send GET request using JavaSctipt to controller and retrieve JSON answer by JavaScript on jsp page?
I would be appreciated for some examples :) or for some tutorial's links.
You can use jQuery to make a ajax get call to the controller. See https://api.jquery.com/jQuery.ajax/. You will have to specify the output type as JSON.
e.g.,
$.ajax({
type: 'GET',
url: '<Your URL>',
cache: false,
dataType: 'json',
// Your input parameters go here
data: {name: 'someValue'},
success: function(data, textStatus){
},
error: function(xhr, textStatus, errorThrown){
}
});
The below link explains how to return JSON object from controller:
http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/
I'm developing REST services which have to receive multiple info. In this case, two objects and an attribute.
This is the javascript where I'm testing the POST request
var user = {
username: "admin",
password: "admin"
};
var userToSubscribe = {
username: "newuser",
password: "newpassword",
email: "user#1and1.es"
};
var openid = "myopenid";
$.ajax({
url: '/myportal/rest/subscribeUser.json',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
data: JSON.stringify({ user: user, userToSubscribe: userToSubscribe, openid: openid})
});
The POST request:
JSON
openid
"myopenid"
user
Object { username="admin", password="admin"}
userToSubscribe
Object { username="newuser", password="newpassword", email="user#1and1.es"}
Source
{"user":{"username":"admin","password":"admin"},"userToSubscribe":{"username":"newuser","password":"newpassword","email":"user#1and1.es"},"openid":"myopenid"}
And the controller which handles the POST:
#RequestMapping(method=RequestMethod.POST, value="/subscribeUser.json")
public #ResponseBody Message subscribeUser(#RequestBody("user") User user, #RequestBody("userToSubscribe") User userToSubscribe, #RequestParam String openid){
...
}
And the error is
POST subscribeUser.json 400 Incorrect request localhost:8080 990 B [::1]:8080
What am i doing wrong?
Thank you
The request body will contain the entire JSON content. So when you want to map the JSON, you use only one RequestBody annotated-parameter. You will have to do something like this:
public #ResponseBody Message subscribeUser(#RequestBody String str)
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(str);
And then use the convertValue method of the mapper to get your different objects from the string.
JsonNode node = mapper.readTree(str);
User theUser = mapper.convertValue(node.get("user"), User.class);
Similarly for the other objects
You cannot use #ModelAttributes in a RESTful method that accepts JSON. I believe the proper method is to use #RequestBody, as done here. You will most likely need to wrap the objects in some wrapper class, but I could be wrong there as I have never personally tried to pass multiple JSON objects in one request before.
That said, I think it would be a good idea if you rethought your REST api, removing the JSON arguments and instead passing them in as part of the URI path, if possible. I would suggest reading through this blog post.
You can create a java bean(POJO) containing all the objects like..
class JavaBean{
private User user;
private UserTOSubscribe userToSubscribe;
private Long openId;
// getter and setter
}
and pass this bean in to the Web service. so web service looks like..
#RequestMapping(method=RequestMethod.POST, value="/subscribeUser.json")
public #ResponseBody Message subscribeUser(#RequestBody JavaBean javaBean) {
...
}
I am trying to send a List of JSON objects into a post request. I keep getting a 500 error here. I feel like i am not setting up my variable in the Method definiton to the right data type but im not sure what it should be set too.
AJAX Request:
function post_request(json_data) {
$j.ajax({
url : '../api/createDisplayGroup/postHtmlVar/' + containerID[1] + '/' + containerType[1],
data: JSON.stringify(json_data),
dataType: 'json',
type : 'post',
contentType : 'application/json'
}).done(function(response) {
run_update(response);
}).error(function(jQXHR, textStatus, errorThrown) {
alert('error getting request');
});
};
Java REST Service (POST only):
#POST
#Path("/postHtmlVar/{containerId}/{contentType}")
#Consumes(MediaType.APPLICATION_JSON)
public List<TabDefinition> postHtml(#PathParam("containerId") String containerId, #PathParam("contentType") String contentType, List<JSONObject> displayGroups) {
Long contId = Long.parseLong(containerId);
Long contType = Long.parseLong(contentType);
//return convertToResponse(peopleFilterService.getDisplayGroups(contId, contType));*/
return testDisplayGroup();
}
You need to take the input json string as a #FormDataParam. I don't think your JAVA REST framework can marshal the json to a list of JSONObject. You may have to create a class representing the json data and define your method like this:
public List<TabDefinition> postHtml(#PathParam("containerId") String containerId, #PathParam("contentType") String contentType, #FormDataParam MyJSonDataClass myJsonDataClassObj) {