Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpringMVC RequestMapping for GET parameters

How to make the RequestMapping to handle GET parameters in the url? For example i have this url

http://localhost:8080/userGrid?_search=false&nd=1351972571018&rows=10&page=1&sidx=id&sord=desc 

(from jqGrid)

how should my RequestMapping look like? I want to get the parameters using HttpReqest

Tried this:

@RequestMapping("/userGrid")     public @ResponseBody GridModel getUsersForGrid(HttpServletRequest request) 

but it doesn't work.

like image 514
Evgeni Dimitrov Avatar asked Nov 03 '12 20:11

Evgeni Dimitrov


People also ask

What is the @RequestMapping annotation used for?

annotation. RequestMapping annotation is used to map web requests onto specific handler classes and/or handler methods. @RequestMapping can be applied to the controller class as well as methods.

Can we use @RequestParam in Get method?

Use the @RequestParam annotation to bind request parameters to a method parameter in your controller. AFAIK, request parameters are variables retrieved from query strings if the request method is GET. They are also the variables retrieved from the form values when the request method is POST.

Can we use @RequestMapping at method level?

The @RequestMapping annotation can be applied to class-level and/or method-level in a controller. The class-level annotation maps a specific request path or pattern onto a controller.

Which of the following is the method where RequestMapping is used with RequestParam?

The @RequestParam annotation is used with @RequestMapping to bind a web request parameter to the parameter of the handler method.


1 Answers

Use @RequestParam in your method arguments so Spring can bind them, also use the @RequestMapping.params array to narrow the method that will be used by spring. Sample code:

@RequestMapping("/userGrid",  params = {"_search", "nd", "rows", "page", "sidx", "sort"}) public @ResponseBody GridModel getUsersForGrid( @RequestParam(value = "_search") String search,  @RequestParam(value = "nd") int nd,  @RequestParam(value = "rows") int rows,  @RequestParam(value = "page") int page,  @RequestParam(value = "sidx") int sidx,  @RequestParam(value = "sort") Sort sort) { // Stuff here } 

This way Spring will only execute this method if ALL PARAMETERS are present saving you from null checking and related stuff.

like image 134
ElderMael Avatar answered Oct 17 '22 03:10

ElderMael