How to post from AngularJS to SpringMVC - java

I have one post method in angularJS and I send post method to Spring MVC but Spring MVC doesn't return new ModelAndView.
AngularJS
**
var app = angular.module('userApp', []);
app.controller('userController', [ "$scope", "$http",
function($scope, $http) {
$scope.user = {};
$scope.addUser = function() {
var response = $http.post('resultA', $scope.user)
response.success(function(data, status, headers, config) {
$scope.message = data;
});
response.error(function(data, status, headers, config) {
alert("failure message: ");
});
alert("aa");
$scope.name = '';
$scope.employees = '';
$scope.headoffice = '';
};
} ]);
SPRING MVC
#RequestMapping(value = "/resultA", method = RequestMethod.POST)
public #ResponseBody ModelAndView submitFormA(#RequestBody User user) {
System.out.println(user.getUsername()+"");
return new ModelAndView("resultA");
}

Your code look fine. Please make sure that resultA view exist. Or if you want to return an String, change method return type to String.

Related

How to send Optional parameters from angular and catch them in Java Controller?

I'm trying to send "search" parameters to Spring Controller but keep getting the 400 bad request . I tried #RequestParam("personalNumber")String personalNumber but it still doesn't work, so now I'm trying to get the wrapper , can you suggest how to send wrapper info to Java controller ? (Wrapper has instances of other classes)
AngularJs
angular.extend($scope, {
obj:{
personalNumber:"",
firstName:"",
lastName:"",
dateFrom:"",
dateTo:""
},
loadCarLoan: urls.BASE_API + "user/getOnlineApplicationList",
carLoanList:[
],
});
$scope.getCarLoan = function () {
$(".loader").show();
console.log("In the angular");
$http.post($scope.loadCarLoan + $.param($scope.obj))
.success(function (response) {
console.log(response);
if(response.success){
$scope.carLoanList = response;
}
$(".loader").hide();
}).error(function () {
$(".loader").hide();
$scope.carLoanList = [];
})
};
$scope.filter = function () {
$scope.getCarLoan();
};
Java Controller :
#RequestMapping(value = "user/getOnlineApplicationList", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST)
public #ResponseBody String getOnlineApplicationList(HttpSession session,
#RequestBody OnlineApplicationListWrapper wrapper) {
System.out.println("In the Controller Java");
HashMap<String, Object> jsonMap = new HashMap<>();
Car car = wrapper.getCar();
Loan loan = wrapper.getLoan();
CustPaymentPlan cpp = wrapper.getCpp();
NaturalPerson np = wrapper.getPerson();
jsonMap.put("success", "true");
jsonMap.put("car", car);
jsonMap.put("loan", loan);
jsonMap.put("cpp", cpp);
jsonMap.put("np", np);
System.out.println(wrapper.getCar().toString());
System.out.println(wrapper.getLoan().toString());
System.out.println(wrapper.getCpp().toString());
System.out.println(wrapper.getPerson().toString());
System.out.println("========");
System.out.println(gson.toJson(jsonMap));
return gson.toJson(jsonMap);
}
You need to change:
#RequestParam("personalNumber") String personalNumber
To:
#RequestParam(value = "personalNumber", required = false) String personalNumber
The required = false indicates to spring that the parameter can be optional.
No need to create a wrapper

500 Internal Server Error when calling ajax in spring

I am using Spring MVC and I have an AJAX which is used to delete selected user. It's working fine on my local system but when I tried to run the same code on development server I'm getting
500 Internal Server Error
I did google to figure out what is wrong with my code but I'm not able to figure out anything till now. Any help will be appreciated.
AJAX function in my JSP file:
$('.del-btn .userId').click(function(){
var userId = $(this).attr("alt");
var data = 'userId='+ userId;
$.ajax({
type: 'POST',
url: '${pageContext.servletContext.contextPath}/deleteUser',
data: data,
success: function(response) {
$('#submitkpi').submit();
}
});
});
deleteUser function in Controller:
#RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
public #ResponseBody Map<String, ? extends Object> deleteKpi(#ModelAttribute(value = "userId") String userId, BindingResult result) {
if (!userId.isEmpty()) {
userService.deleteUser(userId);
return Collections.singletonMap("ok", true);
}
return Collections.singletonMap("errorMsg", "Unable to complete your request!");
}
Can you try this?!
$('.del-btn .userId').click(function(){
var userId = $(this).attr("alt");
$.ajax({
url: 'deleteUser',
data: ({
userId : userId,
}),
success: function(response) {
alert(response)
}
});
});
Controller
#RequestMapping("/deleteUser")
#ResponseBody
public String deleteKpi(#RequestParam(value = "userId") Long userId, HttpSession session) {
if (null != userId) {
userService.deleteUser(userId);
return "Ok";
}
return "NotOk";
}

Internal Server Error in returning arraylist from ajax call

I have a spring project and i am calling my controller from ajax call and i want to return arraylist of an object. In debug it shows proper contents in java code.But in js it gives error. Internal server error 500 .
Here is my controller
#RequestMapping(value = "/viewValidationFailures", method = RequestMethod.GET)
public #ResponseBody ArrayList<ErrorTable> viewValidationFailures(
HttpSession session, Principal principal) {
// System.out.println("parameter"+parameter);
ArrayList<ErrorTable> errorTables = null;
SystemUser systemUser = logincontrollerserviceint.getUserByUsername(principal.getName());
errorTables = validationErrorControllerInterface.getValidationErrorsByUser(systemUser);
return errorTables;
}
This is my angular js ajax call
var helloApp = angular.module("helloApp", []);
helloApp.controller("HttpController", [ '$scope', '$http',
function($scope, $http) {
debugger;
$http({
method : 'GET',
url : 'http://localhost:8080/sms/client/viewValidationFailures',
}).success(function(data, status, headers, config) {
debugger;
$scope.errors = data;
$scope.curPage = 0;
$scope.pageSize = 10;
$scope.numberOfPages = function() {
return Math.ceil($scope.errors.length / $scope.pageSize);
};
$('#LoadingImageDiv').hide();
}).error(function(data, status, headers, config) {
debugger;
$('#LoadingImageDiv').hide();
});
} ])
This is my ErrorTable class
#Column(name = "\"eSTId\"")
private String eSTId;
#Column(name = "\"errorCode\"")
private String errorCode;
#Column(name = "\"errorDescription\"")
private String errorDescription;
#Column(name = "\"timeDate\"")
private String time;
Everytime during ajax call it goes into the error function.
Can somebody suggest me what's wrong here.
I have checked all similar links like
Ajax call results in 500 Internal Server Error
Ajax call Gives internal server error
but nothing worked for me.

Return Json from Spring Controller After Uploading File via AngularJS

FrontEnd: jsp with AngularJS
BackEnd: Spring MVC/Java
I am uploading a file using ng-flow, angularJS. Source: https://github.com/flowjs/ng-flow
File upload is successful. I need to return a json from my Spring Controller. Any clues how to go about it?
P.S. can't find where to put in .success() function, if at all that is applicable.
Spring Controller:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String uploadFileHandler(#RequestParam("file") MultipartFile file, Model model) {
//Upload file and process
JsonObject jo = Json.createObjectBuilder().add(path, folderPath.toString())
.add(aContentsAttrib, aContents)
.add(bContentsAttrib, bContents).build();
}
app.js code:
(function() {
var app = angular.module('app', ['flow'])
.config(['flowFactoryProvider', function (flowFactoryProvider) {
flowFactoryProvider.defaults = {
target: 'upload',
permanentErrors: [404, 500, 501],
maxChunkRetries: 4,
chunkRetryInterval: 500,
simultaneousUploads: 4
};
flowFactoryProvider.on('catchAll', function (event) {
console.log('catchAll', arguments);
});
// Can be used with different implementations of Flow.js
// flowFactoryProvider.factory = fustyFlowFactory;
}]);
app.controller('PageController', function() {
//this.products = gems;
});
app.controller("TabController", function() {
this.tab = 1;
this.showOutput = false;
this.viewEvents = false;
this.isSet = function(checkTab) {
return this.tab === checkTab;
};
this.changeVal = function() {
this.viewEvents = true;
};
this.setTab = function(setTab) {
this.tab = setTab;
};
});
})();
What exactly should be returned from the spring controller? (String/#ResponseBody String etc)
How to collect that json in angular?
On your controller #ResponseBody should be added and the jo returned as String:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public #ResponseBody String uploadFileHandler(#RequestParam("file") MultipartFile file, Model model) {
//Upload file and process
JsonObject jo = Json.createObjectBuilder().add(path, folderPath.toString())
.add(aContentsAttrib, aContents)
.add(bContentsAttrib, bContents).build();
return jo.toString();
}
In AngularJS, you should do this for being able to post files and then retrieve the data back:
$http({url: '/url',
method: 'POST',
data: $scope.myFile,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success(data){
$scope.myData = data;
});
In your Spring controller you should just return an Object containing the properties you want to transfer to your angular service. This will be automatically (or by default) be converted to JSON. #RequestBody is not needed.
This return value will be available in the success callback, something like:
$http({
method: 'POST',
url: '...',
}).success(function (data) {
//data is your JSON response
})},
If you are using Spring 3 you can do this
#RequestMapping(value = "/getDealers", value = "/upload", method = RequestMethod.POST)
#ResponseBody
public String uploadFileHandler() {
}
#ResponseBody annotation directly writes the response to the response stream. You would not need a JSP. Just send the request for the controller from the browser & the controller method will write the response to the response stream.
You can parse the response using Jquery or any json library & display in the JSP
Check this out
An alternate way, which I just found out. Will be useful to extract from existing code, without any modification. It does introduce an extra global variable, outside your main angular app, and might not be highly recommended, but still, posting this.
var json = {};
var app = angular.module('app', ['flow'])
.config(['flowFactoryProvider', function (flowFactoryProvider) {
flowFactoryProvider.defaults = {
target: 'processxls',
permanentErrors: [404, 500, 501],
maxChunkRetries: 4,
chunkRetryInterval: 500,
simultaneousUploads: 4
};
flowFactoryProvider.on('catchAll', function (event) {
console.log('catchAll', arguments);
this.jsonResponse = arguments[2]; //Note this change
//json = this.jsonResponse;
console.log(this.jsonResponse);
json = angular.fromJson(this.jsonResponse);
});
// Can be used with different implementations of Flow.js
// flowFactoryProvider.factory = fustyFlowFactory;
}]);
'json' variable now has the json response received. You can use it for further use now.
P.S. in order to check for which value of 'i' arguments[i] gives you the json, see console.

how to call the spring controller method from form using java script or Jquery

Hai i tried calling the controller using
document.forms[0].value = "getSignFaces";
document.forms[0].submit();
But its not calling method in controller
#RequestMapping(value=signFaces.do, method=RequestMethod.POST , params ="getSignFaces")
public String getSignFaces(Model model,#ModelAttribute(HBMSWebConstants.MODEL_SIGN_DETAILS) HBMSSessionDataWO sessionData,
#ModelAttribute SignDetailsForm form,HttpServletRequest request,
HttpServletResponse response,#RequestParam String noOfFaces,
I need to send the noOfFaces to this method.
Some how it is failling. Please let me know if i am missing any thing
I think you can try using an ajax call to do the post to the controller.
as an example:
var jsonfile= {json:JSON.stringify(contents)};
$.ajax({
type:'POST',
url: "/yourcontrollermapping/signFaces.do
data: jsonfile,
dataType: "json"
});
and then your controller method:
#Controller
#RequestMapping("/yourcontrollermapping"
public class YourController(){
#RequestMapping(value = "/signFaces.do, method = RequestMethod.POST)
public void getSignFaces(#RequestParam("json) String json){
//stuff you want to do
}
}
If you wanne do it javascript native you can :
var jsonfile= {json:JSON.stringify(contents)};
var r = new XMLHttpRequest(); r.open("POST", "yourcontrollermapping/signFaces.do", true); r.onreadystatechange = function () { if (r.readyState != 4 || r.status != 200) return; console.log(r.responseText); }; r.send(jsonFile);

Categories