I'm new in Spring Boot and I want to have the same Request Mapping method for JSON and simple request params, for example:
#RequestMapping(value = "/start")
public String startPostProcess(#RequestParam(value = "url",
required = false,
defaultValue = "https://goo.gl") String url,
#RequestParam(value = "word",
required = false,
defaultValue = "Search") String word,
#RequestBody String hereGoesJSON) {
//Do some stuff
}
So, when request goes with params, only #RequestParam will work, in other cases we will use #RequestBody annotation.
localhost:8080/start?url=htts://google.com&word=Luck
Or may bee I'll be able to write method like this, for accepting any params:
#RequestMapping(value = "/start")
public String startPostProcess(#RequestBody String anyParam) {
//Parse this anyParam
}
?
I've not found this trick in spring documentation, so I will appreciate any links to it.
Okay, I've solved the problem :D
All that I just needed was 2 methods with the same mapping and explicitly specify RequestMethod type:
#RequestMapping(value = "/start")
public String startPostProcess(#RequestParam(value = "url",
required = false,
defaultValue = "https://goo.gl") String url,
#RequestParam(value = "word",
required = false,
defaultValue = "Search") String word) throws InterruptedException {
//Do some stuff
}
#RequestMapping(value = "/start", method = RequestMethod.POST, consumes = "application/json")
public String startJsonProcess(#RequestBody String body) {
//Do another stuff with RequestBody
}
UPD: added "consumes = "application/json". It helps dividing simple POST requests and JSON POST requests.
Related
I need to send a value from an Angularjs front to a springboot Java back-office.
The back is called by many other fronts and services.
Which means I can change The front but I have to make sure that any change on the back must not break it for the other callers.
So Extra headers or Other fields in the request body etc... any change that won't break the other existing calls is what I'm looking for.
An example of some methods signature:
A HTTP GET signature
#Override
#ResponseStatus(code = HttpStatus.OK)
#RequestMapping(value = "/", method = RequestMethod.GET)
public ResponseEntity<List<Something>> getSomething(
#RequestHeader(name = Constants.HEADER.SOME_CODE) final String code,
#RequestHeader(name = Constants.HEADER.COMPANY_ID) final String companyId,
#RequestHeader(name = Constants.HEADER.CLIENT_ID) final String clientId) {
A HTTP POST signature
#Override
#ResponseStatus(code = HttpStatus.OK)
#RequestMapping(value = "/{pathValue}/transactions", method = RequestMethod.POST)
public ResponseEntity<SomeResponse> requestSomething(
#RequestHeader(name = Constants.HEADER.EFS_CODE) final String vode,
#RequestHeader(name = Constants.HEADER.COMPANY_ID) final String companyId,
#RequestHeader(name = "Access-Code", required = false) final String codeAcces,
#RequestHeader(name = Constants.HEADER.CLIENT_ID) final String clientId,
#PathVariable("pathValue") final String pathValue,
#RequestBody #Valid Transact transaction) {
I want to send an object of arraylist(in java) and other parameters as passed by the user to postman.
Here is my Code for controller
#PostMapping(path = "/listEmpPaidSalariesPaged", produces = "application/json")
public List<EmployeeSalaryPayment> listEmpPaidSalariesPaged
(long SID, Collection<Student> student, String orderBy,
int limit, int offset)
I know you can use RAW data and JSON for object
and x-www-form-urlencoded for parameters, but how to send them together?
You can use #RequestBody and #RequestParam annotations, like for example:
#PostMapping(path = "/listEmpPaidSalariesPaged", produces = "application/json")
public List<EmployeeSalaryPayment> listEmpPaidSalariesPaged(#RequestBody StudentRequestModel studentRequestModel, #RequestParam(value = "orderBy", defaultValue = "descending") String orderBy, #RequestParam(value = "limit", defaultValue = "25") int limit, #RequestParam(value = "offset", defaultValue = "0") int offset) {
// controller code
}
#RequestBody will automatically deserialize the HttpRequest body (raw JSON from postman) into a java object (StudentRequestModel).
#RequestParam will extract your query parameters (in postman you can do a POST to /listEmpPaidSalariesPaged?orderBy=ascending for example) into the defined variables.
You can do both at the same time of course in postman.
My method is this:
#RequestMapping(value = "/asignar", method = RequestMethod.GET, headers = "Accept=application/json")
public #ResponseBody
ResponseViewEntity<ResultadoJSON> asignar(
#RequestParam(required = true, value = "usuario") String usuario,
#RequestParam(required = true, value = "clienteId") Long clienteId,
ListaLotes lotes) {
....
}
Object ListaLotes
public class ListaLotes {
private List<LoteForm> lotes;
}
Object LoteForm
public class LoteForm {
private Long loteId;
private Long cantidad;
}
But when i realize the petition throught PostMan, the object "lotes" its always null
PETITION REST
Rest Header
Rest body
What I should do for it works ? I can't modify my Java code its part of an API. Only can modify de REST Petition
As has already been commented, if you want to transfer data to your controller, you need to use the POST method and mark the paramter as #RequestBody.
// or #PostMapping
#RequestMapping(value = "/asignar", method = RequestMethod.POST, headers = "Accept=application/json")
public #ResponseBody
ResponseViewEntity<ResultadoJSON> asignar(
#RequestParam(required = true, value = "usuario") String usuario,
#RequestParam(required = true, value = "clienteId") Long clienteId,
#RequestBody ListaLotes lotes) {
....
}
I have been trying to create a small java client to call Highchart Export server to get the pdf/jpeg etc.. but it is not successful using Spring's RestTemplate -> RestTemplate restTemplate = new org.springframework.web.client.RestTemplate() in the client side. I tried post/get/exchange methods.. but unable to PASS the required method parameters to the server side... the required method is getting called without the params and returnd their test jsp page.
Highchart Export Server code =>
#Controller
#RequestMapping("/")
public class ExportController extends HttpServlet {
...
...
#RequestMapping(method = {RequestMethod.POST, RequestMethod.GET})
public HttpEntity<byte[]> exporter(
#RequestParam(value = "svg", required = false) String svg,
#RequestParam(value = "type", required = false) String type,
#RequestParam(value = "filename", required = false) String filename,
#RequestParam(value = "width", required = false) String width,
#RequestParam(value = "scale", required = false) String scale,
#RequestParam(value = "options", required = false) String options,
#RequestParam(value = "globaloptions", required = false) String globalOptions,
#RequestParam(value = "constr", required = false) String constructor,
#RequestParam(value = "callback", required = false) String callback,
#RequestParam(value = "callbackHC", required = false) String callbackHC,
#RequestParam(value = "async", required = false, defaultValue = "false") Boolean async,
#RequestParam(value = "jsonp", required = false, defaultValue = "false") Boolean jsonp,
HttpServletRequest request,
HttpSession session) throws ServletException, InterruptedException, SVGConverterException, NoSuchElementException, PoolException, TimeoutException, IOException, ZeroRequestParameterException {
...
}
}
What method in RestTemplate should I call and how to pass the params from client side like JSON formatted options, type etc, so that above Service method gets executed with proper params? Your help is appreciated.
I made it work after passing values in org.springframework.util.LinkedMultiValueMap object like
MultiValueMap<String, String> prms = new LinkedMultiValueMap<String, String>();
prms.add("param1", "value1");
prms.add("param2", "value2");
and then calling..
RestTemplate restTemplate = new RestTemplate();
byte[] b = restTemplate.postForObject("http://****/", prms, byte[].class);
I try to make an AJAX query to my controller in Spring MVC.
My action code is:
#RequestMapping(value = "events/add", method = RequestMethod.POST)
public void addEvent(#RequestParam(value = "start_date") String start_date, #RequestParam(value = "end_date") String end_date, #RequestParam(value = "text") String text, #RequestParam(value = "userId") String userId){
//some code
}
My Ajax query is:
$.ajax({
type: "POST",
url:url,
contentType: "application/json",
data: {
start_date: scheduler.getEvent(id).start_date,
end_date: scheduler.getEvent(id).end_date,
text: scheduler.getEvent(id).text,
userId: userId
},
success:function(result){
//here some code
}
});
But I got an error:
Required String parameter ''start_date is not present
Why?
As I know I presented it like (#RequestParam(value = "start_date") String start_date
UDP
Now I give 404
My class to take data
public class EventData {
public String end_date;
public String start_date;
public String text;
public String userId;
//Getters and setters
}
My js AJAX call is:
$.ajax({
type: "POST",
url:url,
contentType: "application/json",
// data: eventData,
processData: false,
data: JSON.stringify({
"start_date": scheduler.getEventStartDate(id),
"end_date": scheduler.getEventEndDate(id),
"text": scheduler.getEventText(id),
"userId": "1"
}),
And controller action:
#RequestMapping(value = "events/add", method = RequestMethod.POST)
public void addEvent(#RequestBody EventData eventData){
}
And JSON data is:
end_date: "2013-10-03T20:05:00.000Z"
start_date: "2013-10-03T20:00:00.000Z"
text: "gfsgsdgs"
userId: "1"
On the server side you expect your request parameters as query strings but on client side you send a json object. To bind a json you will need to create a single class holding all your parameters and use the #RequestBody annotation instead of #RequestParam.
#RequestMapping(value = "events/add", method = RequestMethod.POST)
public void addEvent(#RequestBody CommandBean commandBean){
//some code
}
Here is a more detailed explanation.
I had the same issue.. I solved it by specifying the config params in the post request:
var config = {
transformRequest : angular.identity,
headers: { "Content-Type": undefined }
}
$http.post('/getAllData', inputData, *config*).success(function(data,status) {
$scope.loader.loading = false;
})
config was the parameter I included and it started working..
Hope it helps :)
Spring Boot Code
#RequestMapping(value = "events/add", method = RequestMethod.POST)
public void addEvent(#RequestParam(value = "start_date") String start_date, #RequestParam(value = "end_date") String end_date, #RequestParam(value = "text") String text, #RequestParam(value = "userId") String userId){
//some code
}
Postman Request Link to be send: Add the parameters and value using Parmas in postman and see the below request link.
http://localhost:8080/events/add?start_date=*someValue*&end_date=*someValue*&text=*someValue*&userId=*someValue*