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

下面小编就为大家带来一篇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,value值为put或者delete的参数,如下所示:

 
   姓名:
姓名:
邮箱:
<% Mapmap=new HashMap(); map.put("1","Male"); map.put("0", "Female"); request.setAttribute("genders", map); %> 性别:
部门:

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

以上就是SpringMVC的REST风格的四种请求方式总结的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java