美文网首页
Spring MVC-Rest

Spring MVC-Rest

作者: 石头耳东 | 来源:发表于2022-04-25 08:38 被阅读0次

前置文章:
一、Spring MVC-简单使用
二、Spring MVC-请求与响应

零、本文纲要

  • 一、Rest简介
    1、对比传统风格与Rest风格
    2、RESTful
  • 二、Rest快速入门
    1、基础准备
    2、@PathVariable注解
    3、@RestController注解
    4、@XXXMapping注解
  • 三、页面访问处理
    1、存在问题
    2、静态资源放行

一、Rest简介

Rest全称为Representational State Transfer,翻译为表现形式状态转换,它是一种软件架构。

1、对比传统风格与Rest风格

  • ① 传统风格资源描述形式

http://localhost/user/getById?id=1 查询id为1的用户信息;

http://localhost/user/save 保存用户信息。

  • ② REST风格描述形式

http://localhost/user/1 查询id为1的用户信息;

http://localhost/user保存用户信息。

  • ③ 两者对比

Ⅰ 传统URL有一定可读性,但是信息也容易被他人识别。

Ⅱ Rest风格则隐藏资源的访问行为,无法通过地址得知对资源是何种操作,而且书写简洁。

2、RESTful

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

RESTful.png

二、Rest快速入门

1、基础准备

  • ① 添加依赖
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.0</version>
  <scope>provided</scope>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>5.2.10.RELEASE</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.0</version>
</dependency>
  • ② 添加tomcat插件
<build>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.1</version>
        <configuration>
          <port>80</port>
          <path>/</path>
        </configuration>
      </plugin>
    </plugins>
</build>
  • ③ 编写配置类
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[]{"/"}; // 所有路径由SpringMVC管理
    }

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

@Configuration
@ComponentScan("com.stone.controller")
@EnableWebMvc //开启json数据类型自动转换
public class SpringMvcConfig {
}
  • ④ 编写Book类
public class Book {
    private String name;
    private double price;
    ... ...
}
  • ⑤ 编写Controller类
@RestController //@Controller + ReponseBody
@RequestMapping("/books")
public class BookController {
    
    //@RequestMapping(method = RequestMethod.POST)
    @PostMapping
    public String save(@RequestBody Book book){
        System.out.println("book save..." + book);
        return "{'module':'book save'}";
    }

    //@RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    @DeleteMapping("/{id}")
    public String delete(@PathVariable Integer id){
        System.out.println("book delete..." + id);
        return "{'module':'book delete'}";
    }

    //@RequestMapping(method = RequestMethod.PUT)
    @PutMapping
    public String update(@RequestBody Book book){
        System.out.println("book update..." + book);
        return "{'module':'book update'}";
    }

    //@RequestMapping(value = "/{id}",method = RequestMethod.GET)
    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id){
        System.out.println("book getById..." + id);
        return "{'module':'book getById'}";
    }

    //@RequestMapping(method = RequestMethod.GET)
    @GetMapping
    public String getAll(){
        System.out.println("book getAll...");
        return "{'module':'book getAll'}";
    }
    
}

2、@PathVariable注解

  • ① 作用

使用在形参位置,绑定路径参数与处理器方法形参间的关系,要求路径参数名与形参名一一对应。

如:

请求URL为:http://localhost/boosk/1,则参数接收如下:

@GetMapping("/{id}") // 指定参数在URL中的所在位置
public String getById(@PathVariable Integer id){ // 绑定参数与形参
    System.out.println("book getById..." + id);
    return "{'module':'book getById'}";
}
  • @RequestBody@RequestParam@PathVariable区别于应用

  • 区别

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

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

3、@RestController注解

  • ① 作用

使用在类上,设置当前控制器类为RESTful风格。

相当于:@Controller + @ResponseBody

4、@XXXMapping注解

  • ① 作用

使用在方法上,设置当前控制器方法请求访问路径与请求动作,每种对应一个请求动作。

  • ② 注解分类

常用的有:@GetMapping、@PostMapping、@PutMapping、@DeleteMapping。

@RequestMapping(value = "/{id}",method = RequestMethod.GET)

@GetMapping("/{id}") // 效果等同于上面的注解配置

三、页面访问处理

同样的问题在Spring Boot自定义静态资源映射也讨论过,此处处理方案即为SpringMVC的处理方案。

1、存在问题

访问路径:http://localhost/pages/books.html,如果直接访问会报错。

原因:因为所有的请求路径"/"由SpringMVC管理,如下:

protected String[] getServletMappings() {
    return new String[]{"/"}; // 所有路径由SpringMVC管理
}

2、静态资源放行

  • ① 添加继承抽象类WebMvcConfigurationSupport的配置类
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
    //设置静态资源访问过滤,当前类需要设置为配置类,并被扫描加载
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        //当访问/pages/xx时候,从/pages目录下查找内容,下同
        registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
    }
}
  • ② 扫描该配置类,以生效

添加细分的扫描范围、或者增大扫描范围均可,如下:

@Configuration
@ComponentScan({"com.stone.controller","com.stone.config"}) // 添加细分扫描范围
@EnableWebMvc
public class SpringMvcConfig {
}

@Configuration
@ComponentScan("com.stone") // 增大扫描范围
@EnableWebMvc
public class SpringMvcConfig {
}

四、结尾

以上即为Spring MVC-Rest的全部内容,感谢阅读。

相关文章

网友评论

      本文标题:Spring MVC-Rest

      本文链接:https://www.haomeiwen.com/subject/daeaertx.html