springmvc 梳理11--restful

更详细:http://www.ruanyifeng.com/blog/2011/09/restful.html

package com.xinzhi.controller;

import com.alibaba.fastjson.JSONObject;
import com.xinzhi.entity.User;
import com.xinzhi.util.R;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sr
 * @date 2021/1/25
 */
@Controller
@RequestMapping("/user")
public class UserController {




    @PostMapping
    @ResponseBody
    public R addUser(User user) throws Exception {
    //模型里封装数据
        try {
            System.out.println("---------保存用户---------");
        }catch (Exception e){
            e.printStackTrace();
            return R.fail().put("detail","id为( " + user.getId() +" )的用户保存失败!");
        }

        return R.success();
    }





    @DeleteMapping( value = "/{id}")
    @ResponseBody
    public R deleteUser(@PathVariable  int id) throws Exception {
       //@PathVariable会从  @RequestMapping( value = "/{id} /{name}")  里面找{}
        System.out.println("----------删除--调用dao层删除即可------" + id);
        return R.success();
    }





    @PutMapping( "/{id}")
    @ResponseBody
    public R updateUser(@PathVariable int id) throws Exception {
        System.out.println("------修改用户---调用service----" + id);
        return R.success();
    }




    @GetMapping("/{id}")
    @ResponseBody
    public R redirect(@PathVariable int id){
        System.out.println("---------查询用户----------" + id);
        //:是外部的,/是访问本工程的
        User user =  new User(id,"sunrui","password");
        return R.success().put("data",user);
    }

}

user.http

GET http://localhost:8080/user/1
Accept: application/json

###
POST http://localhost:8080/user
Content-Type: application/x-www-form-urlencoded

id=12&username=sunrui&password=123456

###
PUT http://localhost:8080/user/1
Content-Type: application/json

{
  "id":1,
  "username":"sunrui",
  "password": "123"
}

###
DELETE http://localhost:8080/user/1
Accept: application/json

ajax

待补充

原文地址:https://www.cnblogs.com/Master-Sun/p/14334339.html