How to map URLs using annotations in Spring MVC?
In Spring 3 you can use the @RequestMapping annotation to map URLs onto an entire class or a particular handler method.
Typically the class-level annotation maps a specific request path (or path pattern) onto a form controller, with additional method-level
annotations narrowing the primary mapping for a specific HTTP method request method ("GET", "POST", etc.) or an HTTP request parameter condition.
Dont forget to add component-scan within your xml based configuration file as shown below:
<context:component-scan base-package="com.java2novice.controllers" />
|
The following example shows a controller in a Spring MVC application that uses @RequestMapping annotation:
package com.java2novice.controllers;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.java2novice.models.Employee;
import com.java2novice.models.EmployeeForm;
@Controller
@RequestMapping("/employee")
public class EmployeeController {
@RequestMapping(method = RequestMethod.GET)
public List<Employee> getEmployeeList(){
List<Employee> empList = null;
/**
* Add a logic to retrieve all employee list
*/
return empList;
}
@RequestMapping(method = RequestMethod.POST)
public String addEmployee(EmployeeForm empForm){
/**
* add a logic to add employee details
*/
return "success";
}
@RequestMapping(value="/managers", method = RequestMethod.GET)
public List<Employee> getEmployeeManagers(){
List<Employee> empList = null;
/**
* Add a logic to retrieve all employee managers
*/
return empList;
}
@RequestMapping(value="/{empId}", method = RequestMethod.GET)
public Employee getEmployeeById(@PathVariable Long empId){
Employee emp = null;
/**
* Add a logic to retrieve requested employee details
*/
return emp;
}
}
|
In the example, the @RequestMapping is used in a number of places. The first usage is on the type (class) level, which indicates
that all handling methods on this controller are relative to the /employee path.
1) The getEmployeeList() method has a further @RequestMapping refinement: it only accepts GET requests, meaning that an HTTP GET for
/employee invokes this method.
2) The addEmployee() method has similar @RequestMapping refinement with http method as POST: it only accepts POST requests, meaning
that an HTTP POST for /employee invokes this method.
3) The getEmployeeManagers() method will be invoked when user requested with HTTP GET /employee/managers.
4) The getEmployeeById() method will be invoked when user requested with HTTP GET /employee/{employee_id_number_comes_here}. The
@PathVariable value assigns the dynamic value from the URI to method input parameter.
|