For this tutorial, I will be using the workspace created in my tutorial RESTful Web Service with Spring 3.1. So I suggest you to read RESTful Web Service with Spring 3.1, before start reading this tutorial. In JAX-RS, you can use @RequestParam annotation to inject URI query parameter into Java method and in this tutorial I will demonstrate how to use this using Spring 3.1.0.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | package com.techiekernel.service; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.techiekernel.model.FooBar; import com.techiekernel.model.FooBarSet; /** * This exmaple has been created to demonstrate the @RequestParam for JAX-RS * * @author satish * */ @Controller @RequestMapping("/foobaresample3") public class FooBarServiceExample3 { static FooBarSet fooBarSet; static { fooBarSet = new FooBarSet(); FooBar foobar = null; for (int i = 0; i < 10; i++) { foobar = new FooBar(i, "TechieKernel" + i); fooBarSet.add(foobar); } } @RequestMapping(method = RequestMethod.GET, headers = "Accept=application/xml, application/json", produces = { "application/json", "application/xml" }) @ResponseBody public FooBar getFoobar(@RequestParam int foobarId) { for (FooBar foobar : fooBarSet) { if (foobar.getId() == foobarId) return foobar; } return null; } @RequestMapping(value= "/name" ,method = RequestMethod.GET, headers = "Accept=application/xml, application/json", produces = { "application/json", "application/xml" }) @ResponseBody public FooBar getFoobar(@RequestParam int foobarId, @RequestParam String name) { for (FooBar foobar : fooBarSet) { if (foobar.getId() == foobarId && foobar.getName().equalsIgnoreCase(name)) return foobar; } return null; } } |
Now it is time to test the web service for different inputs..
1 2 3 | curl -i "http://springmvc-rest.cloudfoundry.com/foobaresample3?foobarId=1" -X GET curl -i "http://springmvc-rest.cloudfoundry.com/foobaresample3/name?foobarId=1&name=techiekernel1" -X GET |
I have deployed the application in cloud space and it is available for you to test. You can use the above URLs to test from your side..
Source Code:
You can pull the source code from GitHub.
0 comments:
Post a Comment