I am fairly new to angularjs. Now I have a checkbox in one of my views
<input id="{{fields[3].name}}" type="checkbox" value="{{fields[3].name}}" ng-checked="selection.indexOf(fields[3].name) > -1" ng-click="toggleSelection(fields[3].name)" class="col-xs-1" />
In spring controller(like below) how do I check if the checkbox was checked?
#RequestMapping(value = "/test/{id}/accept", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
public #ResponseBody ResponseBean acceptData(
#PathVariable("id") String id,
#RequestBody AcceptPayload payload, Model model,
HttpServletRequest request, HttpServletResponse response) {
....
}
Any code examples will help
You will need to send the checked data from your webpage to the controller.
The web page will have ng-repeat as below. The variable list contains the json array:
<tr ng-repeat="obj in list">
<td>
<input id="{{obj.name}}" type="checkbox" value="{{obj.name}}"
checklist-model="checkboxes" ng-checked="selection.indexOf(obj.name) > -1"
ng-click="toggleSelection(obj.name)" />
</td>
</tr>
The toggleSelection() function will get the array of selected obj.name and add it to variable array **selectedItems **:
$scope.selectedItems = [];
$scope.toggleSelection = function toggleSelection(name) {
var idx = $scope.selectedItems.indexOf(name);
// is currently selected
if (idx > -1) {
$scope.selectedItems.splice(idx, 1);
}
// is newly selected
else {
$scope.selectedItems.push(name);
}
};
The way in which I would hit the controller in the webpage would be below:
$scope.execute = function() {
$http({
method : 'GET',
url : 'trigger',
params : {
selectedItems : $scope.selectedItems
}
}).success(
function(data, status, headers, config) {
}).error(
function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
The method in controller would look like:
#RequestMapping(value = "/trigger", method = RequestMethod.GET, headers = "Accept=application/json")
public #ResponseBody String trigger(#RequestParam("selectedItems") List<String> selectedItems) throws NumberFormatException, Exception {
// Your method
}
You can change the method from GET to POST as you would want it.
AngularJS is a front end MVC library. The spring controller is back-end. This means that the value has to be sent from the front to the back over an HTTP request.
For example, in HTML,
ng-checked="someVariable"
can be captured in the angular app controller within the scope with
$scope.someVariable
This value has then to be sent over network to your Spring controller through HTTP request. Something like,
$http({ method: 'POST', data: 'someVariable' url: '/someUrl'})
.then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Please refer to https://docs.angularjs.org/api/ng/service/$http
Related
I am attempting to send form data with Multipart data (Image) to Spring MVC controller. From my form. image field is non mandatory. so when i call spring controller without input image field, i get below error in browser console.
Failed to load resource: the server responded with a status of 400
(Bad Request)
Html Code:
<input file="file" type="file" id ="file2"/>
AngularjS Code:
$scope.saveData = function (formObj) {
$http({
url: CONTEXT_PATH+'saveFile',
method: "POST",
headers: { 'Content-Type': undefined },
transformRequest: function (data) {
alert(data.files);
var formData = new FormData();
formData.append("model", angular.toJson(data.model));
formData.append("file", data.files);
return formData;
},
data: { model: formObj, files: $scope.file }
}).then(function (response) {
//alert(response);
});
};
app.directive('file', function () {
return {
scope: {
file: '='
},
link: function (scope, el, attrs) {
el.bind('change', function (event) {
var file = event.target.files[0];
scope.file = file ? file : undefined;
scope.$apply();
});
}
};
});
Spring Controller Code:
#RequestMapping(value = "/saveFile")
public #ResponseBody String storeAd(#RequestParam ("model") String adString, #RequestParam ("file") MultipartFile file) throws IOException {
System.out.println("adString > "+adString);
return "OK";
}
When the image is not uploaded, the request is bad because Spring MVC assumes all parameters required unless otherwise defined.
In your case, you should add required = false.
#RequestParam(value = "file", required = false)
Your server code is expecting a request parameter with name "file" but you are not defining it properly.
Change
<input file="file"
To
<input type="file" name="file"
I am pretty new in Spring MVC and I have the following problem trying to handle an AJAX request that send an array of int to a controller method.
So I have the following situation. I have this JQuery function:
// It is global and it is initiazilized by another function:
var checkedRowList = new Array();
// SOME OTHER CODE THAT INIZIALIZED THE checkedRowList array here
...............................................
...............................................
...............................................
$('#validaButton').click(function() {
alert("validazione");
alert("CHECKED ROWS: " + checkedRowList.length);
alert(checkedRowList[0]);
$.ajax({
type: "POST",
data: {'checkedRowList' : checkedRowList},
url: "validaProgetti"
}).done(function(response) {
alert("SUCCESS");
}).error(function(xhr) {
alert("ERROR");
manageError(xhr);
});
});
So the checkedRowList is correctly initizialized (I checked it) and I use the ajax() function to send it toward the validaProgetti resource using a POST request.
Then into a controller class I have this method that have to handle the previous request:
#RequestMapping(value = "validaProgetti", method=RequestMethod.POST)
public String validaProgetti(#RequestParam List<Integer> checkedRowList, Model model, HttpServletRequest request) {
System.out.println("Numero progetti da validare: " + checkedRowList);
return "blablabla";
}
As you can see it handle HTTP Post request toward the validaProgetti resource. And Inside it I have specify the RequestParam List checkedRowList to retry the array passed by the AJAX request.
But it don't work because when the AJAX request is performed it don't enter into the validaProgetti() method and it shown the alert("SUCCESS"); popup.
Why? What am I missing? How can I fix this situation?
as I see you missed two things.
The first one is that in the Spring Web MVC controller. You don't pass a RequestParam but RequestBody.
#RequestMapping(value = "validaProgetti", method=RequestMethod.POST)
public #ResponseBody String validaProgetti(#RequestBody List<Integer> checkedRowList) {
System.out.println("Numero progetti da validare: " + checkedRowList);
return "blablabla";
}
The second one is related with your Ajax request. You should send javascript array formatted as JSON. This is done via the function JSON.stringify(), which converts js value into json.
$('#validaButton').click(function() {
alert("validazione");
alert("CHECKED ROWS: " + checkedRowList.length);
alert(checkedRowList[0]);
$.ajax({
type: "POST",
data: JSON.stringify(checkedRowList),
url: "validaProgetti",
contentType:"application/json"
}).done(function(response) {
alert("SUCCESS");
}).error(function(xhr) {
alert("ERROR");
manageError(xhr);
});
});
Also you may change the request mapping when defining in java code. Since it is a relative path, it would be confusing in some cases.
#RequestMapping(value = "/validaProgetti", method=RequestMethod.POST)
public #ResponseBody String validaProgetti(#RequestBody List<Integer> checkedRowList) {
System.out.println("Numero progetti da validare: " + checkedRowList);
return "blablabla";
}
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.
I have two dropdownlists in Jsp One for state and other for country. As soon as i select country the statelist should be populated automatically with respective lists. But i am getting whole jsp page as response in ajax call.
My ajax Program:
$("select#country").change(function() {
var val=$("#country").val();
alert(val);
$.ajax({
url : 'getstates',
method : 'get',
contentType: 'application/json',
data :{
country : val
},
success: function (data) {
alert("Success Response"+ data);
},
error :function()
{
alert("error");
}
});
My controller program
#RequestMapping(value = "/getstates", method = RequestMethod.GET)
public ModelAndView showstates(#RequestParam(required = false, value = "")
String country,#Valid #ModelAttribute("employee")Login employee,
BindingResult result, Model model) {
HashMap<String,String> stateMap = new HashMap<String,String>();
//put your logic to add state on basis of country
if (country.equals("UnitedStates")) {
stateMap.put("Al","Alaska");
stateMap.put("Tl","Texas");
} else if (country.equals("UnitedKingdom")) {
stateMap.put("Be","Bedfordshire");
stateMap.put("Ber","Berkshire");
} else if (country.equals("India")) {
stateMap.put("Mh","Maharashtra");
stateMap.put("WB","West Bengal");
stateMap.put("KR","Karnataka");
stateMap.put("AP","Andhra Pradesh");
stateMap.put("TN","Tamil Nadu");
}
return new ModelAndView("LoginForm","state" ,stateMap);
}
I am using spring form. I need to get only Staemap as respone but i am getting whole jsp page as response.
I need to get only Staemap as respone but i am getting whole jsp page
as response.
Because you are returning the ModelAndView object with the view here,
return new ModelAndView("LoginForm","state" ,stateMap);
If you need to return the respone alone from the controller method.However you cant print the HashMap directly in the ajax response on your jsp. IMHO you can convert it to JSONArray
JSONArray jarray = JSONArray.fromObject(statemap);
Read ,
send array from controller to a view using JSON in MVC
Sending JSON response from spring controller
loop through json array jquery
#RequestMapping(value="LoadBaselineVersions")
#ResponseBody
public Map<Integer,String> loadBaseNames(#RequestParam(value="projectname") String name,HttpSession session){
return basenameService.getBaselineversions(name);
}
$("#projectname").bind(
'blur',
function() {
$.ajax({
type : 'post',
url : 'LoadBaselineVersions?projectname='
+ $("#projectname").val(),
dataType : 'json',
success : function(data) {
$("#baseversion").empty();
$.each(data, function(val, text) {
$("#baseversion").append(
$('<option></option>').val(text).html(
text));
});
}
});
});
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);