SpringMVC(三)【REST 风格】(2)

简介: SpringMVC(三)【REST 风格】

SpringMVC(三)【REST 风格】(1)https://developer.aliyun.com/article/1534212

1.3.2、标准请求动作注解

       经过上一步的简化,我们的 UserController 现在变成了这样:

@RestController
@RequestMapping("/users")
public class UserController {
 
    @RequestMapping(method = RequestMethod.POST)
    public String save(@RequestBody User user){
        System.out.println("user save,  name = " + user.getName() + " , age = " + user.getAge());
        return "{'module':'user save'}";
    }
 
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public String delete(@PathVariable Integer id){
        System.out.println("user deleted ... user id => " + id);
        return "{'module': 'user delete'}";
    }
 
    @RequestMapping(method = RequestMethod.PUT)
    public String update(@RequestBody User user){
        System.out.println("user deleted ... user => " + user.toString());
        return "{'module': 'user update'}";
    }
 
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public String getById(@PathVariable Integer id){
        System.out.println("user get ... user id => " + id);
        return "{'module': 'user get'}";
    }
 
    @RequestMapping(method = RequestMethod.GET)
    public String getAll(){
        System.out.println("user get all ...");
        return "{'module': 'user get all'}";
    }
}

       现在看起来还是很冗余,我们可以对这些方法的请求行为进行进一步简化,现在这么长的参数太扎眼了,现在我们的代码就变成了这样(把 value =  "/{param}" 和  method = RequestMethpd.X 合并到一个注解中):

@RestController
@RequestMapping("/users")
public class UserController {
 
    @PostMapping
    public String save(@RequestBody User user){
        System.out.println("user save,  name = " + user.getName() + " , age = " + user.getAge());
        return "{'module':'user save'}";
    }
 
    @DeleteMapping("/{id}")
    public String delete(@PathVariable Integer id){
        System.out.println("user deleted ... user id => " + id);
        return "{'module': 'user delete'}";
    }
 
    @PutMapping
    public String update(@RequestBody User user){
        System.out.println("user deleted ... user => " + user.toString());
        return "{'module': 'user update'}";
    }
 
    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id){
        System.out.println("user get ... user id => " + id);
        return "{'module': 'user get'}";
    }
 
    @GetMapping
    public String getAll(){
        System.out.println("user get all ...");
        return "{'module': 'user get all'}";
    }
}

显然一下子变得清新脱俗!舒服多了。

1.4、基于 RESTful 页面数据交互

实体类

package com.lyh.domain;
 
public class Book {
    private Integer id;
    private String type;
    private String name;
    private String description;
 
    public Book(){}
 
    public Book(Integer id, String type, String name, String description) {
        this.id = id;
        this.type = type;
        this.name = name;
        this.description = 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;
    }
}

SpringMVC 配置类

@Configuration
@ComponentScan("com.lyh.controller") // 扫描
@EnableWebMvc // 开启 json 转对象的功能等各种格式转换
public class SpringMvcConfig {
 
}

Sevlet 容器配置类

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};
    }
}

BookController 控制器类

@RestController
@RequestMapping("/books")
public class BookController {
 
 
    @PostMapping
    public String save(@RequestBody Book book){
        System.out.println("book save ... book => " + book.toString());
        return "{'module':'book save'}";
    }
 
    @GetMapping
    public List<Book> getAll(){
        List<Book> list = new ArrayList<Book>();
        list.add(new Book(1,"编程","《图解Spark》","大数据技术"));
        list.add(new Book(2,"小说","《黄金时代》","王小波著作"));
        return list;
    }
}

测试

       导入静态资源后访问 localhost:85/pages/boos.html 发现报错找不到映射:No Mapping for GET /pages/books.html 这是因为我们现在的请求都被 SpringMVC 拦截走了,其实这些静态资源应该是由 Tomcat 处理的。

1.4.1、放行非 SpringMVC 请求

       上面的问题是对于静态资源的访问,本该是由 Tomcat 处理,但是前面我们在 Servlet 配置类中设置了所有请求都由 SpringMVC 来响应。所以,现在我们需要通过添加一个配置类来实现放行静态资源:

@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/");
        }
}

       然后,我们需要让 SpringMVC 去加载这个新的配置类:

这样就可以访问到了:

相关文章
|
7月前
|
Web App开发 JavaScript Java
教会你什么是Spring-Rest- url 请求风格
教会你什么是Spring-Rest- url 请求风格
90 0
|
7月前
|
JSON 网络架构 数据格式
SpringMVC-REST风格简介及RESTful入门案例
SpringMVC-REST风格简介及RESTful入门案例
83 0
|
6月前
|
JSON 前端开发 Java
spring mvc Rest风格
spring mvc Rest风格
41 0
|
6月前
|
JSON Java 网络架构
SpringMVC(三)【REST 风格】
SpringMVC(三)【REST 风格】
|
7月前
|
JSON 网络架构 数据格式
SpringMVC -- REST风格开发,RESTful快速开发、RESTful注解开发
SpringMVC -- REST风格开发,RESTful快速开发、RESTful注解开发
85 2
|
7月前
|
JSON 前端开发 Java
Spring MVC响应结合RESTful风格开发,打造具有强大功能和良好体验的Web应用!
Spring MVC响应结合RESTful风格开发,打造具有强大功能和良好体验的Web应用!
|
XML JSON Java
SpringMVC与REST相结合实现RESTful风格
SpringMVC与REST相结合实现RESTful风格
126 0
|
缓存 测试技术
SpringMVC的Restful风格
SpringMVC的Restful风格
49 0
SpringMVC RestFul风格实现
在controller层中定义如下的代码,代码会获取路径上的值并返回a和b的加和: RestFul风格的路径需要使用@PathVariable注解表示变量:
166 0
SpringMVC RestFul风格实现
|
JSON 网络架构 数据格式
SpringMVC的请求与相应和REST风格
SpringMVC的请求与相应和REST风格
97 0
SpringMVC的请求与相应和REST风格