SpringMVC学习笔记4-----RestFul风格简单解读

5.RestFul风格

restFul风格的好处:

  • 使路径变的更加简洁,
  • 获得参数更加方便,框架会自动进行类型转换。
  • 通过路径变量的类型可以进行约束访问参数,如果类型不一致,则访问不到对应的请求方法,如果访问的路径是/commit/1/a,则路径与方法不匹配,而不是参数转换失败。
  • 安全,原来的提交方式会暴露提交的参数。

原来的地址栏传参:

原来的http://localhost:8080/add?a=1&b=2

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;


@Controller
public class RestFulController {
    
    

    @RequestMapping("/add")
    public String test1(int a, int b, Model model) {
    
    
        int result=a+b;
        model.addAttribute("msg","a+b="+result);
        return "test";
    }
}

通过?号将a=1,b=2传入其中,在地址栏有暴露,不安全。

restFul风格传参

传递两个int

http://localhost:8080/add/6/71

通过获取路径变量,来进行传递获取的参数,

  • 在方法上要加上**@PathVariable**
  • 在@RequestMapping()上,要加/add/{a}/{b}

就将第一个6,传递给a,71就传递给b。

@RequestMapping("/add/{a}/{b}")
public String test2(@PathVariable int a,@PathVariable int b, Model model){
    
    
    int result=a+b;
    model.addAttribute("msg","这是restful传参a+b="+result);
    return "test";
}

传递一个int一个String

http://localhost:8080/add/3/wang

@RequestMapping("/add/{a}/{b}")
public String test2(@PathVariable int a,@PathVariable String b, Model model){
    
    
    String result=a+b;
    model.addAttribute("msg","这是restful传参a+b="+result);
    return "test";
}

结果为:

这是restful传参a+b=3wang

当传入/3/4时,结果为34.表示最后的4是字符串拼接在后面。

自定义提交的方式

方式一,@RequestMapping,method来定义
@RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.DELETE)
public String test2(@PathVariable int a,@PathVariable String b, Model model){
    
    
    String result=a+b;
    model.addAttribute("msg","这是restful传参a+b="+result);
    return "test";
}

注意

这里网页默认的提交方式是GET,(可以通过F12,抓包查看)

我们设置为只能DELETE方式,所以会报一个405错误。

​ - HTTP Status 405 - Request method ‘GET’ not supported

当修改为GET之后。输入

http://localhost:8080/add/4/as

结果为:

这是restful传参a+b=4as

可以传递成功。

方式二,@GetMapping,
@GetMapping//查询
@PostMapping//新增
@PutMapping//更新
@RequestMapping
。。。。还有很多

在地址栏相同的情况下,可以通过请求的方式不同,最后的结果也不相同。

案例:

//http://localhost:8080/add/2/as
    //test2=2as
    @GetMapping("/add/{a}/{b}")
    public String test2(@PathVariable int a,@PathVariable String b, Model model){
    
    
        String result=a+b;
        model.addAttribute("msg","test2="+result);
        return "test";
    }

    //通过a.jsp的post提交。http://localhost:8080/add/2/as
    //test3=2as
    @PostMapping("/add/{a}/{b}")
    public String test3(@PathVariable int a,@PathVariable String b, Model model){
    
    
        String result=a+b;
        model.addAttribute("msg","test3="+result);
        return "test";
    }

第一个采用默认的get提交,第二个使用自己建立网页的post提交,通过请求方式的不同,走了两天路径,在地址栏上显示是一样的,实现了地址栏的复用。

猜你喜欢

转载自blog.csdn.net/weixin_45263852/article/details/115101462