Restful 风格路由
1. 配置类
1.1、SpringMvcConfig配置类
java
@Configuration
@ComponentScan({"com.itheima.controller", "com.itheima.config"}) 方式1.2 添加com.itheima.config 扫描目录
@EnableWebMvc
public class SpringMvcConfig {
}
1.2、ServletContainerInitConfig类
java
public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[0];
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
// 乱码处理 过滤器
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
return new Filter[]{filter};
}
}
1.3、SpringMvcSupport配置类
java
@Configuration //方式1.1 添加Configuration注解
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
// 当访问 /pages的时候 ,走pages目录下访问 不要走mvc
registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
}
}
- 这个类的主要作用 添加静态资源排除,让这些路径 不会进入SpringMvc动态请求里面
2. 控制器
2.1、 Restful 风格 增删改查
java
@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(){
Book book1 = new Book();
book1.setType("计算机");
book1.setName("SpringMVC入门教程");
book1.setDescription("小试牛刀");
Book book2 = new Book();
book2.setType("计算机");
book2.setName("SpringMVC项目实战");
book2.setDescription("一代总是");
List<Book> bookList = new ArrayList<>();
bookList.add(book1);
bookList.add(book2);
return bookList;
}
@DeleteMapping("/{id}")
public String delete(@PathVariable Integer id){
System.out.println("book delete id = "+ id);
return "{'module':'book delete success'}";
}
@PutMapping
public String update(@RequestBody Book book){
System.out.println("book update book = "+ book);
return "{'module':'book update success'}";
}
}
-
@RestController 声明为Rest风格控制器
-
@RequestMapping("/books") 路径
-
@PostMapping Post请求
-
@GetMapping Get请求
-
@DeleteMapping("/{id}") Delete请求
-
@PutMapping Put请求
-
Json格式参数必须加上@ReqeustBody 注解