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中的方法无法返回jsp页面,配置的视图解析器不起作用,返回的内容就是 return 里的内容。

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

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

  2.编写控制层代码

@RestController //标记为:restful ,默认返回类型是json,通过produces改变返回类型
@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 ......

  3.前台页面不能发起 put 或 delete 请求,需要把 post 请求转换成 put 或 delete 请求

<form action="${pageContext.request.contextPath}/update" method="post">
  <input type="hidden" name="_method" value="PUT"/>
  ...... </form>
扫描二维码关注公众号,回复: 9194978 查看本文章

猜你喜欢

转载自www.cnblogs.com/roadlandscape/p/12316513.html