Saturday, March 12, 2022

Spring Web MVC

Front Controller

the concept of the Front Controller in the typical Spring Model View Controller architecture

At a very high level, here are the main responsibilities we're looking at:

  • Intercepts incoming requests
  • Converts the payload of the request to the internal structure of the data
  • Sends the data to Model for further processing
  • Gets processed data from the Model and advances that data to the View for rendering


  • DispatcherServlet plays the role of the Front Controller in the architecture.
  • The diagram is applicable both to typical MVC controllers as well as RESTful controllers
  • MVC applications are not service-oriented hence there is a View Resolver that renders final views based on data received from a Controller
  • RESTful applications are designed to be service-oriented and return raw data (JSON/XML typically). Since these applications do not do any view rendering, there are no View Resolvers – the Controller is generally expected to send data directly via the HTTP response

MVC Controller : 

@Controller
@RequestMapping(value="Test")
public class TestController{
.....
}

Rest Controller :

Maven Dependencies :  spring-web,  spring-webmvc,  jackson-databind

@Controller
public class TestController{
   @GetMapping(value = "/student/{studentId}")
    public @ResponseBody Student getTestData(@PathVariable Integer studentId) {
        Student student = new Student();
        student.setName("Peter");
        student.setId(studentId);

        return student;
    } 
}
@ResponseBody annotation on the method – which instructs Spring to bypass the view resolver and essentially write out the output directly to the body of the HTTP response.

Spring Boot - @RestController

@RestController
public class RestAnnotatedController {
    @GetMapping(value = "/annotated/student/{studentId}")
    public Student getData(@PathVariable Integer studentId) {
        Student student = new Student();
        student.setName("Peter");
        student.setId(studentId);

        return student;
    }
}
@RestController annotation from Spring Boot is basically a quick shortcut that saves us from always having to define @ResponseBody. Help by pass view rendering stage and directly writing response to HTTP response body

@RequestMapping
the annotation is used to map web requests to Spring Controller methods

Example 1 : Request Mapping with by path and HTTP method

@RequestMapping(value = "/ex/foos", method = POST)
@ResponseBody
public String postFoos() {
    return "Post some Foos";
}


Example 2 : Request Mapping and HTTP header

@RequestMapping(
  value = "/ex/foos", 
  headers = { "key1=val1", "key2=val2" }, method = GET)
@ResponseBody
public String getFoosWithHeaders() {
    return "Get some Foos with Header";
}


Example 3 : Mapping media types produced and consumed by controller

@RequestMapping(value="/method6",
produces={"application/json","application/xml"},
consumes="text/html")
@ResponseBody
public String method6(){
return "method6";
}
Above method can consume message only with Content-Type as text/html and is able to produce messages of type application/json and application/xml.


Example 4 : Request Mapping with Path Variable

@RequestMapping(value = "/ex/foos/{fooid}/bar/{barid}", method = GET)
@ResponseBody
public String getFoosBySimplePathWithPathVariables
  (@PathVariable long fooid, @PathVariable long barid) {
    return "Get a specific Bar with id=" + barid + 
      " from a Foo with id=" + fooid;
}

Example 5 : Request Mapping with Request Parameters

@RequestMapping(value = "/ex/bars", method = GET)
@ResponseBody
public String getBarBySimplePathWithRequestParam( @RequestParam("id") long id) {
    return "Get a specific Bar with id=" + id;
}

http://localhost:8080/spring-rest/ex/bars?id=100

Example 6 :  Request Mapping with Fallback

@RequestMapping(
  value = "*", 
  method = { RequestMethod.GET, RequestMethod.POST ... })
@ResponseBody
public String allFallback() {
    return "Fallback for All Requests";
}

@RequestMapping New Shortcut Annotations

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
  • @PatchMapping



Reference 1 :  Baeldung
Reference 2 :  Journal Dev