Access absolute path of resource when using #RequestMapping in spring boot controller - spring

I am using #RquestMapping for mapping url to controller method.
#RestController
#RequestMapping(path = "/api/tasks")
public class TaskController { ....
and methods inside controller have /{id} with request mapping annotations.
#RequestMapping(
path = "/{taskId},
method = RequestMethod.GET
)
public Map<String, Object> methodOne(...
I want to access http method and absolute path (configured path) for that method inside.
i.e. I want to get /api/tasks/{taskId} as value (not the /api/tasks/1 if api is called for task id 1) and GET as method inside of the methodOne.
I checked the HandlerMapping but it returns actual path of resource called by client. Not the configured path for the method / resource.
Any help or guidance would be highly appreciated. Thank you.

String[] pathReqMappingAnnotationOnControllerClass = this.getClass().getAnnotation(RequestMapping.class).path();
Method method = TaskApiController.class.getMethod("getListOfTasks", HttpServletRequest.class, HttpServletResponse.class);
String[] pathReqMappingAnnotationOnControllerMethod = method.getAnnotation(RequestMapping.class).path();
String wholePath = pathReqMappingAnnotationOnControllerClass[0] + pathReqMappingAnnotationOnControllerMethod[0];
//pathReqMappingAnnotationOnControllerMethod will be empty array if method is not annotated for path

#RequestMapping(path = "/{id}", method = [RequestMethod.DELETE])
public void test(#PathVariable("id") String id, HttpServletRequest request) {
\\ Code Here
}
In the method parameter, id is the pathVariable. And request method is accessible in the request variable (Although I do not know what is the point as you are limiting it to only accept GET requests)

As suggested by #codedetector, best option is if you have request object or you can add one if you dont have it.
#RequestMapping(path = "/{taskId}, method = RequestMethod.GET)
public String methodOne(HttpServletRequest request){
String test = request.getRequestURI();
return test;
}
If you dont have request object in your method, with below code you can get any URL on your system.
import org.springframework.hateoas.mvc.ControllerLinkBuilder
...
ControllerLinkBuilder linkBuilder = ControllerLinkBuilder.linkTo(methodOn(YourController.class).getSomeEntityMethod(parameterId, parameterTwoId))
URI methodUri = linkBuilder.Uri()
String methodUrl = methodUri.getPath()
--------Edit
I am not sure why you need in this format "/api/tasks/{taskId}" as value (not the /api/tasks/1 )but i can think of using a constant use it for your #RequestMapping path parameter and then easily after getting absolute path , replace/append it with that constant.
String pathParam ="/{taskId}"

#RequestMapping(path = "/{id}", method = [RequestMethod.DELETE])
public void test(#PathVariable("id") String id, HttpServletRequest request) {
switch(id){
case 1:
method1();
break;
case 2:
method2();
break
....
....
}
}
private void method1(){};
private void method2(){};
private void method3(){};

Related

Error 400 when receiving data from URL parameters en Spring MVC

I am trying to receive data from an URL with two parameters like this one:
http://localhost:80000/xxx/xxx/tickets/search?codprovincia=28&municipio=110000
No matter the approach, I am always getting a 400 error, but if I access the URL without the two parameters, the controller returns the view correctly (without the parameters, naturally)
This is the code of my controller:
#Controller
#RequestMapping(value = "/xxx" )
public class BuscadorIncidenciasController extends BaseControllerWeb {
#RequestMapping("tickets")
public String tickets(Model model, #RequestParam ("codprovincia") String codprovincia, #RequestParam ("municipio") String municipio, HttpServletRequest request) throws NoAjaxException {
//...
return CONST.JSP_VIEW;
}
...}
Extra info: if I use this URL:
http://localhost:9081/xxx/xxx/tickets/search/28/790000
And this code:
#Controller
#RequestMapping(value = "/xxx" )
public class BuscadorIncidenciasController extends BaseControllerWeb {
#RequestMapping(value = "buscar/{codprovincia}/{municipio}", method = RequestMethod.GET)
public String buscar(#PathVariable Integer codprovincia, #PathVariable Integer municipio ,Model model, HttpServletRequest request) throws NoAjaxException {
//...
return CONST.JSP_VIEW;
}
...}
It gets the parameters correctly. The problem is that I have to use the first URL. I have reviewed similar questions about similar issues, and I have implemented the solutions to those issues, but I get the 400 error regardless what I try (add value="xxx=, required=false, and other suggestions.)
For RequestParam, you need to explicitly add 'name' attribute
#RequestParam(name = "codprovincia"), #RequestParam (name = "municipio")
No need to for HttpServletRequest, unless you have reason
Also, in your 'tickets' method, RequestMapping is not conforming to your URL path.
I think it should be
#RequestMapping("/xxx/tickets/search")
Cheers!

how to configure spring-data-rest search method path with #PathVariable

I want to customize my spring-data-rest search method path by passing parameter as a path variable like follows
http://localhost:8080/orders/search/customers/{customerId}
findByCustomer(#PathVariable("customerId") Integer customer);
The search resource listh the links as follows
http://localhost:8080/orders/search/customers/%7BcustomerId%7D
How to expose search url with path params?
You can use custom handler similar to this:
#RepositoryRestController
public class OrderController {
#Autowired
OrderRepository orderRepository;
#GetMapping("/orders/search/customers/{id}")
public #ResponseBody ResponseEntity<?> getByCustomers(#PathVariable Integer customer) {
Order order = orderRepository.findOne(id);
if(order == null) return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
Resource<Order> resource = new Resource<Order>(order);
return ResponseEntity.ok(resource);
}
}
More about this can be found here.
Use HttpServletRequest to get the request url:
findByCustomer(#PathVariable("customerId") Integer customer, HttpServletRequest request){
String request = request.getRequestURL().toString(); // StringBuffer, so use append if you want to...
[...]
}
also you can use request.getQueryString() to get the query part after ?.

DTO has only null with GET request params, but not POST #RequestBody

I'm trying to get my query params in a DTO like in this question but my DTO has always null value.
Is there anything wrong in my code ? I made it as simple as possible.
Queries:
GET http://localhost:8080/api/test?a=azaz => null
POST http://localhost:8080/api/test with {"a":"azaz"} => "azaz"
Controller with a GET and a POST:
#RestController
#RequestMapping(path = {"/api"}, produces = APPLICATION_JSON_VALUE)
public class MyController {
// GET: dto NOT populated from query params "?a=azaz"
#RequestMapping(method = GET, path = "test")
public #ResponseBody String test(TestDto testDto){
return testDto.toString(); // null
}
// POST: dto WELL populated from body json {"a"="azaz"}
#RequestMapping(method = POST, path = "test")
public #ResponseBody String postTest(#RequestBody TestDto testDto){
return testDto.toString(); // "azaz"
}
}
DTO:
public class TestDto {
public String a;
#Override
public String toString() {
return a;
}
}
Thanks !
Full Spring boot sample to illustrate it
The problem is that you are missing setter for the field.
public void setA(String a) {
this.a = a;
}
should fix it.
I'm assuming that you have done required configuration like having Jackson mapper in the class path, consume json attribute, getter and setter in DTO classes etc.
One thing missed here is, in RequestMapping use value attribute instead of path attribute as shown below
#RequestMapping(method = POST, value= "/test", consumes="application/json")
public #ResponseBody String postTest(#RequestBody TestDto testDto){
return testDto.toString();
}
And, make sure that you set content-type="application/json" while sending the request
I think what you are trying to do is not possible. To access the query Parameter you have to use #RequestParam("a"). Then you just get the String. To get your object this way you have to pass json as Parameter. a={"a":"azaz"}
Kind regards

Request parameters in spring

I need to take two parameters in my spring controller.
http://mydomain.com/myapp/getDetails?Id=13&subId=431
I have controller which will return Json for this request.
#RequestMapping(value = "/getDetails", method = RequestMethod.GET,params = "id,subId", produces="application/json")
#ResponseBody
public MyBean getsubIds(#RequestParam String id, #RequestParam String subId) {
return MyBean
}
I am getting 400 for when i tried to invoke the URL. Any thoughts on this?
I was able to get it with one parameter.
Try specifying which parameter in the query string should match the parameter in the method like so:
public MyBean getsubIds(#RequestParam("id") String id, #RequestParam("subId") String subId) {
If the code is being compiled without the parameter names, Spring can have trouble figuring out which is which.
As for me it works (by calling: http://www.example.com/getDetails?id=10&subId=15):
#RequestMapping(value = "/getDetails", method = RequestMethod.GET, produces="application/json")
#ResponseBody
public MyBean getsubIds(#RequestParam("id") String id, #RequestParam("subId") String subId) {
return new MyBean();
}
P.S. Assuming you have class MyBean.

Spring #PathVariable integration test

I'm trying ot write an integration test for one of my methods, that handles a form submission.
The problem is that i use #PathVariable int id in the #RequestMapping of my controller.
I get the following error message when my test method reaches the .handle() part.
nested exception is java.lang.IllegalStateException: Could not find #PathVariable [id] in #RequestMapping
So the controller cant reach the id. I'm using request.setRequestURI("/url-" + s.getId()); But appareantly its not helping with setting up #PathVariable.
Is there any way to set up the #PathVariable of my Mock object?
Update:
Yeah, im useing MockHttpServletRequest and annotationMethodHandlerAdapter.handle in my test class.
The Controller:
#RequestMapping(method = RequestMethod.POST, params = {"edit" })
public String onSubmit(#ModelAttribute("sceneryEditForm") SceneryEditForm s,
#PathVariable int id, Model model) {
// some code that useing id
}
The test method:
#Test
public void testEditButton() throws Exception {
MyObject s = new MyObject();
request.setMethod("POST");
request.setRequestURI("/edit-" + s.getId());
request.setParameter("edit", "set");
final ModelAndView mav = new AnnotationMethodHandlerAdapter()
.handle(request, response, controller);
assertViewName(mav, "redirect:/view-" + s.getId());
}
The error is correct: there is no path variable id
You need to add the path expression with an placeholder id
#RequestMapping(value = "/something/{id}",
method = RequestMethod.POST,
params = {"edit" })
public String onSubmit(#ModelAttribute("sceneryEditForm") SceneryEditForm s,
#PathVariable int id, Model model) {
// some code that useing id
}

Resources