Send value from Front To Back without changing java methods signature (springboot) - java

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) {

Related

Spring not catch all object of my rest petition

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) {
....
}

Spring - is it possible to give same url (path) in request mapping for two different post methods?

Is it possible to map same path (uri) in request mapping for two different post methods, only difference is request body.
Example
#RequestMapping(value = "/hello", method = RequestMethod.POST)
public String helloEmployee(#RequestBody Employee employee) {
return "Hello Employee";
}
#RequestMapping(value = "/hello", method = RequestMethod.POST)
public String helloStudent(#RequestBody Student student) {
return "Hello Student";
}
No, you can't give same url in request mapping of post method having different request body type but same media type. Below won't work:
#PostMapping(path = "/hello", consumes = MediaType.APPLICATION_JSON_VALUE)
public String hello(#RequestBody Pojo1 val) {
return "Hello";
}
#PostMapping(path = "/hello", consumes = MediaType.APPLICATION_JSON_VALUE)
public String hello(#RequestBody Pojo2 val) {
return "Hello";
}
If you have different media type, then it will. Below will work:
#PostMapping(path = "/hello", consumes = MediaType.APPLICATION_JSON_VALUE)
public String hello(#RequestBody Pojo val) {
return "Hello";
}
#PostMapping(path = "/hello", consumes = MediaType.TEXT_PLAIN_VALUE)
public String hello(#RequestBody String val) {
return "Hello";
}
Your RequestMapping should differ on at least one of the conditions; path,method,params,headers,consumes,produces
I needed the same url post mapping but it was giving me an error so I added different params and it worked for me
//url1 post mapping
#PostMapping(value = "/applicant/{step}", params = "validatedata")
//url2 post mapping
#PostMapping(value = "/applicant/{step}", params = "data")
if any of the below is different(as mentioned by the above answers)then you can have the same URL post mapping
path,method,params,headers,consumes,produces
In my case params was diffrent
Yes you can do that but you need to specify unique parameters signature in RequestMapping annotation:
public class MyController {
#RequestMapping(method = RequestMethod.POST, params = {"!name", "!name2"})
public String action(HttpServletRequest request, HttpServletResponse response){
// body
}
#RequestMapping(method = RequestMethod.POST, params = "name")
public String action(HttpServletRequest request, HttpServletResponse response,
#RequestParam(value = "name", required = true) String name) {
// body
}
}
`

Spring Boot passing JSON and simple attributes to the same mapping

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.

Java Client for HighChart Export server REST service

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);

Spring REST-ful uri with optional querystring

The normal uri which triggers the default controller to get all cars is just "/cars"
I want to be able to search for cars aswell with an uri, for example: "/cars?model=xyz" which would return a list of matching cars. All the request parameters should be optional.
The problem is that even with the querystring the default controller triggers anyway and I always get "all cars: ..."
Is there a way to do this with Spring without a separate search uri (like "/cars/search?..")?
code:
#Controller
#RequestMapping("/cars")
public class CarController {
#Autowired
private CarDao carDao;
#RequestMapping(method = RequestMethod.GET, value = "?")
public final #ResponseBody String find(
#RequestParam(value = "reg", required = false) String reg,
#RequestParam(value = "model", required = false) String model
)
{
Car searchForCar = new Car();
searchForCar.setModel(model);
searchForCar.setReg(reg);
return "found: " + carDao.findCar(searchForCar).toString();
}
#RequestMapping(method = RequestMethod.GET)
public final #ResponseBody String getAll() {
return "all cars: " + carDao.getAllCars().toString();
}
}
You can use
#RequestMapping(method = RequestMethod.GET, params = {/* string array of params required */})
public final #ResponseBody String find(#RequestParam(value = "reg") String reg, #RequestParam(value = "model") String model)
// logic
}
ie, the #RequestMapping annotation has a property called params. If all of the parameters that you specify are contained in your request (and all other RequestMapping requirements match), then that method will be called.
Try a variation of this:
#Controller
#RequestMapping("/cars")
public clas CarController
{
#RequestMapping(method = RequestMethod.get)
public final #ResponseBody String carsHandler(
final WebRequest webRequest)
{
String parameter = webRequest.getParameter("blammy");
if (parameter == null)
{
return getAll();
}
else
{
return findCar(webRequest);
}
}
}

Categories

Resources