Lets say I have a Category domain model object that follows a file tree structure. I want to be able to construct a RequestMapping annotation for the controller method so that
/category/art/macros
/category/people/weddings/2014/5-19
/category/sports/college/baseball/2014/5-19
can be handled by the minimum number of controller methods.
I already have one controller method defined:
#RequestMapping(value ={"/category/{category}"}, method = RequestMethod.GET)
public String adminCategory(ModelMap model, #PathVariable(value = "category") String category){
model.addAttribute("message", category);
return "gallery";
}
This works for a single URL like
/category/sports
How can I adapt this to be more flexible?
The challenge is here that you can't make #PathVariable optional but you can have two or more controller methods which can call the same service code. So, for you three URL patterns you have to define three different controllers:
GET: /category/art/macros
#RequestMapping(value ={"/category/{category}"}, method = RequestMethod.GET)
public String adminCategory(ModelMap model, #PathVariable(value = "category") String category){
model.addAttribute("message", category);
return "gallery";
}
GET: /category/people/weddings/2014/5-19
#RequestMapping(value ={"/category/{category}/{subcategory}/{year}/{date}"}, method = RequestMethod.GET)
public String adminCategory(ModelMap model, #PathVariable(value = "category") String category,
#PathVariable(value = "subcategory") String subcategory,
#PathVariable(value = "year") String year,
#PathVariable(value = "date") String date
){
model.addAttribute("message", category, subcategory, year, date);
return "gallery";
}
GET: /category/sports/college/baseball/2014/5-19
#RequestMapping(value ={"/category/{category}/{subcategory}/{year}/{date}"}, method = RequestMethod.GET)
public String adminCategory(ModelMap model, #PathVariable(value = "category") String category,
#PathVariable(value = "subcategory") String subcategory,
#PathVariable(value = "sub_sub_category") String sub_sub_category,
#PathVariable(value = "year") String year,
#PathVariable(value = "date") String date
){
model.addAttribute("message", category, subcategory, sub_sub_category, year, date);
return "gallery";
}
PS You can user #RequestParam which can be optional and reduce the number of controllers.
Related
I have below API to be tested. Not getting solution to pass string array to requestors. Tried with comma seperated values, values with in [] etc.
#RequestMapping(value = "/v10/{user}/alerts/alertguids/{requestors}", method = RequestMethod.GET)
#ResponseBody
#ResponseStatus(HttpStatus.OK)
public String[] retrieveRunnableAlertGuidsByRequestors(#RequestParam(value = "productId") final String productId,
#PathVariable final String[] requestors)
I'm not sure with #PathVariable but you can use the #RequestParam.
eg:
#RequestMapping(value = "/v10/{user}/alerts/alertguids/{requestors}", method = RequestMethod.GET)
#ResponseBody
#ResponseStatus(HttpStatus.OK)
public String[] retrieveRunnableAlertGuidsByRequestors(#RequestParam(value = "productId") final String productId,
#RequestParam(value = "param[]") final String[] requestors)
I have to write an API call
#GET
#Path("/{settingName1, settingName2}")
public Response getNetworkSettingValue(#ApiParam(value = "Name") #QueryParam("name") String name,
#ApiParam(value = "City") #QueryParam("city") String city,
#ApiParam(value = "State") #QueryParam("state") String state) {}
here my doubt is how to get settingName1 & settingName2 values,
can write like
#ApiParam(value = "SettingName1") #PathParam("settingName1") String settingName1
or
#ApiParam(value = "SettingName1") #PathVariable("settingName1") String settingName1
in method declaration.
or
any other way to get those two values
By the #Path annotation, I assume you are using JAX-RS (Jersey, RESTEasy, etc). So it should be:
#ApiParam(value = "SettingName1") #PathParam("settingName1") String settingName1
If you were using Spring, it should be:
#ApiParam(value = "SettingName1") #PathVariable("settingName1") String settingName1
your annotations are mixed up with spring and swagger.
If u want to accesss pathvariables with spring than it have to be like
#RequestMapping(value = "/{settingName1}/{settingName2}", method = equestMethod.GET)
public Response getNetworkSettingValue(#ApiParam(value = "settingName1") #PathVariable final String settingName1,
#ApiParam(value = "settingName2") #PathVariable final String settingName2) {
...
return new Response();
}
What is the proper way to handle editing objects in Spring MVC. Let's say I have user object:
public class User {
private Integer id;
private String firstName;
private String lastName;
//Lets assume here are next 10 fields...
//getters and setters
}
Now in my controller I have GET and POST for url: user/edit/{id}
#RequestMapping(value = "/user/edit/{user_id}", method = RequestMethod.GET)
public String editUser(#PathVariable Long user_id, Model model) {
model.addAttribute("userForm", userService.getUserByID(user_id));
return "/panels/user/editUser";
}
#RequestMapping(value = "/user/edit/{user_id}", method = RequestMethod.POST)
public String editUser(#Valid #ModelAttribute("userForm") User userForm,
BindingResult result, #PathVariable String user_id, Model model) {
if(result.hasErrors()) {
User user = userService.getById(user_id);
user.updateFields(userForm);
}
userService.update(user);
}
Now the question is do I really need to get my user from database in POST method and update every field one by one in some update method or is there better way for that?
I am thinking about using #PathVariable for User and get User from database with converter and then in some way inject parameters from POST method into that object automatically. Something like this:
#RequestMapping(value = "/user/edit/{user}", method = RequestMethod.POST)
public String editUser(#Valid #PathVariable("user") User userForm,
BindingResult result, Model model)
But when I try this I got error with BindingResults:
java.lang.IllegalStateException: An Errors/BindingResult argument is expected to be declared immediately after the model attribute, the #RequestBody or the #RequestPart arguments
Is there any easy way to create controller to handle objects editing or do I need to copy fields which could change one by one??
By the way, I can't use SessionAttributes because it causes problems for multiple tabs.
I believe you are sending "userForm" as a model attribute. If so try with following pattern,
#RequestMapping(value = "/user/edit/{user_id}", method = RequestMethod.POST)
public String editUser(#PathVariable String user_id, #Valid #ModelAttribute("userForm") User userForm,
BindingResult result, Model model)
Thanks
You keep user id in a input hidden inside your edit form.
#RequestMapping(value = "/user/edit", method = RequestMethod.POST)
public String editUser(#Valid #ModelAttribute("userForm") User userForm,
BindingResult result,Model model){
if(result.hasErrors()){
User user = userService.getById(userForm.getId());
user.updateFields(userForm);
}
userService.update(user);
return "redirect:.......";
}
How do I change my request mapping for dynamic urls? URLs might look like this:
http://zz.zz.zz.com:8080/webapp/p1/q9/e3/test?Id=2&maxrows=5
http://zz.zz.zz.com:8080/webapp/a1/b2/c3/test?Id=2&maxrows=5
http://zz.zz.zz.com:8080/webapp/x1/y2/z3/test?Id=2&maxrows=5
Here's the working controller syntax when the url is in this format:
http://zz.zz.zz.com:8080/webapp/test?Id=2&maxrows=5
#RequestMapping(value = "/test", method = RequestMethod.GET)
public #ResponseBody void test(
#RequestParam(value = "Id", required = true) String Id,
#RequestParam(value = "maxrows", required = true) int maxrows
) throws Exception {
System.out.println("Id: " + Id + " maxrows: " + maxrows);
}
Try this:
#RequestMapping(value = "/test/{param1}/{param2}/{param3}")
public #ResponseBody void test(
#RequestParam(value = "Id", required = true) String Id,
#RequestParam(value = "maxrows", required = true) int maxrows,
#PathVariable(value = "param1") String param1,
#PathVariable(value = "param2") String param2,
#PathVariable(value = "param3") String param3) {
...
}
For more information look at Spring Reference Documentation
#RequestMapping(value = "/Fin_AddCheckBook", method = RequestMethod.POST)
public #ResponseBody
JsonResponse addCoaCategory(
#RequestParam(value="checkbookNumber", required=true) String checkbookNumber,
#RequestParam(value="checkbookName", required=true) String checkbookName,
#RequestParam(value="startNumber", required=true) long startNumber,
#RequestParam(value="bankId", required=true) long bankId,
#RequestParam(value="currencyId", required=true) long currencyId,
#RequestParam(value="noOfLeves", required=true) int noOfLeves,
#RequestParam(value="alertAt", required=true) int alertAt,
#RequestParam(value="isActive", required=true) int isActive, Map map, Model model) {
I have two table in one form ! I want to receive first table elements by name by specifying #RequestParam(value="startNumber", required=true) long startNumber;
but
second table elements in Map i.e Map map
How to receive some parameter with name and all other element in map ?
Create your own objects :
public class MyMap {
private String myObject1; // dont forget that these names should be same as #RequestParam values
private Integer myObject2;
//setters and getters. they are must!!
}
public class MyMap2 {
private String my1;
private Integer my2;
//setters and getters. they are must!!
}
Now put this object as a parameter of your controller method.
#RequestMapping(value = "/Fin_AddCheckBook", method = RequestMethod.POST)
public #ResponseBody JsonResponse addCoaCategory(MyMap myMap, MyMap2 myMap2, BindingResult result) {
if (!result.hasErrors()) {
// work with myMap myMap2
}
}