美文网首页
Spring Boot - 5. Controller 的使用

Spring Boot - 5. Controller 的使用

作者: ChenME | 来源:发表于2018-01-18 16:07 被阅读20次
    1. @Controller :处理 http 请求;
    2. @RestController :Spring4 之后新加的注解,原来返回 json 需要 @ResponseBody 配合 @Controller
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class HelloController {
    }
    
    1. @RequsetMapping :配置 url 映射;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String sayHello() {
        return "Hello";
    }
    
    1. @PathVariable :获取 URL 中的数据;
    import org.springframework.web.bind.annotation.PathVariable;
    
    @RequestMapping(value = "/{id}/hello", method = RequestMethod.GET)
    public String sayHello(@PathVariable("id") Integer id) {
        return "id is " + id;
    }
    
    // 访问 http://localhost:8081/cme/23/hello
    
    屏幕快照 2018-01-18 15.58.51.png
    1. @RequestParam :获取请求参数的值;
    import org.springframework.web.bind.annotation.RequestParam;
    
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String sayHello(@RequestParam("id") Integer myId) {
        return "id is " + myId;
    }
    
    // 访问 http://localhost:8081/cme/hello?id=100
    
    屏幕快照 2018-01-18 16.05.54.png
    • 设置默认值
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String sayHello(@RequestParam(value = "id", required = false, defaultValue = "0") Integer myId) {
        return "id is " + myId;
    }
    
    // 访问 http://localhost:8081/cme/hello
    
    屏幕快照 2018-01-18 16.11.44.png
    1. @GetMapping @PostMapping ... :组合注解;

    相关文章

      网友评论

          本文标题:Spring Boot - 5. Controller 的使用

          本文链接:https://www.haomeiwen.com/subject/etswoxtx.html