Share on Google+Share on Google+

@PathVariable Annotation

Advertisement
In this tutorial you will learn about @PathVariable Annotation

@PathVariable Annotation

By using the @PathVariable annotation you can create the dynamic varible at the url and can access that varible from there as.

	/*
	 * Here pathVar is the new path variable when it finds the
	 * /param/process-form/pathVar it is copies by the @PathVariable into the
	 * pathVar variable.
	 * try url as when you are running application '/PathVariableAnnotation/param/client-req/productName'
	 */

	@RequestMapping(value = "/client-req/{pathVar}")
	public String processReq(Model model,
			@PathVariable("pathVar") String pathVar) {
		model.addAttribute("pathVar", pathVar);
		return "view-data";
	}

Please consider the complete controller class given below

SampleInterfaceImp.java

package roseindia.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value = "/param/")
public class ApplicationController {

	/*
	 * Here pathVar is the new path variable when it finds the
	 * /param/process-form/pathVar it is copies by the @PathVariable into the
	 * pathVar variable.
	 * try url as when you are running application '/PathVariableAnnotation/param/client-req/productName'
	 */

	@RequestMapping(value = "/client-req/{pathVar}")
	public String processReq(Model model,
			@PathVariable("pathVar") String pathVar) {
		model.addAttribute("pathVar", pathVar);
		return "view-data";
	}

	/*
	 * By using  @PathVariable you can also add new variable between the URL.
	 * try url as when you are running application '/PathVariableAnnotation/param/product/YourNewVarible/information'
	 */
	
	@RequestMapping(value = "/product/{productName}/information")
	public String anotherReq(Model model,
			@PathVariable("productName") String productName) {
		model.addAttribute("productName", productName);
		return "view-data";
	}
}

You can download the complete source code from here

Advertisements

Advertisement

Posted on: May 17, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.