I am making SPA using AngularJS in Spring 4 with Hibernate 5.
I'm getting an error while passing JSON array from the AngularJS controller to the Spring Controller.
All fields value successfully coming in angular JSON array, but not passing in Spring controller.
Error: Could not read JSON: ; nested exception is
com.google.gson.JsonSyntaxException:
My project structure is like below.
Spring_Hibernate_MVC
=src
-com->karmesh->mvcApp->controller->register->RegisterController.java
=WebContent
-js->app->RegisterController.js
-Views->Register.html
Register,html
<div id="DivRegisterMain" ng-controller="RegisterController">
<form name="myForm" novalidate>
:::://Form fields here.
<input type="submit" value="SubmitTest" ng-click="submit()" ><br>
</form>
</div>
app.js
var routeApp=angular.module("RouteApp",['ngRoute']);
RegisterController.js
routeApp.controller("RegisterController", function($scope, $http) {
$scope.regJson = {
"is" : 1,
"fname" : "",
"lname" : "",
"gender" : "",
"dob" : "",
"email" : "",
"contact" : "",
"yop" : "",
"degree" : "",
"branch" : "",
"perc" : "",
"state" : "",
"city" : ""
};
$scope.studentList = [];
$scope.submit = function() {
var req = {
method: 'POST',
url: 'http://localhost:8050/Spring_Hibernate_MVC/registerStudent.do',
data: $scope.studentList,
};
$http(req).
then(function(response){
console.log(response); // prints true or false
if (response)
console.log("in success");
else
console.log("in fail");
$scope.studentList=[];
}, function(response){
console.log(response.status);
console.log("in error");
});
};
RegisterController.java
#EnableWebMvc
#RestController
#RequestMapping("/")
public class RegisterController {
#Autowired
private RegisterService registerService;
public RegisterController() {
System.out.println(this.getClass().getSimpleName() + "created..");
}
#ResponseBody
#RequestMapping(value="/registerStudent.do", method = RequestMethod.POST)
public boolean registerStudent(#RequestBody List<RegisterDTO> stdList) {
System.out.println("inside controller..");
if (stdList != null) {
System.out.println("success...");
}
return registerService.isStudentExist(stdList);
}
}
use JSON Serialization/Deserialization
your request should be
var req = {
method: 'POST', url:'http://localhost:8050/Spring_Hibernate_MVC/registerStudent.do',
data: JSON.stringify($scope.studentList),
};
your spring controller
#ResponseBody
#RequestMapping(value="/registerStudent.do", method = RequestMethod.POST)
public boolean registerStudent(#RequestBody string data) {
List<RegisterDTO> stdList = JsonConvert.DeserializeObject<RegisterDTO>(data); // find java jsondeserializer
System.out.println("inside controller..");
if (stdList != null) {
System.out.println("success...");
}
return registerService.isStudentExist(stdList);
}
You are missing contentType: 'application/json' in your request!
RegisterController.js
$scope.submit = function() {
var req = {
method: 'POST',
url: 'http://localhost:8050/Spring_Hibernate_MVC/registerStudent.do',
data: angular.toJson($scope.studentList),// note this
};
};
download gson jar file.
RegisterController.js
#ResponseBody
#RequestMapping(value = "/registerStudent.do", method = RequestMethod.POST)
public boolean registerStudent(#RequestBody String data) {
Gson googleJson = new Gson();
ArrayList stdList = googleJson.fromJson(data, ArrayList.class);
if (stdList != null) {
// store your stdList
}
return registerService.isStudentExist(stdList);
}
Related
Hi I need to pass the full model and one string from html to Spring controller using AJAX. I use the below code snippet but it doesn't work.
var str = $("#resourceManagement").serialize();
var agreementId = ${agreementId};
var tempCnltName=$modal.find("input[data-type='cnltName']").val();
$.ajax({
type:"POST",
data: {str, tempCnltName},
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline",
async: false,
dataType: "json",
success: function (data, status, xhr) {
message = data.errorMsg;
},
error: function () {
}
});
The problem is that if I pass model alone (str) or string alone (tempCnltName) I can get it in controller but I cannot get both together.
My controller is as below:
#RequestMapping(value = "/app/agreement/checkDuplicateConsultantOnline", method = RequestMethod.POST)
public #ResponseBody AjaxResponse checkDuplicateConsultantOnline(
#ModelAttribute("consultantBidModel") ConsultantBidModel model,
#RequestParam(value = "tempCnltName", required = false) String cnltName,
HttpServletRequest request,
HttpSession session) throws Exception {
final Set<String> allCnltNames = new HashSet<>();
String errMessage = "";
if (model.getLeadingCnltName() != null) {
allCnltNames.add(model.getLeadingCnltName().toLowerCase());
}
if (model.getJointVentureConsultants() != null) {
for (ConsultantBidListItem entry : model.getJointVentureConsultants()) {
if (!allCnltNames.add(entry.getCnltName().toLowerCase())) {
errMessage = "Each consultant can only appear once.";
}
}
}
if (model.getSubConsultants() != null) {
for (ConsultantBidListItem entry : model.getSubConsultants()) {
if (!allCnltNames.add(entry.getCnltName().toLowerCase())) {
errMessage = "Each consultant can only appear once.";
}
}
}
AjaxResponse response = new AjaxResponse();
if (errMessage != null) {
response.setSuccess(true);
response.setResponseObject(errMessage);
response.setErrorMsg(errMessage);
}
return response;
}
On the server side, you're already prepared to receive both the model (with #ModelAttribute) and an additional URL parameter (with #RequestParam)
On the client, append the URL parameter to the URL. Assuming that str is your model and tempCnltName is your string to submit to the server:
$.ajax({
type:"POST",
data: str,
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline?tempCnltName=" + tempCnltName,
...
try
var strVal = $("#resourceManagement").serialize();
var agreementId = ${agreementId};
var tempCnltNameVal=$modal.find("input[data-type='cnltName']").val();
$.ajax({
type:"POST",
data: {str: strVal, tempCnltName: tempCnltNameVal},
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline",
async: false,
dataType: "json",
success: function (data, status, xhr) {
message = data.errorMsg;
},
error: function () {
}
});
Probably the malformed json is causing trouble
Another way of doing the above, add the string to model:
var strVal = "consulName=" + tempCnltName + "&";strVal = strVal + $("#resourceManagement").serialize();
The model can then have a new parameter consulName and we can get the value in Controller.
I want to know how can I pass the parameters from JSP to the controller.
I am trying to send through ajax call but its going to error function
HTML:
<input type="submit" name="syncSubmit" value="synchronize" id="submitSync" >
JSP:
$("#submitSync").click(function() {
var campaignId = [];
var accountSe_Id = $ {
accountSe_Id
};
var accountId = $ {
accountId
};
$("#selectedCampaigns option").each(function() {
campaignId.push({
"campaignId": $(this).val()
});
});
$.ajax({
type: "POST",
url: "/partial-synch.json",
processData: true,
data: {
campaignId: JSON.stringify(campaignId),
accountSe_Id: accountSe_Id,
accountId: accountId
},
dataType: "json",
success: function(data) {
},
error: function(data) {
alert("fail");
}
});
return false;
});
Controller:
#RequestMapping(value = "/partial-synch.json", method = RequestMethod.POST)
#ResponseBody
public Object[] partialSync(
#RequestParam("campaignId") String campaignId,
#RequestParam("accountSe_Id") long accountSe_Id,
#RequestParam("accountId") long accountId) {
Object[] resposneBody = new Object[1];
}
I'm currently developing spring mvc application and I need to post JSON array.
When I access request.getParameter("paramValue") to fetch the param attibute, but it returning a null value,
Here is my front-end code:
$.ajax(url, {
async: true,
type: 'post',
contentType: 'application/json',
data: JSON.stringify({
"test":"test value"
})
}).done(function (response) {
console.log(data);
}).fail(function (xhr) {
console.log("request failed");
console.log(xhr);
});
Here is my server-side code:
#RequestMapping(value = "/Products", method = RequestMethod.POST)
public void saveProducts(HttpServletRequest req, HttpServletResponse res) throws Exception {
System.out.println(req.getContentType());
System.out.println(req.getContentLength());
System.out.println(req.getContextPath());
System.out.println(req.getParameterValues("test"));
System.out.println(req.getMethod());
StringBuilder buffer = new StringBuilder();
BufferedReader reader = req.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString();
System.out.println(data);
System.out.println(req.getParameter("test"));
}
The output is:
application/json
22
null
POST
{"test" : "Test DAta"}
null
I can't figure out whats going on, please help me.
remove this line in you ajax function
contentType: 'application/json',
and replace this line
data: JSON.stringify({
"test":"test value"
})
with
data: {
"test":"test value"
}
and also you can use
req.getParameter("test")
instead
req.getParameterValues("test")
You can by using this :
var data ={id: 1, name :'test'}
$.ajax(url, {
async: true,
type: 'post',
contentType: 'application/json',
data: data
}).done(function (response) {
console.log(data);
}).fail(function (xhr) {
console.log("request failed");
console.log(xhr);
});
and in server side
create a pojo :
public class Product{
private long id;
private String name;
// getters and setters
add library jackson .
add this method in your controller:
#RequestMapping(value = "/Products", method = RequestMethod.POST)
public RepsoneEntity<? >saveProducts(#requestBody Product pr){
LOG.debug(pr.toString());
return new reRepsoneEntity<Product>(pr,HttpStatus.ACCEPTED);
}
i finally fixed it several annotation and changing the the return type of server side method,
#RequestMapping(value = "/Products", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public ResponseEntity<?> saveProducts(#RequestParam(value = "data") String brand) {
return ResponseEntity.ok(brand);
}</code>
front end
$.ajax(url, {
async: true,
type: "POST",
data: {"data" : JSON.stringify({"Brand" : "Test Brand"})}
}).done(function (response) {
console.log(response);
}).fail(function (xhr) {
console.log("request failed");
console.log(xhr);
});
and i used org.json to access json objects parsed as text, gson to deal with POJOs
and now it works :)
I'm trying to call a POST request (using Jersey APi for REST) from an HTML form using AngularJS v 1.5.8.
I have an HTML form with a submit button that calls a REST serivce:
<body ng-app="myApp" ng-controller="loginController">
......
<form name="myForm" nonvalidate ng-submit="login()">
......
<div
class="col-md-4 col-md-offset-4 col-sm-4 col-sm-offset-3 col-xs-6 col-xs-offset-3">
<button type="submit" class="btn btn-default" ng-submit="login()">Submit</button>
</div>
</form>
This is my loginController script:
var app = angular.module ("myApp", []);
app.controller("loginController", function($scope, $http){
$scope.username = "";
$scope.password = "";
$scope.login = function() {
var transform = function(data) {
return $.param(data);
}
$http(
{
url : 'http://localhost:8080/RestServices/services/user/add',
method : 'POST',
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
},
transformRequest : function(data) {
return $.param(data);
},
data: { name: $scope.username,
password: $scope.password }
}).success(function(response, status) {
$scope.data = response; //Assign data received to $scope.data
}
)
}
}
)
And here is my simple REST post service:
#Path("user")
public class UserResource {
private TreeMap<Integer, User> userMap = new TreeMap<Integer, User>();
#POST
#Path("add")
#Consumes({MediaType.APPLICATION_JSON})
public Response addUser(User user) {
int id = userMap.size();
user.setId(id);
userMap.put(id, user);
ObjectMapper mapper = new ObjectMapper();
String jsonString = "";
try {
jsonString = mapper.writeValueAsString(user);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
jsonString = null;
}
return Response.ok().entity(jsonString).build();
}
}
The POST request is called but returns a 415 error: the server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
The problem is with the format that the REST API is expecting i.e. JSON.
So try with application/json and specifying charset won't be required:
headers: {
'Content-Type' : 'application/json'
}
function loginController($scope, $http) {
$scope.username = "";
$scope.password = "";
$scope.login = function () {
$http({
method: 'POST',
url: 'user/add',
data: {
username: $scope.username,
password: $scope.password
}
}).success(function (data, status, headers, config) {
$scope.result =data.username;
alert($scope.result);
}).error(function (data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
}
I am trying to pass string to controller use of Ajax Stringify but i got this error
415 (Unsupported Media Type)
My Ajax call:
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "addSample",
data: JSON.stringify(search), // Note it is important
cache : false,
beforeSend : function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success : function(response) {
console.log("Success: "+ response);
},
error : function(xhr) {
console.log("Sorry, there was a problem! " + xhr.responseText);
},
complete : function() {
console.log("Request complete");
}
});
Passing the String :
var search = {
" name" : "aa",
"sname": "bb",
"dname" : "cc"
}
My spring controller function:
#RequestMapping(headers={"Accept=application/json"},value = "addSample", method = RequestMethod.POST)
public #ResponseBody
String addData(HttpServletRequest request,#RequestBody final DemoDTO demoDTO)
{
return "{\"value\":\"true\"}";
}
My DTO:
public class DemoDTO implements Serializable{
private String name;
private String sname;
private String dname;
//getter setter
}
Please help me for solving this....
Try to replace this:
beforeSend : function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
With this:
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
Also, remove headers={"Accept=application/json"} from spring controller so it would be as follows:
#RequestMapping(value = "addSample", method = RequestMethod.POST)
public #ResponseBody
String addData(HttpServletRequest request,#RequestBody DemoDTO demoDTO)
{
return "{\"value\":\"true\"}";
}