Spring AngularJS get request - java

I am trying to do pagination for my users list. I have an error "Bad request" when I try to use params in request. What can be the problem?
UserController.java
#RequestMapping(value = "/user/{page}",params ={"size"}, method = RequestMethod.GET)
public ResponseEntity<List<User>> getList(#PathVariable("page") int page, #RequestParam("size") int size) {
List usersList = userService.getList(page, size);
ResponseEntity<List<User>> respEntity = null;
if(usersList.isEmpty()){
respEntity =new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
return respEntity;
}
respEntity =new ResponseEntity<List<User>>(usersList, HttpStatus.OK);
return respEntity;
}
user_service.js
fetchAllUsers: function(page, size) {
return $http.get('http://localhost:8080/user/' + page, size)
.then(
function(response){
console.log(response.data);
console.table(response.data);
return response.data;
},
function(errResponse){
console.error('Error while fetching users');
return $q.reject(errResponse);
}
);
},

The documentation of $http.get says:
get(url, [config]);
[...]
config (optional) Object Optional configuration object
You're passing the size as second argument, instead of a config object. The correct code is
$http.get('http://localhost:8080/user/' + page, {
params: {
size: size
}
})...

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

How to convert ArrayList to Pageable object springboot

I was trying to return list as page object to my client side angular Application. But it return all the list not a page.
this is my server side controller method which return the list
#GetMapping("/users/departmentAdminPageUsers")
#Timed
public ResponseEntity<List<DepartmentAdminPageUserDTO>> getDepartmentAdminPageUsers(#ApiParam Pageable pageable, #ApiParam String searchKey, #ApiParam String depId)
throws URISyntaxException {
List<DepartmentAdminPageUserDTO> userList=userService.getAllDepartmentAdminPageUsers(depId,searchKey);
final Page<DepartmentAdminPageUserDTO> page = new PageImpl<>(userList, pageable,userList.size());
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/users/departmentAdminPageUsers");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
this is my client side angular method which send request
getAllUsersByDepId(req?: any):Observable<Response>{
let params: URLSearchParams = new URLSearchParams();
if (req) {
params.set('page', req.page);
params.set('size', req.size);
params.set('searchKey', req.searchKey);
params.set('depId', req.depId);
}
let options = {
search: params
};
return this.http.get(this.resourceUrl+ '/departmentAdminPageUsers', options);
}
I need to return page instead the whole list.
you are returning the whole list as the page content, try:
List<DepartmentAdminPageUserDTO> userSubList = userList.subList((pageable.getPage()-1)*pageable.getSize(), (pageable.getPage()*pageable.getSize())-1);
final Page<DepartmentAdminPageUserDTO> page = new PageImpl<>(userSubList, pageable,userList.size());
protected Page<T> listToPage(Pageable pageable, List<T> entities) {
int lowerBound = pageable.getPageNumber() * pageable.getPageSize();
int upperBound = Math.min(lowerBound + pageable.getPageSize() - 1, entities.size());
List<T> subList = entities.subList(lowerBound, upperBound);
return new PageImpl<T>(subList, pageable, subList.size());
};

Data is passed within ""(doublequotes) from angularJs to SpringMVC Controller

I am passing data from controller.js to service.js to SpringController.java
but weird thing is happening when i pass $scope.credentials.uname data to Java Controller .
The data passed is coming in doublequotes . When i print the value in Java
its getting printed as "USER" instead of USER.
Also due to this i am not able to save the username in database.
$scope.submitUsername = function()
{
$log.info("username "+$scope.credentials.uname);
Here log is getting printed properly chrome console
username SYS_USER --> without double quotes
loginService.fetchUserType(angular.copy($scope.credentials.uname)).then(function(data)
{
if (data.loginType == 'NotValidUsername')
{
$log.info("Failure")
toaster.pop('information', "Warning", 'Enter Valid UserName');
}
else
{
$log.info("Success")
if (data.loginType == 'database')
{
$scope.isExternalUser = true;
$scope.showSubmitButton = false;
}
else
{
$scope.isExternalUser = false;
$scope.showSubmitButton = false;
}
}
})
};
service.js
fetchUserType : function(userName)
{
var promise = $http({
url : "checkUserType.do",
method : "POST",
data : JSON.stringify(userName)
}).success(function(data, status, header, config, statusText)
{
}).error(function(data, status, header, config, statusText)
{
if(!status === 901)
toaster.pop('error', status, statusText);
}).then(function(response)
{
return response.data;
})
return promise;
}
Java Controller method
#RequestMapping(value = "/checkUserType.do", method = { RequestMethod.GET, RequestMethod.POST })
#ResponseBody
public Object checkUserType(#RequestBody String username,HttpServletRequest request)
{
log.info(" Inside checkUserType "+username);
User user = new User();
user.setUserName(username);
String userType = loginService.checkUserType(user.getUserName());
user.setLoginType(userType);
return user;
}
Output on console is
Inside checkUserType "SYS_USER".
How should i pass data so that i can avoid these ""(doublequotes) being passed to Java Controller
Remove JSON.stringify(userName) from your service.js This is whats adding the double quotes around your request.
Instead your data should just be data: userName. When it gets send to your controller it will be correctly converted to json for your controller to digest.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

How to post from AngularJS to SpringMVC

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.

Error 405 Method Not Allowed error, when sending DELETE to server

I get following response when I try to delete: 405 Method Not Allowed.
In my logs there is written that GET is allowed, but DELETE isn't.
Java:
#ResponseBody
#RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
public void delete(#PathVariable String id) {
speakerService.delete(id);
}
Angularjs
app.factory('SpeakerResource', function ($resource) {
return $resource('rest/speaker/:speakerId',
{
speakerId: '#speakerId'
},
{
'update': { method: 'PUT' }
},
{
'delete': { method: 'DELETE', params: { 'id': 'speakerId' }}
}
)
});
SpeakerService
this.delete = function (id, callback) {
SpeakerResource.delete({ speakerId: id }, function () {
callback();
});
}
I do not know your complete code, and I am not an expert in AngularJS, but it looks like your want to send a DELETE request to the URL <hopefullySomething>/{id} (Path variable). But it looks like that you send a DELETE request so some URL with an parameter id <hopefullySomething>?id={id} (Request parameter).
This question and answers explain the difference between path variable and request parameters a bit more #RequestParam vs #PathVariable
use $http.delete(), and return data for example status, I just tested the following with spring and working correctly
#RequestMapping(value = "delete/{id}", method = RequestMethod.DELETE)
public #ResponseBody Status deletePerson(#PathVariable("id") int id) {
try {
personService.removePerson(id);
return new Status(1, "person deleted Successfully !");
} catch (Exception e) {
return new Status(0, e.toString());
}
}
angular
angular.module('personService', [])
.factory('Person', ['$http',function($http) {
return {
deletePerson: function(id) {
return $http.delete('/restperson/delete/'+id);
}
}
}]);
controller
angular.module('personController', [])
// inject the person service factory into our controller
.controller('mainController', ['$scope','$http','Person', function($scope, $http, Person) {
//delete
$scope.deletePerson = function(id) {
Person.deletePerson(id)
.success(function(data) {
$scope.message = data;
});
};
}]);

Categories