SpringMVC(二)


REST风格

REST(Representational State Transfer),表现形式状态转换

  • 传统风格资源描述形式
    http://localhost/user/getById?id=1
    http://localhost/user/saveUser

  • REST风格描述形式
    http://localhost/user/1
    http://localhost/user

优点:

隐藏资源的访问行为,无法通过地址得知对资源是何种操作。
书写简化。

按照REST风格访问资源时使用行为动作区分对资源进行了何种操作

根据REST风格对资源进行访问称为RESTful

GET方式请求代表(查询)
POST方式请求代表(新增/保存)
PUT方式请求代表(修改/更新)
DELETE方式请求代表(删除)

上述行为是约定方式,约定不是规范,可以打破,所以称REST风格,而不是REST规范

入门案例

只需要修改上一个项目。

在Controller中定义方法时设定”http请求动作(请求方式)”和”设定请求参数(路径变量)”

@Controller
public class UserController {

    //设置当前请求方法为POST,表示REST风格中的添加操作
    @RequestMapping(value = "/users",method = RequestMethod.POST)
    @ResponseBody
    public String save(){
        System.out.println("user save...");
        return "{'module':'user save'}";
    }

    //设置当前请求方法为DELETE,表示REST风格中的删除操作
    //@PathVariable注解用于设置路径变量(路径参数),要求路径上设置对应的占位符,并且占位符名称与方法形参名称相同
    @RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public String delete(@PathVariable Integer id){
        System.out.println("user delete..." + id);
        return "{'module':'user delete'}";
    }

    //设置当前请求方法为PUT,表示REST风格中的修改操作
    @RequestMapping(value = "/users",method = RequestMethod.PUT)
    @ResponseBody
    public String update(@RequestBody User user){
        System.out.println("user update..."+user);
        return "{'module':'user update'}";
    }

    //设置当前请求方法为GET,表示REST风格中的查询操作
    //@PathVariable注解用于设置路径变量(路径参数),要求路径上设置对应的占位符,并且占位符名称与方法形参名称相同
    @RequestMapping(value = "/users/{id}" ,method = RequestMethod.GET)
    @ResponseBody
    public String getById(@PathVariable Integer id){
        System.out.println("user getById..."+id);
        return "{'module':'user getById'}";
    }

    //设置当前请求方法为GET,表示REST风格中的查询操作
    @RequestMapping(value = "/users",method = RequestMethod.GET)
    @ResponseBody
    public String getAll(){
        System.out.println("user getAll...");
        return "{'module':'user getAll'}";
    }
}

@RequestBody @RequestParam @PathVariable三者关系

  • 区别
    @RequestParam用于接收url地址传参或表单传参
    @RequestBody用于接收json数据
    @PathVariable用于接收路径参数,使用{参数名称}描述路径参数

  • 应用
    后期开发中,发送请求参数超过1个时,以json格式为主,@RequestBody应用较广
    如果发送非json格式数据,选用@RequestParam接收请求参数
    采用RESTful进行开发,当参数数量较少时,例如1个,可以采用@PathVariable接收请求路径变量,通常用于传递id值

RESTful快速开发

在上述入门案例中,

这个两个部分重复性太高。

解决方法:

  • 在Controller类上使用@RequestMapping定义共同的访问路径。

  • 使用@GetMapping @PostMapping @PutMapping @DeleteMapping代替@RequestMapping(method=RequestMethod.XXX)

  • 在Controller类上使用@RestController注解,等同于@Controller与@ResponseBody两个注解组合功能

代码示例:

在BookController类中

@RestController
@RequestMapping("/books")
public class BookController2 {

    @PostMapping
    public String save(@RequestBody Book book){
        System.out.println("book save..." + book);
        return "{'module':'book save'}";
    }

    @DeleteMapping("/{id}")
    public String delete(@PathVariable Integer id){
        System.out.println("book delete..." + id);
        return "{'module':'book delete'}";
    }

    @PutMapping
    public String update(@RequestBody Book book){
        System.out.println("book update..."+book);
        return "{'module':'book update'}";
    }

    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id){
        System.out.println("book getById..."+id);
        return "{'module':'book getById'}";
    }

    @GetMapping
    public String getAll(){
        System.out.println("book getAll...");
        return "{'module':'book getAll'}";
    }
}

RESTful页面数据交互案例

没有数据持久化层

案例结构

Config文件夹下:

public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    protected Class<?>[] getRootConfigClasses() {
        return new Class[0];
    }

    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    //乱码处理
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        return new Filter[]{filter};
    }
}




@Configuration
@ComponentScan({"com.yang.controller", "com.yang.config"})
@EnableWebMvc
public class SpringMvcConfig {
}





@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
    //设置静态资源访问过滤,当前类需要设置为配置类,并被扫描加载
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        //当访问/pages/????时候,从/pages目录下查找内容
        registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
    }
}

BookController类

@RestController
@RequestMapping("/books")
public class BookController {

    @PostMapping
    public String save(@RequestBody Book book){
        System.out.println("book save ==> "+ book);
        return "{'module':'book save success'}";
    }

    @GetMapping
    public List<Book> getAll(){
        System.out.println("book getAll is running ...");
        List<Book> bookList = new ArrayList<Book>();

        Book book1 = new Book();
        book1.setType("计算机");
        book1.setName("数据库");
        book1.setDescription("小牛");
        bookList.add(book1);

        Book book2 = new Book();
        book2.setType("计算机");
        book2.setName("操作系统");
        book2.setDescription("小马");
        bookList.add(book2);

        Book book3 = new Book();
        book3.setType("计算机");
        book3.setName("计算机网络");
        book3.setDescription("小鼠");
        bookList.add(book3);

        return bookList;
    }

}

Book类(主要是获取数据):

public class Book {
    private Integer id;
    private String type;
    private String name;
    private String description;

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", type='" + type + '\'' +
                ", name='" + name + '\'' +
                ", description='" + description + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

还要用到axios进行交互

methods: {
               // 重置表单
               resetForm() {
                   //清空输入框
                   this.formData = {};
               },

               // 弹出添加窗口
               openSave() {
                   this.dialogFormVisible = true;
                   this.resetForm();
               },

               //添加
               saveBook () {
                   axios.post("/books",this.formData).then((res)=>{

                   });
               },

               //主页列表查询
               getAll() {
                   axios.get("/books").then((res)=>{
                       this.dataList = res.data;
                   });
               },

           }

文章作者: 小小星仔
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小小星仔 !
评论
  目录