With new versions of Spring MVC controllers can be created using the various annotations available like @Controller, @RequestMapping and so on. By Using these annotations, you need not have your controller class extend the various built-in controller classes in Spring MVC.
Creating controller using Spring MVC provided annotation can be summarized as shown below:
- Create a simple POJO class and annotate it with @Controller.
- Create as may request handling methods as required by your web application.
- Now map the URL’s to the appropriate methods using the annotation @RequestMapping.
- Implement the method body by first calling appropriate business logic service; populate the Model object with data from the business service and then finally selecting appropriate View object and returning it.
Listing 14-5 below shows a typical controller class created using @Controller annotation and a sample method mapped to appropriate URL.
Listing 14-5. Controller class created using @Controller annotation
1 2 3 4 5 6 7 8 9 |
@Controller public class SampleController { @RequestMapping("/sampleURL") public String testMethod(Model model) { //Call business logic return "/WEB-INF/sample/test.jsp"; } } |
The @RequestMapping anotation has multiple options by which to map the URL request from the client. Listing 14-6 below shows this annotation and its various options.
Listing 14-6. @RequestMapping annotation options
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
//@RequestMapping with query parameters (parameter name should be present) //Sample URL - /sample/test?paramName=paramValue @RequestMapping(value="/sample/test", params={"paramName"}) public void testMethod1(…){ … } //@RequestMapping with query parameters (parameter name and parameter value should be present) //Sample URL - /sample/test?paramName=paramValue @RequestMapping(value="/sample/test", params={"paramName=paramValue"}) public void testMethod2(…){ … } //@RequestMapping with request method (GET, POST etc.) //Sample URL - /sample/test @RequestMapping(value="/sample/test", method=RequestMethod.GET) public void testMethod3(…){ … } |
Page Visitors: 7466

Tomcy John

Latest posts by Tomcy John (see all)
- A Guide to Continuous Improvement for Architects - February 2, 2023
- Cloud-first Architecture Strategy - January 26, 2023
- Architecture Strategy and how to create One - January 24, 2023