关于SpringMVC学习的第二天(第三部分:RestFul)

RestFul就是改变浏览器的url。

原来的浏览器url :http://localhost:8080/add?a=1&b=2
RestFul浏览器url :http://localhost:8080/add/a/b
现在RestFul比较流行,比如百度百科。

@Controller
public class RestFulController {

    //原来的浏览器url     :http://localhost:8080/add?a=1&b=2
    @RequestMapping("/add")
    public String test1(int a, String b, Model model) {
        String res = a + b;
        model.addAttribute("msg", "结果为:" + res);
        return "test";
    }

    //RestFul浏览器url   :http://localhost:8080/add/a/b

    // 可以指定方法GET,POST,PUT,DELETE,以下两种方式是一致的,而POST,PUT,DELETE也如此
    // @RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.GET)
    // @GetMapping("/add/{a}/{b}")

    @RequestMapping("/add/{a}/{b}")
    public String test2(@PathVariable int a, @PathVariable String b, Model model) {
        String res = a + b;
        model.addAttribute("msg", "结果为:" + res);
        return "test";
    }

    /*
    一:
        浏览器url为:http://localhost:8080/add/1/2
        输出结果为(注意参数一个是int,一个是String)
                get结果为:12(匹配的是get)
        假设浏览器url使用的是get方法,以下两个方法请求地址一致,但会自动匹配第二个,也就是正确那个

    二:
        如下的提交为post
        
浏览器url为:http://localhost:8080/add/1/2 输出结果为(注意参数一个是int,一个是String) post结果为:12(匹配的是post) 三:可以发现上面两种url一样,但走的是不一样的方法 */
@PostMapping("/add/{a}/{b}") public String test3(@PathVariable int a, @PathVariable String b, Model model) { String res = a + b; model.addAttribute("msg", "post结果为:" + res); return "test"; } @GetMapping("/add/{a}/{b}") public String test4(@PathVariable int a, @PathVariable String b, Model model) { String res = a + b; model.addAttribute("msg", "get结果为:" + res); return "test"; }

你可能感兴趣的:(java,web,spring)