SpringMVC的REST风格的四种请求方式总结

网友投稿 243 2023-04-13


SpringMVC的REST风格的四种请求方式总结

一、 在HTTP 协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。

它们分别对应四种基本操作:

1、GET ====== 获 取资源

  2、POST ======新建资源

  3、PUT======= 更新资源

  4、DELETE==== 删除资源

二、REST:即 Representational State Transfer。(资源)表现层状态转化。是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、扩展方便, 所以正得到越来越多网站的采用。

我们可以通过rest风格占位符方式,利用@PathVariable注解将占位符的值赋给调用方法参数,实现结果:

/某路径/1 HTTP GET : 得到 id = 1 的 一条数据

/某路径/1 HTTP DELETE: 删除 id = 1的 一条数据

/某路径/1   HTTP PUT: 更新id = 1的 一条数据

/某路径 HTTP POST: 新增一条数据

实现方式(REST风格四种请求方式的调用):

我们通过@RequestMapping映射请求中的method参数实现四种请求方式的调用,以下为示例代码。

GET请求:

@RequestMapping(value="/student",method=RequestMethod.GET)

public ModelAndView toAddPage(){

ModelAndView mView=new ModelAndView();

mView.addObject("employee",new Employee());

mView.setViewName("add-stu");

mView.addObject("departments", departmentDao.getDepartments());

return mView;

}

POST请求:

@RequestMapping(value="/student",method=RequestMethod.POST)

public String addStu(Employee employee){

employeeDao.save(employee);

return "redirect:/show" ;

}

DELETE请求:

@RequestMapping(value="/student/{id}",method=RequestMethod.DELETE)

public String deleteStu(@PathVariable(value="id") Integer id){

employeeDao.delete(id);

return "redirect:/show" ;

}

PUT请求:

@RequestMapping(value="/student",method=RequestMethod.PUT)

public String Update(@RequestParam(value="id")Integer id,Employee employee){

employeeDao.save(employee);

return "redirect:/show" ;

}

三、将POST请求转化为put请求和delele请求

1.在web.xml文件中配置HiddenHttpMethodFilter过滤器:

  

   hiddenHttpMethodFilter

   org.springframework.web.filter.HiddenHttpMethodFilter

  

  

   hiddenHttpMethodFilter

   /*

  

2.在表单域中需要携带一个name值为_method,PqqtMSFuHvalue值为put或者delete的参数,如下所示:

姓名:

姓名:

邮箱:

<%

Mapmap=new HashMap();

map.put("1","Male");

map.put("0", "Female");

request.setAttribute("genders", map);

%>

性别:

部门:

最后在Controller层调用即可。根据@RequestMapping的value值以及携带的参数、请求方式查找匹配函数。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:es6学习之解构时应该注意的点
下一篇:使用canvas进行图像编辑的实例
相关文章

 发表评论

暂时没有评论,来抢沙发吧~