RestFul风格:
对比图
原来风格:
@Controller
public class HelloController {
// 原来的风格:http://localhost:8080/hello?a=2&b=3
@RequestMapping("/hello")
public String hello( int a, int b, Model md)
{
int res = a+b;
md.addAttribute("msg","你好世界"+res);
return "test";
}
}
输入栏输入:
http://localhost:8080/hello?a=2&b=3
现在风格:
@Controller
public class HelloController {
@RequestMapping("/hello/{a}/{b}")
public String hello(@PathVariable int a, @PathVariable int b, Model md)
{
int res = a+b;
md.addAttribute("msg","你好世界"+res);
return "test";
}
}
地址栏输入:
http://localhost:8080/hello/15/8 结果为:你好世界23
@PathVariable路径变量接收请求路径中占位符的值,这里指的是a与b的值
restful风格改变请求方式:
第一种手动配置:
里面包括了五种请求方式:
第二种注解方式:
@Controller
public class HelloController {
@GetMapping(value = "/hello/{a}/{b}")
public String hello1(@PathVariable int a, @PathVariable int b, Model md)
{
int res = a+b;
md.addAttribute("msg","你好01:"+res);
return "test";
}
@PostMapping(value = "/hello/{a}/{b}")
public String hello2(@PathVariable int a, @PathVariable int b, Model md)
{
int res = a+b;
md.addAttribute("msg","你好02:"+res);
return "test";
}
}
与此同时,当再次请求的:http://localhost:8080/hello/2/3的时候, 结果为:你好015,走的是 hello1这个方法,说明通过地址栏输入访问的时候,是get请求
再次创建一个jsp表单用form表单,利用post方法请求
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="/hello/8/6" method="post">
<input type="submit" value="提交">
</form>
</body>
</html>
输入栏结果为:http://localhost:8080/hello/8/6 页面结果为: 你好02:14
restful最大的好处一个是方便简洁,一个是安全,隐藏了一些关键代码