zoukankan      html  css  js  c++  java
  • SpringMVC Rest风格

    对资源的操作,基本都不外乎增删改查4个操作

      传统风格:http://i.cnblogs.com/element/add?id=1

           http://i.cnblogs.com/element/update?id=1

           http://i.cnblogs.com/element/delete?id=1

           http://i.cnblogs.com/element/get?id=1

      使用起来繁琐,而且当操作多的时候,起url名字也会变的困难,Rest风格就是来解决这个问题的

      比如我要对一号元素做增删改查的操作

      我只需要url写成http://i.cnblogs.com/element/1  然后通过请求方法的不同  例如:get、post、delete、put等来区别是增删改查中的哪个操作

      具体代码如下:

    @Controller
    public class RestController {
    
        @RequestMapping(value = "book/{id}" ,method = RequestMethod.GET)
        public String query(Model model, @PathVariable int id){
    
            model.addAttribute("msg","查询"+id+"号图书");
            return "restFul";
        }
    
        @RequestMapping(value = "book/{id}" ,method = RequestMethod.DELETE)
        public String delete(Model model, @PathVariable int id){
    
            model.addAttribute("msg","删除"+id+"号图书");
            return "restFul";
        }
    
        @RequestMapping(value = "book/{id}" ,method = RequestMethod.PUT)
        public String update(Model model, @PathVariable int id){
    
            model.addAttribute("msg","更新"+id+"号图书");
            return "restFul";
        }
    
        @RequestMapping(value = "book/{id}" ,method = RequestMethod.POST)
        public String add(Model model, @PathVariable int id){
    
            model.addAttribute("msg","添加"+id+"号图书");
            return "restFul";
        }
    
    }

    现在问题就剩下 如何让前端.jsp页面发送不同的请求,有以下几步

      1)、在web.xml文件中写好 过滤器   

    <filter>
            <filter-name>HiddenHttpMethodFilter</filter-name>
            <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
            <filter-name>HiddenHttpMethodFilter</filter-name>
            <url-pattern>/*</url-pattern>
    </filter-mapping>

      2)、在.jsp页面中区分好提交请求    

    <form action="book/1" method="post">
            <input type="submit" value="添加1号图书">
        </form>
    
        <form action="book/1" method="post">
          <label>
            <input name="_method" value="delete">
          </label>
          <input type="submit" value="删除1号图书">
        </form>

     注意:tomcat8.0 及以上版本会报异常

      需要在.jsp文件中加入  isErrorPage="true"

  • 相关阅读:
    Celery详解
    JWT详解
    进程及进程池
    多线程详解
    python常用模块之os模块的用法
    python常用模块之paramiko与ssh
    reflect 反射
    http 静态文件
    模板渲染语言
    http web 开发
  • 原文地址:https://www.cnblogs.com/lxy-java/p/12876370.html
Copyright © 2011-2022 走看看