Thursday 17 May 2012

@RequestMapping - A quick tutorial on Multiple and Conditional Parameters

I've been doing some work with recently creating Java rest web services. In doing this I've learnt a couple of nifty things about the @RequestMapping annotation. This information seems to be spread around quite a lot of forums etc so I thought it would be good to compile it into one tutorial.

The @RequestMapping annotation is used to define the URL pattern that will trigger your code when the web service is called.

So an annotation Like this
@RequestMapping(value = "/example/{id}", method = RequestMethod.GET)
public Example exampleMethod(@PathVariable("id") Long id){
...Code goes here
}

means that the method exampleMethod will be triggered by a URL like this
http://llocalhost:8080/example-ws/example/13

Two things I've seen asked on the internet quite a lot is how can I have multiple mappings and conditional mappings.

Multiple Mappings
The value parameter of @RequestMapping is of type String [] so an annotation of the form

@RequestMapping(value = {"/example", "/example/{id}"}, method = RequestMethod.GET)

Will allow both the urls
http://llocalhost:8080/example-ws/example/13 and http://llocalhost:8080/example-ws/example
to execute the code that follows the annotation.

Conditional Mappings
If you want to execute different code based on what url is sent then simply have multiple methods using different @RequestMapping parameters

so in the same class you would have

@RequestMapping(value = "/example1/{id}", method = RequestMethod.GET)
...Method 1 goes here

and


@RequestMapping(value = "/example2/{id}", method = RequestMethod.GET)
...Method 2 goes here


this would allow you to call method 1 with
http://llocalhost:8080/example-ws/example1/13

and method 2 with
http://llocalhost:8080/example-ws/example2/13


Hopefully you find this tutorial helpful as it took me a while to find this information

No comments:

Post a Comment