20201207本周spring学习
一:controller层请求参数整理
@RequestParam
接收的是?后面拼接的参数;
注: 被@RequestParam修饰的参数是必填的,如下面的例子:
http://localhost:9001/test?name=123&pass=456 ▶▶▶ ✔
http://localhost:9001/test?name=&pass=456 ▶▶▶ ✔
http://localhost:9001/test?name=123 ▶▶▶ ✔
http://localhost:9001/test?pass=456 ▶▶▶ ✘
http://localhost:9001/test?name=123&pass=456
// 后台接收:
@GetMapping(value = "/test")
public void test(@RequestParam String name, String pass) {
System.out.println("*************name***********"+name);
System.out.println("*************pass***********"+pass);
}
@PathVariable
使用@PathVariable接收参数,参数值需要在url进行占位
http://localhost:9001/test/123
// 后台接收:
@GetMapping(value = "/test/{name}")
public void test(@PathVariable String name) {
System.out.println("*************name***********"+name);
}
@RequestBody
使用@RequestBody接收参数,前端请求方式必须是json格式;
即: Content-type:application/json
@PostMapping(value = "/payment/create")
public CommonResult save(@RequestBody Payment payment) {
int result = paymentService.insert(payment);
log.info("*****插入结果:" + result);
if (result > 0) {
return new CommonResult<>(200, "插入数据库成功", result);
} else {
return new CommonResult<>(444, "插入数据库失败");
}
}
@RequestAttribute
@RequestAttribute修饰的参数主要是从request中获取属性参数;
基本应用是从请求转发过来的,或者是filter接收处理了一下参数;
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
final HttpServletRequest req = (HttpServletRequest) servletRequest;
final String path = req.getServletPath();
if (StringUtils.isBlank(path )) {
final String[] array = path.split("\\.");
if (array.length > 1) {
//登录请求,过滤
filterChain.doFilter(servletRequest, servletResponse);
} else {
try {
getPostData(req);
} catch (Exception e) {
e.printStackTrace();
}
filterChain.doFilter(servletRequest, servletResponse);
}
}
}
//**********************getPostData 大致意思**************
//1: 先对请求路径进行过滤
final String path = req.getServletPath();
//2: 针对token进行认证
final Map<String, String> header = getHeadersInfo(req);
final String token = header.get("authorization");
//3: 统一拿到参数,放到postData中
String postData = req.getParameter("postData");
//4: 放行
//**********************后台接收(达到统一接收目的)**************
@RequestMapping("/handleLogins")
public Map<String, Object> handleLogins(@RequestAttribute String postData);