How do I use #RequestParam to bind one parameters of type String which is mandatory and another one which is of type Map<String, String> which is optional ?
#RequestMapping(value = "users", method = RequestMethod.GET)
public String getUsers(#RequestParam(name = "mandatory") String mandatory,
#RequestParam(required = false) Map < String, String > optional)
throws Exception {
return userService.getUsers(mandatory, optional);
}
If what you want is to simply indicate that the "mandatory" parameter is required, you must add the required = true as follows:
#RequestMapping(value = "users", method = RequestMethod.GET)
public String getUsers(#RequestParam(name = "mandatory", required = true) String mandatory,
#RequestParam(required = false) Map < String, String > optional)
throws Exception {
return userService.getUsers(mandatory, optional);
}
Related
I´m trying to make a request with or without parameters, according the code below:
#RequestMapping(value = "/threshold/list", method = RequestMethod.GET)
public List<Threshold> listThreshold(#RequestParam(required = false) String categoria, #RequestParam(required = false) String kpi, #RequestParam(required = false) String data, #RequestParam(required = false) String hora) {
return thresholdQuery.listThreshold(categoria, kpi, data, hora);
}
But when I call the endpoint this way:
http://localhost:8081/threshold/list?categoria=casa
I got the error below:
Not enough variable values available to expand 'categoria=casa'
I believe it should be 'name' instead of 'value'
#RequestParam(name="categoria",required = false)
How can I simply redirect a url if a specific query parameter is missing?
#RestController
public class PersonController {
//only in case the "sort" query parameter is missing
#GetMapping("/persons")
public String unsorted() {
return "redirect:/persons?sort=name";
}
//only in case the "sort" query parameter exists
#GetMapping("/persons")
public String sorted() {
//...
}
}
Use #RequestParam to extract query parameters
Add parameter for #RequestParam: value, defaultValue, required
with java >= 8:
#RestController
public class PersonController {
#GetMapping("/persons")
public String personList(#RequestParam(value = "sort", defaultValue = "name") Optional<String> sort) {
//handling process here
}
}
with java < 8:
#RestController
public class PersonController {
#GetMapping("/persons")
public String personList(#RequestParam(value = "sort", defaultValue = "name", required=false) String sort) {
//handling process here
}
}
You could use #GetMapping.params
#GetMapping(value = "/persons", params = "sort")
public String sorted() {
You can use the params element. One mapping will supports params="sort" for when the sort parameter is present and the other params="!sort" for when it is missing.
However, you may want to consider using a default value instead of performing a redirect. What benefit does the redirect provide? It will require the server respond and then and have the client make a second HTTP request.
Using params
#RestController
public class PersonController {
//only in case the "sort" query parameter is missing
#GetMapping(value = "/persons", params = "!sort")
public String unsorted() {
return "redirect:/persons?sort=name";
}
//only in case the "sort" query parameter exists
#GetMapping(value = "/persons", params = "sort")
public String sorted() {
//...
}
}
Using default value
#RestController
public class PersonController {
//only in case the "sort" query parameter exists
#GetMapping("/persons")
public String sorted(
#RequestParam(name = "sort", defaultValue = "name") String sort)
{
//...
}
}
You can set a default value:
#RestController
public class PersonController {
//only in case the "sort" query parameter is missing
#GetMapping("/persons")
public String unsorted(#RequestParam(value = "sort", defaultValue = "name") String name) {
// do logic
}
}
You can also set the default value for the missing value and continue forward
#RequestParam(value = "sort", defaultValue = "name") String name
User can search something on my list
<form action="/worldoffragrance">
<input name="search"/>
<input type="submit" value="search"/>
If list its empty, I'd like to make another website, where User can put what he want , How can i resolve this problem? :)
#RequestMapping("/")
public String fragrance() { return "fragrance"; }
#RequestMapping("/worldoffragrance")
public String worldoffragrance(
#RequestParam(value = "search") String search,
#RequestParam(value = "operation", required = false, defaultValue = "search") String operation, Model model) {
List<Fragrance> matchingPerfumes = advisor.findMatchingPerfume(search);
if (matchingPerfumes.isEmpty()) {
return "redirect:/fragrancenotfound";
}
model.addAttribute("matchingPerfumes", matchingPerfumes);
return "result";
}
#RequestMapping("/fragrancenotfound")
public String fragranceNotFound(
#RequestParam(value = "name", required = true) String getName,
#RequestParam(value = "ingredients", required = true) String getIngredients,
#RequestParam(value = "operation", required = false, defaultValue = "add" ) String operation, ModelMap model)
{
model.addAttribute("getName", "getIngredients");
return "redirect: /createNewFragrance";
}
#RequestMapping("/createnewfragrance")
public String createnewfragrance() {
return "createNewFragrance";}
you are redirecting to /fragrancenotfound which has a required parameter of name (and ingredient) which you are not providing. either provide these values or make them not required
I have method in my REST controller that contains a lot of parameters. For example:
#RequestMapping(value = "/getItem", method = RequestMethod.GET)
public ServiceRequest<List<SomeModel>> getClaimStatuses(
#RequestParam(value = "param1", required = true) List<String> param1,
#RequestParam(value = "param2", required = false) String param2,
#RequestParam(value = "param3", required = false) List<String> param3,
#RequestParam(value = "param4", required = false) List<String> param4,
#RequestParam(value = "param5", required = false) List<String> param5) {
// ......
}
and I would like to map all GET request parameters to a POJO object like:
public class RequestParamsModel {
public RequestParamsModel() {
}
public List<String> param1;
public String param2;
public List<String> param3;
public String param4;
public String param5;
}
I need something like we can do using #RequestBody in REST Controller.
Is it possible to do in Spring 3.x ?
Thanks!
Possible and easy, make sure that your bean has proper accessors for the fields. You can add proper validation per property, just make sure that you have the proper jars in place. In terms of code it would be something like
import javax.validation.constraints.NotNull;
public class RequestParamsModel {
public RequestParamsModel() {}
private List<String> param1;
private String param2;
private List<String> param3;
private String param4;
private String param5;
#NotNull
public List<String> getParam1() {
return param1;
}
// ...
}
The controller method would be:
import javax.validation.Valid;
#RequestMapping(value = "/getItem", method = RequestMethod.GET)
public ServiceRequest<List<SomeModel>> getClaimStatuses(#Valid RequestParamsModel model) {
// ...
}
And the request, something like:
/getItem?param1=list1,list2¶m2=ok
Are you trying to do
#RequestMapping(value = "/getItem", method = RequestMethod.GET)
public ServiceRequest<List<SomeModel>> getClaimStatuses(#ModelAttribute RequestParamsModel requestParamModel) {
...
}
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);
}
}
}