Share on Google+Share on Google+

@RequestMapping annotation for mapping requests

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 :

public class HelloWorldController {
	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:

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".


Posted on: January 8, 2013 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.

Discuss: @RequestMapping annotation for mapping requests  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image