4.0、springmvc-Restful风格的实现
前端url 携带参数格式如下:
'/add/'+a+'/'+b
RestfulController.java文件
package com.hkl.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class RestfulController {
@GetMapping("/add/{a}/{b}")
public String add(@PathVariable int a, @PathVariable int b, Model model) {
int msg = a + b;
model.addAttribute("msg",msg);
return "hello";
}
@PostMapping("/add/{a}/{b}")
public String add2(@PathVariable int a, @PathVariable int b, Model model) {
int msg = a + b;
model.addAttribute("msg",msg);
return "hello";
}
}
使用Restful风格编码的优点:
·代码简洁
·代码高效
·代码安全性得到提升
使用时注意一下几点即可:
·在方法上加上@GetMapping注解即表示该方法通过Get的方式访问@PostMapping则表示
post方式访问。当然还有其他几种访问的方式但是使用的最多的就是Get和Post方式。也可以使用
@RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.POST)这种方式来设置访问方式。
·@PathVariable表示路径变量,在方法的形参前加上该注解,即可使用"/add/{a}/{b}"这种方
式来传递参数,这样在前端页面的url路径中不会暴露代码的参数是什么,安全性大大提高。