Home Tutorial Spring @ModelAttribute Annotaion

 
 

Share on Google+Share on Google+
@ModelAttribute Annotaion
Posted on: May 17, 2012 at 12:00 AM
Advertisement
In this tutorial you will learn about the @ModelAttribute Annotaion

@ModelAttribute Annotaion

@ModelAttribute annotation can be used for maintaining some common attributes for all the handler methods inside the class, rather than adding attributes for on model in each handler methods. you can also use this annotation inside the handler method parameter. you may use this annotaion as

@ModelAttribute("cities")
	public List changeData() {
		List cities = new ArrayList();
		cities.add("Patna");
		cities.add("Delhi");
		cities.add("Kanpur");
		cities.add("Lucknow");
		cities.add("Hyderabad");
		cities.add("Merath");
		return cities;
	}

A sample controller class is given below

MyController.java

package roseindia.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import roseindia.form.SampleForm;

@Controller
public class MyController {

	@RequestMapping(value = "/load-form")
	public String loadform(@ModelAttribute("sampleForm") SampleForm sampleForm) {
		return "index";
	}

	@RequestMapping(value = "/view-attributes")
	public String modelAttributeExample(
			@ModelAttribute("sampleForm") SampleForm sampleForm) {
		return "view-data";
	}

	/*
	 * Set Model Default attribute here.
	 */

	@ModelAttribute("cities")
	public List changeData() {
		List cities = new ArrayList();
		cities.add("Patna");
		cities.add("Delhi");
		cities.add("Kanpur");
		cities.add("Lucknow");
		cities.add("Hyderabad");
		cities.add("Merath");
		return cities;
	}
}

You can download the complete source code from here

Advertisement

Related Tags for @ModelAttribute Annotaion:


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.

Posted on: May 17, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com