• springMVC 使用restful风格


    使用步骤:

      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>

      @RestController 的使用(@RestController注解相当于@ResponseBody + @Controller合在一起的作用。)

        使用 @RestController 注解 Controller,则 Controller 中的方法无法返回页面,配置的视图解析器不起作用,返回的内容就是 return 里的内容。

        如果控制器中所有方法都是返回JSON,XML或自定义mediaType内容到页面,则可以在类上加上 @RestController 注解,

        如果需要返回视图,则在类上使用@Controller注解,额外对不返回视图的方法使用@ResponseBody注解

      2.编写控制层代码

    @RestController //标记为:restful ,默认返回类型是json,通过produces改变返回类型(xml...)
    @RequestMapping("users")
    public class UserController {
       @Autowired
       UserService userService;
    
       @GetMapping("/status/check")
       public String status()
       {
          return "working";
       }
    
       @GetMapping("/{id}")
       public String getUser(@PathVariable String id)
       {
    
          return "HTTP Get was called";
       }
    
       @PostMapping("/create")
       public String createUser(@RequestBody UserDetailsRequestModel requestUserDetails)
       {
          return "HTTP POST was called";
       }
    
       @DeleteMapping("/{userId}")
       public String deleteUser(@PathVariable String userId)
       {
          return "HTTP DELETE was called";
       }
    
       @PutMapping("/{userId}")
       public String updateUser(@PathVariable String userId, @RequestBody UserDetailsRequestModel requestUserDetails)
       {
          return "HTTP PUT was called";
       }
    }

      @GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。
      @PostMapping是一个组合注解,是@RequestMapping(method = RequestMethod.POST)的缩写。

      @DeleteMapping......  @PutMapping ......  @PatchMapping ......

      3.前台页面不能发起 put、delete、patch 请求,需要把 post 请求转换成对应的请求

    <form action="${pageContext.request.contextPath}/update" method="post">
      <input type="hidden" name="_method" value="PUT"/>
      ...... </form>

     明确:必须原来是 post 请求才能转换成 put、delete、patch 请求

        如果是form表单,可以添加隐藏域 <input type="hidden" name="_method" value="PUT"/> 来实现

        超链接默认是 get 请求,无法转换成 put 或 delete,可以通过 ajax 发起请求实现

    $.ajax({
      type : 'post',
      data : {'_method':'delete','id':'1'},
      dataType : 'json',
      url : url,
      success : function(data){
        // ......
      },
      error:function(){
        // ......
    }
  • 相关阅读:
    Python多线程_thread和Threading
    Python多线程_thread和Threading
    ICMP协议
    ICMP协议
    Python中的Pexpect模块的简单使用
    Python中的Pexpect模块的简单使用
    Python中math和cmath模块的使用
    Python中math和cmath模块的使用
    Python中sys模块的使用
    Python模块化编程
  • 原文地址:https://www.cnblogs.com/roadlandscape/p/12316513.html
Copyright © 2020-2023  润新知