【系统学习SpringBoot】springBoot 入门篇

学了spring boot感觉 ,和springMVC在许多地方还是时分相似的,,请求处理都是使用@RequestMapping注解,但是启动方式上有很大不同,,
springMVC是web项目,需要通过tomcat进行启动
springBoot则类似应用程序,使用main进行启动(SpringApplication.run()),哈哈这是表象,看了这个日志,才知道,springboot也是通过tomcat启动的(Tomcat started on port(s): 8080 (http))



一。不带参请求

//    @RequestMapping(value = {"/hello","/hi"} ,method =            RequestMethod.GET)
    @PostMapping("/hello")
    public String sayHello(){
        return "hello Spring boot";
    }

@RequestMapping(value = “/hello” ,method = RequestMethod.GET)

@GetMapping(“/hello”)
两个注解的作用是相同的,,当然,Get换成 post/put等也可以

{“/hello”,”/hi”},,或的关系,请求任意一个即可映射到sayHello()中



二。接收请求参数

自从有了spring booti,,接收参数将变得十分简单

  @GetMapping("/hello/{id}")
    public String sayHello(@PathVariable int id, @RequestParam(value = "name", required = false, defaultValue = "xiaobai") String name) {
        return "   id:" + id + "   name:" + name;
//        return "name:"+ name;
    }



(1)可以在映射字符串后添加“ {id} ”,接收与请求链接对应的参数,,@PathVariable(“name”)注解可携带映射名称({}花括号中的字符串和变量名不同时,相同时不需要

(2)@RequestParam(value = “name”)注解,可以解析URL链接中的GET请求(如baidu.com?name=baidu。,,,可以解析后面字符串“百度”

(3)@RequestParam(value = “name”, required = false, defaultValue = “xiaobai”)
required指是否必须传入,。。defaultValue,,设置默认值



三。接收请求参数并封装为对象

 @PostMapping("/hello2")
    public String sayHello(Student student) {
        return "   id:" + student.getId() + "   name:" + student.getName();
    }

sayHello(Student student),将此方法中的参数直接换成对象,即可接收post表单中传入的信息,,,,就这么简单粗暴



四。接受信息限制

(1)首先需要在实体类中,添加注解 @Min,当然@Max也有

 @Min(value = 10, message = "小于10,,不可以的")
    private int id;

(2)在需要验证的参数中加入 @Valid 注解
通过 result.getFieldError().getDefaultMessage();可以获取,注解中的message

 @PostMapping("/hello2")
    public String sayHello(@Valid User student, BindingResult result) {
        if (result.hasErrors()) {
            System.out.println("错了");
            return result.getFieldError().getDefaultMessage();
        }
        return "   id:" + student.getId() + "   name:" + student.getName();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鼠晓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值