SpringMVC框架有什么优点?
在Controller中如何定义访问路径,如何响应数据?
1 创建web工程(Maven结构)
2 设置tomcat服务器,加载web工程(tomcat插件)
3 导入坐标(SpringMVC+Servlet)
4 定义处理请求的功能类(UserController)
5 编写SpringMVC配置类,加载处理请求的Bean。
6 加载SpringMVC配置,并设置SpringMVC请求拦截的路径
org.apache.tomcat.maven tomcat7-maven-plugin 2.1 80 /
javax.servlet javax.servlet-api 3.1.0 provided org.springframework spring-webmvc 5.2.10.RELEASE
注意事项:
//定义表现层控制器bean
@Controller
public class UserController {//设置映射路径为/save,即外部访问路径@RequestMapping("/save")//设置当前操作返回结果为指定json数据(本质上是一个字符串信息)@ResponseBodypublic String save(){System.out.println("user save ...");return "{'info':'springmvc'}";}
}
注意事项:
对于SpringMVC而言,Controller方法返回值默认表示要跳转的页面,没有对应的页面就会报错。如果不想跳转页面而是响应数据,那么就需要在方法上使用@ResponseBody注解。
//springmvc配置类,本质上还是一个spring配置类
@Configuration
@ComponentScan("com.itheima.controller")
public class SpringMvcConfig {
}
//web容器配置类
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {//加载springmvc配置类,产生springmvc容器(本质还是spring容器)protected WebApplicationContext createServletApplicationContext() {//初始化WebApplicationContext对象AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();//加载指定配置类ctx.register(SpringMvcConfig.class);return ctx;}//设置由springmvc控制器处理的请求映射路径protected String[] getServletMappings() {return new String[]{"/"};}//加载spring配置类protected WebApplicationContext createRootApplicationContext() {return null;}
}
@Controller
public class UserController {
}
@RequestMapping("/save")
public void save(){System.out.println("user save ...");
}
注意:其实@RequestMapping注解还可以写到类上面,笔记后面会介绍到。
@RequestMapping("/save")
@ResponseBody
public String save(){System.out.println("user save ...");return "{'info':'springmvc'}";
}
AbstractDispatcherServletInitializer类是SpringMVC提供的快速初始化Web3.0容器的抽象类
AbstractDispatcherServletInitializer提供三个接口方法供用户实现
//加载springmvc配置类,产生springmvc容器(本质还是spring容器)
protected WebApplicationContext createServletApplicationContext() {AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();ctx.register(SpringMvcConfig.class);return ctx;
}
//设置由springmvc控制器处理的请求映射路径
protected String[] getServletMappings() {return new String[]{"/"};
}
//加载spring配置类
protected WebApplicationContext createRootApplicationContext() {return null;
}
因为功能不同,如何避免Spring错误的加载到SpringMVC的bean?
SpringMVC相关bean(表现层bean)
Spring控制的bean
业务bean(Service)
功能bean(DataSource等)
SpringMVC相关bean加载控制
Spring相关bean加载控制
@Configuration
@ComponentScan(value = "com.itheima",excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = Controller.class))
public class SpringConfig {
}
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer { protected WebApplicationContext createServletApplicationContext() { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();ctx.register(SpringMvcConfig.class);return ctx; } protected WebApplicationContext createRootApplicationContext() { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(SpringConfig.class); return ctx; } protected String[] getServletMappings() { return new String[]{"/"}; }
}
简化格式
public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer{protected Class>[] getServletConfigClasses() {return new Class[]{SpringMvcConfig.class}};protected String[] getServletMappings() {return new String[]{"/"};}protected Class>[] getRootConfigClasses() {return new Class[]{SpringConfig.class};}
}
Postman是一款功能强大的网页调试与发送网页HTTP请求的Chrome插件。
作用:常用于进行接口测试
特征
双击资料中的“Postman-win64-8.3.1-Setup.exe”即可自动按照,打开之后需要注册,如果底部有如下链接,可以点击跳过注册
注意:第一次请求需要创建一个新的目录,后面就不需要创建新目录,直接保存到已经创建好的目录即可。
@RequestMapping注解注解可以写在哪?有什么作用?
@Controller
//类上方配置的请求映射与方法上面配置的请求映射连接在一起,形成完整的请求映射路径
@RequestMapping("/user")
public class UserController {//请求路径映射@RequestMapping("/save") //此时save方法的访问路径是:/user/save@ResponseBodypublic String save(){System.out.println("user save ...");return "{'module':'user save'}";}
}
如何解决POST请求中文乱码问题?
//普通参数:请求参数与形参名称对应即可完成参数传递
@RequestMapping("/commonParam")
@ResponseBody
public String commonParam(String name ,int age){System.out.println("普通参数传递 name ==> "+name);System.out.println("普通参数传递 age ==> "+age);return "{'module':'common param'}";
}
org.apache.tomcat.maven tomcat7-maven-plugin 2.1 80 / UTF-8
//普通参数:请求参数与形参名称对应即可完成参数传递
@RequestMapping("/commonParam")
@ResponseBody
public String commonParam(String name ,int age){System.out.println("普通参数传递 name ==> "+name);System.out.println("普通参数传递 age ==> "+age);return "{'module':'common param'}";
}
问题:我们发现,POST请求传递的参数如果包含中文那么就会出现中文乱码问题,说明我们之前配置的tomcat插件uri路径编解码字符集无法解决POST请求中文乱码问题。那么如何解决呢?
在加载SpringMVC配置的配置类中指定字符过滤器。
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[]{"/"};}//乱码处理@Overrideprotected Filter[] getServletFilters() {CharacterEncodingFilter filter = new CharacterEncodingFilter();filter.setEncoding("UTF-8");return new Filter[]{filter};}
}
当请求参数名与形参变量名不同,该如何接收请求参数?
//普通参数:请求参数名与形参名不同时,使用@RequestParam注解关联请求参数名称与形参名称之间的关系
@RequestMapping("/commonParamDifferentName")
@ResponseBody
public String commonParamDifferentName(@RequestParam("name") String userName , int age){System.out.println("普通参数传递 userName ==> "+userName);System.out.println("普通参数传递 age ==> "+age);return "{'module':'common param different name'}";
}
public class User {private String name;private int age;//同学们自己添加getter/setter/toString()方法
}
//POJO参数:请求参数与形参对象中的属性对应即可完成参数传递
@RequestMapping("/pojoParam")
@ResponseBody
public String pojoParam(User user){System.out.println("pojo参数传递 user ==> "+user);return "{'module':'pojo param'}";
}
注意事项:请求参数key的名称要和POJO中属性的名称一致,否则无法封装。
public class User {private String name;private int age;private Address address;//同学们自己添加getter/setter/toString()方法
}
public class Address {private String province;private String city;private Address address;
}
//嵌套POJO参数:嵌套属性按照层次结构设定名称即可完成参数传递
@RequestMapping("/pojoContainPojoParam")
@ResponseBody
public String pojoContainPojoParam(User user){System.out.println("pojo嵌套pojo参数传递 user ==> "+user);return "{'module':'pojo contain pojo param'}";
}
注意事项:请求参数key的名称要和POJO中属性的名称一致,否则无法封装。
//数组参数:同名请求参数可以直接映射到对应名称的形参数组对象中
@RequestMapping("/arrayParam")
@ResponseBody
public String arrayParam(String[] likes){System.out.println("数组参数传递 likes ==> "+ Arrays.toString(likes));return "{'module':'array param'}";
}
//集合参数:同名请求参数可以使用@RequestParam注解映射到对应名称的集合对象中作为数据
@RequestMapping("/listParam")
@ResponseBody
public String listParam(@RequestParam List likes){System.out.println("集合参数传递 likes ==> "+ likes);return "{'module':'list param'}";
}
问题:@EnableWebMvc注解和@ResponseBody注解有什么用?
com.fasterxml.jackson.core jackson-databind 2.9.0
@Configuration
@ComponentScan("com.itheima.controller")
//开启json数据类型自动转换
@EnableWebMvc
public class SpringMvcConfig {
}
注意事项:
@EnableWebMvc注解功能强大,该注解整合了多个功能,此处仅使用其中一部分功能,即json数据进行自动类型转换
//集合参数:json格式
//1.开启json数据格式的自动转换,在配置类中开启@EnableWebMvc
//2.使用@RequestBody注解将外部传递的json数组数据映射到形参的集合对象中作为数据
@RequestMapping("/listParamForJson")
@ResponseBody
public String listParamForJson(@RequestBody List likes){System.out.println("list common(json)参数传递 list ==> "+likes);return "{'module':'list common for json param'}";
}
@Configuration
@ComponentScan("com.itheima.controller")
@EnableWebMvc
public class SpringMvcConfig {
}
@RequestMapping("/listParamForJson")
@ResponseBody
public String listParamForJson(@RequestBody List likes){System.out.println("list common(json)参数传递 list ==> "+likes);return "{'module':'list common for json param'}";
}
//POJO参数:json格式
//1.开启json数据格式的自动转换,在配置类中开启@EnableWebMvc
//2.使用@RequestBody注解将外部传递的json数据映射到形参的实体类对象中,要求属性名称一一对应
@RequestMapping("/pojoParamForJson")
@ResponseBody
public String pojoParamForJson(@RequestBody User user){System.out.println("pojo(json)参数传递 user ==> "+user);return "{'module':'pojo for json param'}";
}
//集合参数:json格式
//1.开启json数据格式的自动转换,在配置类中开启@EnableWebMvc
//2.使用@RequestBody注解将外部传递的json数组数据映射到形参的保存实体类对象的集合对象中,要求属性名称一一对应
@RequestMapping("/listPojoParamForJson")
@ResponseBody
public String listPojoParamForJson(@RequestBody List list){System.out.println("list pojo(json)参数传递 list ==> "+list);return "{'module':'list pojo for json param'}";
}
@DateTimeFormat注解的作用是什么?
//日期参数 http://localhost:80/dataParam?date=2088/08/08&date1=2088-08-18&date2=2088/08/28 8:08:08
//使用@DateTimeFormat注解设置日期类型数据格式,默认格式yyyy/MM/dd
@RequestMapping("/dataParam")
@ResponseBody
public String dataParam(Date date,@DateTimeFormat(pattern="yyyy-MM-dd") Date date1,@DateTimeFormat(pattern="yyyy/MM/dd HH:mm:ss") Date date2){System.out.println("参数传递 date ==> "+date);System.out.println("参数传递 date1(yyyy-MM-dd) ==> "+date1);System.out.println("参数传递 date2(yyyy/MM/dd HH:mm:ss) ==> "+date2);return "{'module':'data param'}";
}
名称:@DateTimeFormat
类型:形参注解
位置:SpringMVC控制器方法形参前面
作用:设定日期时间型数据格式
属性:pattern:指定日期时间格式字符串
public interface Converter {@NullableT convert(S var1);
}
传递日期类型参数必须在配置类上使用@EnableWebMvc注解。其功能之一:根据类型匹配对应的类型转换器。
如何响应json数据?
@Controller
public class UserController {//响应页面/跳转页面//返回值为String类型,设置返回值为页面名称,即可实现页面跳转@RequestMapping("/toJumpPage")public String toJumpPage(){System.out.println("跳转页面");return "page.jsp";}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title Hello Spring MVC!
//响应文本数据
//返回值为String类型,设置返回值为任意字符串信息,即可实现返回指定字符串信息,需要依赖@ResponseBody注解
@RequestMapping("/toText")
@ResponseBody
public String toText(){System.out.println("返回纯文本数据");return "response text";
}
//响应POJO对象
//返回值为实体类对象,设置返回值为实体类类型,即可实现返回对应对象的json数据,需要依赖@ResponseBody注解和@EnableWebMvc注解
@RequestMapping("/toJsonPOJO")
@ResponseBody
public User toJsonPOJO(){System.out.println("返回json对象数据");User user = new User();user.setName("itcast");user.setAge(15);return user;
}
//响应POJO集合对象
//返回值为集合对象,设置返回值为集合类型,即可实现返回对应集合的json数组数据,需要依赖@ResponseBody注解和@EnableWebMvc注解
@RequestMapping("/toJsonList")
@ResponseBody
public List toJsonList(){System.out.println("返回json集合数据");User user1 = new User();user1.setName("传智播客");user1.setAge(15);User user2 = new User();user2.setName("黑马程序员");user2.setAge(12);List userList = new ArrayList();userList.add(user1);userList.add(user2);return userList;
}
注意:需要添加jackson-databind依赖以及在SpringMvcConfig配置类上添加@EnableWebMvc注解
Rest风格使用了几种请求方式定义访问行为?
Rest风格如何通过路径传递参数?
做法:在Controller中定义方法时设定"http请求动作(请求方式)“和"设定请求参数(路径变量)”
@Controller
public class UserController {//设置当前请求方法为POST,表示REST风格中的添加操作@RequestMapping(value = "/users",method = RequestMethod.POST)@ResponseBodypublic String save(){System.out.println("user save...");return "{'module':'user save'}";}//设置当前请求方法为DELETE,表示REST风格中的删除操作//@PathVariable注解用于设置路径变量(路径参数),要求路径上设置对应的占位符,并且占位符名称与方法形参名称相同@RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)@ResponseBodypublic String delete(@PathVariable Integer id){System.out.println("user delete..." + id);return "{'module':'user delete'}";}//设置当前请求方法为PUT,表示REST风格中的修改操作@RequestMapping(value = "/users",method = RequestMethod.PUT)@ResponseBodypublic 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)@ResponseBodypublic String getById(@PathVariable Integer id){System.out.println("user getById..."+id);return "{'module':'user getById'}";}//设置当前请求方法为GET,表示REST风格中的查询操作@RequestMapping(value = "/users",method = RequestMethod.GET)@ResponseBodypublic String getAll(){System.out.println("user getAll...");return "{'module':'user getAll'}";}
}
以上截图中的代码和我们之前写的UserController中的方法类似,其中图中两个方法都有三处是有问题的,可以进行优化。存在的问题如下:
问题1:每个方法的@RequestMapping注解中都定义了访问路径/books,重复性太高。
问题2:每个方法的@RequestMapping注解中都要使用method属性定义请求方式,重复性太高。
问题3:每个方法响应json都需要加上@ResponseBody注解,重复性太高。
解决以上三个问题
解决问题1:在Controller类上使用@RequestMapping定义共同的访问路径。
@Controller
@RequestMapping("/books")
public class BookController {@RequestMapping(method = RequestMethod.POST)public String save(@RequestBody Book book){System.out.println("book save..." + book);return "{'module':'book save'}";}@RequestMapping(value = "/{id}" ,method = RequestMethod.DELETE)public String delete(@PathVariable Integer id){System.out.println("book delete..." + id);return "{'module':'book delete'}";}@RequestMapping(method = RequestMethod.PUT)public String update(@RequestBody Book book){System.out.println("book update..."+book);return "{'module':'book update'}";}@RequestMapping(value = "/{id}" ,method = RequestMethod.GET)public String getById(@PathVariable Integer id){System.out.println("book getById..."+id);return "{'module':'book getById'}";}@RequestMapping(method = RequestMethod.GET)public String getAll(){System.out.println("book getAll...");return "{'module':'book getAll'}";}
}
解决问题2:使用@GetMapping @PostMapping @PutMapping @DeleteMapping代替@RequestMapping(method=RequestMethod.XXX)
@Controller
@RequestMapping("/books")
public class BookController {// @RequestMapping( method = RequestMethod.POST)@PostMapping//使用@PostMapping简化Post请求方法对应的映射配置public String save(@RequestBody Book book){System.out.println("book save..." + book);return "{'module':'book save'}";}// @RequestMapping(value = "/{id}" ,method = RequestMethod.DELETE)@DeleteMapping("/{id}") //使用@DeleteMapping简化DELETE请求方法对应的映射配置public String delete(@PathVariable Integer id){System.out.println("book delete..." + id);return "{'module':'book delete'}";}// @RequestMapping(method = RequestMethod.PUT)@PutMapping //使用@PutMapping简化Put请求方法对应的映射配置public String update(@RequestBody Book book){System.out.println("book update..."+book);return "{'module':'book update'}";}// @RequestMapping(value = "/{id}" ,method = RequestMethod.GET)@GetMapping("/{id}") //使用@GetMapping简化GET请求方法对应的映射配置public String getById(@PathVariable Integer id){System.out.println("book getById..."+id);return "{'module':'book getById'}";}// @RequestMapping(method = RequestMethod.GET)@GetMapping //使用@GetMapping简化GET请求方法对应的映射配置public String getAll(){System.out.println("book getAll...");return "{'module':'book getAll'}";}
}
解决问题3:在Controller类上使用@RestController注解,等同于@Controller与@ResponseBody两个注解组合功能
@RestController //使用@RestController注解替换@Controller与@ResponseBody注解,简化书写
@RequestMapping("/books")
public class BookController {//方法省略了没写
}
//POJO实体类
public class Book {private Integer id;private String type;private String name;private String description;//同学们自己重写getter、setter、toString()方法...
}//SpringMVC容器初始化类
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[]{"/"};}//乱码处理@Overrideprotected Filter[] getServletFilters() {CharacterEncodingFilter filter = new CharacterEncodingFilter();filter.setEncoding("UTF-8");return new Filter[]{filter};}
}//SpringMVC配置类
@Configuration
@ComponentScan({"com.itheima.controller","com.itheima.config"})
@EnableWebMvc
public class SpringMvcConfig {
}
@RestController
@RequestMapping("/books")
public class BookController {@PostMappingpublic String save(@RequestBody Book book){System.out.println("book save ==> "+ book);return "{'module':'book save success'}";}@GetMappingpublic List getAll(){System.out.println("book getAll is running ...");List bookList = new ArrayList();Book book1 = new Book();book1.setType("计算机");book1.setName("SpringMVC入门教程");book1.setDescription("小试牛刀");bookList.add(book1);Book book2 = new Book();book2.setType("计算机");book2.setName("SpringMVC实战教程");book2.setDescription("一代宗师");bookList.add(book2);Book book3 = new Book();book3.setType("计算机丛书");book3.setName("SpringMVC实战教程进阶");book3.setDescription("一代宗师呕心创作");bookList.add(book3);return bookList;}
}
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {//设置静态资源访问过滤,当前类需要设置为配置类,并被扫描加载@Overrideprotected 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/");}
}
//添加
saveBook () {axios.post("/books",this.formData).then((res)=>{});
},
//主页列表查询
getAll() {axios.get("/books").then((res)=>{this.dataList = res.data;});
},
Name(“SpringMVC实战教程”);
book2.setDescription(“一代宗师”);
bookList.add(book2);
Book book3 = new Book();book3.setType("计算机丛书");book3.setName("SpringMVC实战教程进阶");book3.setDescription("一代宗师呕心创作");bookList.add(book3);return bookList;
}
}
[外链图片转存中...(img-cemtGstB-1670169587608)]##### 4.2.2 设置对静态资源的访问放行```java
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {//设置静态资源访问过滤,当前类需要设置为配置类,并被扫描加载@Overrideprotected 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/");}
}
//添加
saveBook () {axios.post("/books",this.formData).then((res)=>{});
},
//主页列表查询
getAll() {axios.get("/books").then((res)=>{this.dataList = res.data;});
},