Cannot handle request by requestMapping - java

I need to handle requests like
www.example.com/student/thisisname?age=23&country=UK&city=London
I am just interested in thisisname part and value of city parameter.
I have following RequestMapping but it does not work. I tried {name}{.*:city} as well.
#RequestMapping(value = "/{name:.*}{city}", method = RequestMethod.GET)

You can do it by 2 ways. Either using #RequestParam or #PathVariable
By Using #RequestParam
#RequestMapping(value = "/name", method = RequestMethod.GET)
public void someMethod(#RequestParam String city){}
By using #PathVariable
#RequestMapping(value = "/name/{city}", method = RequestMethod.GET)
public void someMethod(#PathVariable String city){}
You can use any of this method just you need to concentrate on URL

You can handle it using PathVariable and RequestParam annotation. In below code name is thisisname part and city is query param city value.
#RequestMapping(value = "/student/{name}", method = RequestMethod.GET)
public void someMethod(#PathVariable String name, #RequestParam("city") String city){
}

Related

Using a String variable in RequestMapping value

I have the following:
#Value("${apiVersion")
private String apiVersion;
#RequestMapping(value = "/{apiVersion}/service/call", method = RequestMethod.POST)
And I expected the URL to be:
/apiVersion/service/call
But it turns out {foo} accept any value, it doesn't actually use the String.
Is there a way for me to use the String value as part of the URL?
EDIT
The issue is that I have multiple calls that us that value.
#RequestMapping(value = apiVersion + "/call1", method = RequestMethod.POST)
#RequestMapping(value = apiVersion + "/call2", method = RequestMethod.POST)
#RequestMapping(value = apiVersion + "/call3", method = RequestMethod.POST)
etc.
Technically I can declare constants for each one like you suggested, but it doesn't sound optimal. If there is no way to do it then it is fine, I was just wondering if there is.
SOLUTION
Adding general mapping to the controller.
#RequestMapping("${apiVersion}")
If you want to apply it for all methods in a controller declare it on the controller class level:
#RestController
#RequestMapping("/test")
public class MyController { ...
and you do not need to prepend it before method path.
Otherwise it should be constant so like:
private static final String FOO = "test";
and prepend it before method path like:
FOO + "/service/call"
If you just want to predefine the path in Java just do
#RequestMapping(value = foo + "/service/call", method = RequestMethod.POST)
PathVariables in SpringMvc are meant to be a placeholder for endpoints like in the following
#GetMapping(value = "/books/{id}")
public String displayBook(#PathVariable id) { ... }

Request method 'GET' not supported but it's actually present in Controller

I was developing a simple CRUD application, when i've encountered a this weird error. Weird, because in my controller class convenient #RequestMapping annotated method is present with request GET method mapping. The requested URI is [context]/purchase/change/2. The error is following:
org.springframework.web.servlet.PageNotFound - Request method 'GET' not supported
and there is my controller:
#Controller
#RequestMapping("/purchase")
public class PurchasesController {
//...
#RequestMapping(value = "/add/{userId}", method = RequestMethod.GET)
public String addPurchase(Model model, #PathVariable int userId) {
//that method works with mapping ex. "context/purchase/add/1"
return "purchase_update_add";
}
#RequestMapping(value = "/add/{userId}", method = RequestMethod.POST)
public String addPurchase(
#ModelAttribute("purchase") PurchaseDTO purchaseDto,
#PathVariable int userId) {
//that works too
return "redirect:/user/" + userId;
}
#RequestMapping(value = "/change/${purchaseId}", method = RequestMethod.GET)
public String changePurchaseDate(Model model, #PathVariable int purchaseId) {
model.addAttribute("operation", "change");
PurchaseDTO purchase = new PurchaseDTO();
Purchase purchaseEntity = purchasesDAO.getPurchase(purchaseId);
purchase.setDate(purchaseEntity.getDate());
purchase.setId(purchaseId);
model.addAttribute("purchase", purchase);
return "purchase_update_add";
}
#RequestMapping(value = "/change/{userId}", method = RequestMethod.POST)
public String changePurchaseDate(
#ModelAttribute("purchase") PurchaseDTO purchaseDto,
#PathVariable int userId) {
Purchase purchase = purchasesDAO.getPurchase(purchaseDto.getId());
purchase.setDate(purchaseDto.getDate());
purchasesDAO.updatePurchase(purchase);
return "redirect:/user/" + userId;
}
You've created a Path Variable with ${...} syntax:
#RequestMapping(value = "/change/${purchaseId}", method = RequestMethod.GET)
^ $ is redundant
Use the correct {...} syntax instead:
#RequestMapping(value = "/change/{purchaseId}", method = RequestMethod.GET)

Spring RequestMapping conflicts

I have a RequestMapping that displays a grid, and another one for loading objects in grid.
#RequestMapping(value = "/grid/{objType}", method = RequestMethod.GET)
public String displayGrid(Model model, #PathVariable("objType") String objType) {
// some code here
}
#RequestMapping(value = "/loadGrid", method = RequestMethod.GET)
public #ResponseBody String loadGrid(Model model) {
// returns a JSON
}
When i display the grid the url is like ../grid/User
The problem is that after the grid is created and a request loadGrid is made, the request is mapped to /grid/loadGrid which is resolved by the first method instead of the second one.
Is there any way to make a request for /grid with nothing after it ?
Or any way to resolve this conflict ?
The collision isn't a problem; spring resolves exact matches first. (see the source code of AbstractHandlerMethodMapping)
Your problem is that you've incorrectly defined your mappings. If you define a #RequestMapping at the class level, all the method #RequestMappings will be prefixed with the defined value.
The following maps three endpoints: /grid, /grid/{objType} and /grid/loadGrid. Note that the #RequestMapping for get() defines no value, only its method because it inherits from the class-level annotation.
#Controller
#RequestMapping(value = "/grid")
public class GridController {
#RequestMapping(method = RequestMethod.GET)
public String get(Model model) {
// ...
}
#RequestMapping(value = "/{objType}", method = RequestMethod.GET)
public String displayGrid(Model model, #PathVariable("objType") String objType) {
// ...
}
#ResponseBody
#RequestMapping(value = "/loadGrid", method = RequestMethod.GET)
public String loadGrid(Model model) {
// ...
}
}

how can i read #Pathvariable name and value using HandlerInterceptor in spring?

My code is :
#RequestMapping(value = "productDescription/{productId}/{competitorList}", method = RequestMethod.GET)
#ResponseBody
public ProductDescription getProductDescription(
#PathVariable String productId, #PathVariable String competitorList) {
return service.getProductDescription(productId, competitorList);
}
Using HttpServletRequest request in postHandler method, I want to read the pathvariable names and values.
I am able to get parameter name and values using request.getParameterMap() method if I'm using #RequestParam instead #Pathvariable.
Try this:
#RequestMapping(value = "productDescription/{productId}/{competitorList}", method = RequestMethod.GET)
#ResponseBody
public ProductDescription getProductDescription(#PathVariable("productId") String productId, #PathVariable("competitorList") String competitorList) {
return service.getProductDescription(productId, competitorList);
}

RequestMapping with multiple values with pathvariable - Spring 3.0

#RequestMapping(value = {"/userDetails", "/userDetails/edit/{id}"}, method = RequestMethod.GET)
public String userDetails(Map Model,****) {
//what goes here?
}
What will be my arguments to the userDetails method? And how do I differentiate /userDetails and /userDetails/edit/9 within the method?
Ideally we can get pathvariable by using annotation #PathVariable in method argument but here you have used array of url {"/userDetails", "/userDetails/edit/{id}"} so this will give error while supply request like localhost:8080/domain_name/userDetails , in this case no id will be supplied to #PathVariable.
So you can get the difference (which request is comming through) by using argument HttpServletRequest request in method and use this request object as below -
String uri = request.getRequestURI();
Code is like this -
#RequestMapping(value = {"/userDetails", "/userDetails/edit/{id}"}, method=RequestMethod.GET)
public String userDetails(Map Model,HttpServletRequest request) {
String uri = request.getRequestURI();
//put the condition based on uri
}

Categories

Resources