Suggested Pages

Friday, June 29, 2012

Spring MVC @PathVariable - Tutorial

In this post we'll see an example of the using of @PathVariable in Spring MVC. Suppose this is your controller class.
AddressBookController.java
 ...

@Controller
@RequestMapping(value = "/dao")
public class AddressBookController {

 private static Logger logger = Logger
   .getLogger(AddressBookController.class);

 @Qualifier(value = "addressBookDAO")
 @Autowired
 private AddressBookDAO addressBookDAO;

   
 @RequestMapping(value = "/contact/add/{number}", method = RequestMethod.GET)
 public void add(@PathVariable(value = "number") String number ) {
  logger.debug("add contact()----start: " + number);
  Contact contact=new Contact();
  contact.setNumber(number);
  addressBookDAO.create(contact);
  logger.debug("add contact()----end");
 }
 
}
    
As you can see you @PathVariable is used to map a method parameter with a portion of the request URI. Now if you are interested into saving a contact with a given number telephone (for example 123456), you can make a request at the following URL: http://localhost:8083/<context>/<dispatcher-servlet>/dao/contact/add/123456 .
  • <context> : it is your application context path;
  • <dispatcher-servlet> : it is the value of url-pattern tag of the spring dispatcher-servlet used in your web.xml.

No comments :

Post a Comment

Suggested Pages