SpringMVC中的RestFul的使用
在URL风格中
RestFul的好处主要为简洁,高效和安全。因为在原生的URL风格中,页面传递参时,总会显示传递的属性和值。
localhost:8080/method?a=1&b=1
而RestFul则可以避免这种情况,这主要就是RestFul的安全性的体现
localhost:8080/method/1/2
在SpringMVC中RestFul有两种方式的运用,主要都是要用到**@PathVariable**注解来实现
第一种方法:
package com.leige.controler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.leige.domain.Student;
import com.leige.service.StudentService;
@Controller
public class ControllerRestFul{
//RequestMethode.可以设置RequestMapping的请求方式:get put post delet
//RequestMapping中value可以由Path代替,这两个的意义是一样的
@RequestMapping(value = "/test1/{a}/{b}",method = RequestMethod.GET)
public String test(@PathVariable int a ,@PathVariable int b ,Model model){
int c = a + b;
model.addAttribute("msg","a+b="+c);
return "test" //视图页面的地址
}
}
上面的URL格式就可以为:localhost:8080/test/test1/1/2
而页面上就能得出: a+b = 3的内容
第二种方法:
`
package com.leige.controler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.leige.domain.Student;
import com.leige.service.StudentService;
@Controller
public class ControllerRestFul{
/*不同的请求方式对应的着不同的Mapping
GetMapping
PostMapping
PutMapping
DeleteMapping
*/
@GetMapping("test2/{a}/{b}")
public String test(@PathVariable int a ,@PathVariable int b ,Model model){
int c = a + b;
model.addAttribute("msg","a+b="+c);
return "test" //视图页面的地址
}
}
第二种RestFul的抒写格式也是最简洁最多使用的方式
不同的请求方式,但要是URL格式一样,也会导致类似于重载的情况出现也就是说可以根据视图表单的请求方式不同,来走不一样的Controller方法。