springboot:spring_restcontroller

Spring RestController

  1. Create a package call controllers (could be anything, but this name make it clear) under your project root package.
  2. Create a class call Home (could be anything, but this name make it clear) in the controllers package.
  3. package com.example.demo.controllers
    
    import com.example.demo.domain.Cat
    import org.springframework.web.bind.annotation.GetMapping
    import org.springframework.web.bind.annotation.RequestParam
    import org.springframework.web.bind.annotation.RestController
    
    @RestController
    class Home {
        @GetMapping("/")
        String index() {
            return "Return as plain text"
        }
    
        @GetMapping("/cat")
        Cat something() {
            return new Cat()
        }
    
        @GetMapping("/param")
        String param(@RequestParam(value = "param1", defaultValue = "param1") String param1) {
            return param1
        }
    }
  4. Above your class name, add @RestController to tell spring that it is a rest controller class
  5. To map url get path to a method, put @GetMapping with the corresponding path eg:@GetMapping(“/”) above the method. This example mapped the root path to the method index()
  6. If the thing return is a string, it will return a plain text to the http client.
  7. If the thing return is an object, it will return a JSON that represent that Object. It depends in the getter of that Object.
  8. We can take parameter from user by using @RequestParam. We can map it to the parameter with the method parameter, and give it a default value if the user do not supply one.

We have all kind of mapping, and we can map the same path with different http method to a different functions.

  1. @GetMapping
  2. @PostMapping
  3. @PutMapping
  4. @DeleteMapping
  5. @PatchMapping

We can add @RequestMapping(“something”) to the class so that any mapping under this class will become /something/…

  • springboot/spring_restcontroller.txt
  • Last modified: 2020/05/28 15:17
  • by chongtin