Home Spring Spring3.2 @RequestMapping annotation for mapping requests
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

@RequestMapping annotation for mapping requests

Advertisement
In this section, you will learn to map request to associated class or method using @RequestMapping annotation.

@RequestMapping annotation for mapping requests

In this section, you will learn to map request  to associated class or method using @RequestMapping annotation.

@RequestMapping annotation  is used to map the requested URL to the associated class or method to handle the request.

Given below the sample code for @RequestMapping annotation :

@Controller
public class HelloWorldController {
	@RequestMapping("/hello")
	public ModelAndView helloWorld() {
		String message = "Hello World, Spring 3.0!";
		return new ModelAndView("hello", "message", message);
	}
}

In the above example, URL "/hello" is mapped to the handler method helloWorld.

If you want to map the URL to the entire class, you can do it as follows:

@Controller
@RequestMapping("/loginform")
public class LoginController {
	@RequestMapping(method = RequestMethod.GET)
	public String showForm(Map model) {
		LoginForm loginForm = new LoginForm();
		model.put("loginForm", loginForm);
		return "loginform";
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String processForm(@Valid LoginForm loginForm, BindingResult result,
	Map model) {
		String userName = "Admin";
		String password = "root";
		if (result.hasErrors()) {
			return "loginform";
		}
		loginForm = (LoginForm) model.get("loginForm");
		if (!loginForm.getUserName().equals(userName)|| !loginForm.getPassword().equals(password)) {
			return "loginerror";
		}
		model.put("loginForm", loginForm);
		return "loginsuccess";
	}
}

In the above example, the entire class LoginController is mapped to the URL "/loginform".

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  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.

Posted on: January 8, 2013

Related Tutorials

Ask Questions?    Discuss: @RequestMapping annotation for mapping requests  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com