@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

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