一:什么是SpringMVC
SpringMVC是一个基于Java实现了MVC设计模式的请求驱动类型的轻量级web框架,通过把模型--视图--控制器分离,将web层进行职责解耦,把复杂的web运用分成逻辑清晰的几部分,简化开发,减少出错,方便组内成员的配合
二:SpringMVC快速入门
1.导入依赖
创建Maven项目,并导入对应的jar包,在pom.xml文件中导入以下两个依赖
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.31</version> </dependency>
2.创建核心配置类
在src包下创建两个包,分别为config包和controller包
在config包下创建SpringMvcConfig核心配置类
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration//表示为一个配置类 @ComponentScan("com.lcyy")//扫描包 public class SpringMvcConfig { //创建一个视图解析器到IOC容器中去 @Bean public InternalResourceViewResolver internalResourceViewResolver(){ InternalResourceViewResolver resolver = new InternalResourceViewResolver(); //设置视图的前缀 resolver.setPrefix("/pages/"); //设置后缀 resolver.setSuffix(".jsp"); return resolver; } }
在创建ServletConfig类
import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer; public class ServletConfig extends AbstractDispatcherServletInitializer { //加载springmvc配置,放到IOC容器中去 @Override protected WebApplicationContext createServletApplicationContext() { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(SpringMvcConfig.class); return ctx; } //配置tomcat需要接收到的哪些资源 @Override protected String[] getServletMappings() { return new String[]{"/"}; } //加载spring配置 @Override protected WebApplicationContext createRootApplicationContext() { return null; } }
3.创建controller关键类
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class UserController { //访问的是视图 @RequestMapping("/save") public String save(){ return "success"; } /** * @ResponseBody 添加这个注解表示为在视图显示json字符串 * @return */ @RequestMapping("/save2") @ResponseBody public String save2(){ return "hello"; } }
4.创建访问的资源
在webapp下创建pages包,在包下创建名为:success.jsp的jsp文件
<%-- Created by IntelliJ IDEA. User: 22818 Date: 2024/5/12 Time: 13:23 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> hello 我是Springmvc </body> </html>
5.配置tomcat
6.浏览器测试
运行tomcat,在浏览器输入localhost:8080/save 和 localhost:8080/save2,对应的结果分别如下:
7.解决中文乱码问题:
在ServletConfig类下,重写getServletFilters()方法(此为过滤器),定义编码格式为utf-8
/** * 解决中文乱码问题,使用过滤器(输入(服务器向外发送为输入)) * @return */ @Override protected Filter[] getServletFilters() { CharacterEncodingFilter filter = new CharacterEncodingFilter(); //设置为utf-8 filter.setEncoding("utf-8"); //返回过滤器 return new Filter[]{filter}; }
三:测试工具:Postman
1.软件介绍:
1. Postman 是一款功能超级强大的用于发送 HTTP 请求的 测试工具
2. 做 WEB 页面开发和测试的人员常用工具
3. 创建和发送任何的 HTTP 请求 (Get/Post/Put/Delete...)
2.测试请求数据
Get请求:
2.1:普通参数—参数名相同
/** * 普通参数--参数相同(get) * @param name * @param age * @return */ @RequestMapping("/commonParam") @ResponseBody public String commonParam(String name,Integer age){ System.out.println("name = " + name); System.out.println("age = " + age); return "success"; }
2.2参数为字符串数组
/** * 参数为字符串数组(get请求) * @param hobby * @return */ @RequestMapping("/arrayParam") @ResponseBody public String arrayParam(String[] hobby){ //封装到数组里 System.out.println("hobby = " + Arrays.toString(hobby)); return "success"; }
2.3参数为字符串集合
/** * 参数为字符串集合(get)需添加@RequestParam * @param hobby * @return */ @RequestMapping("/listParam") @ResponseBody public String listParam(@RequestParam List<String> hobby){ System.out.println("hobby = " + hobby); return "success"; }
2.4日期类型
/** * 日期格式 * @param date * @param date1 * @return */ @RequestMapping("/dateParam") @ResponseBody public String dateParam(Date date, @DateTimeFormat(pattern = "yyyy-MM-dd") Date date1) { System.out.println("date = " + date); System.out.println("date1 = " + date1); return "success"; }
Post请求:
2.5普通参数—参数名相同
/** * 普通参数--参数相同(get) * @param name * @param age * @return */ @RequestMapping("/commonParam") @ResponseBody public String commonParam(String name,Integer age){ System.out.println("name = " + name); System.out.println("age = " + age); return "success"; }
2.6普通参数—参数名不同
/** * 普通参数--形参名不同,起别名 * @param username * @param age * @return 返回给前端 */ @RequestMapping("/commonParamDifferentName") @ResponseBody public String commonParamDifferentName(@RequestParam("name") String username, Integer age){ System.out.println("username = " + username); System.out.println("age = " + age); return "success"; }
2.7参数为实体类型
/** * 参数为pojo(实体类)类型(post) * @param u * @return 返回给前端 */ @RequestMapping("/pojoParam") @ResponseBody public String pojoParam(User u){ //封装为了实体类 System.out.println("user = " + u); return "success"; }
2.8参数为实体类型嵌套实体类
/** * pojo嵌套使用(post) * @param u * @return */ @RequestMapping("/pojoContainPojoParam") @ResponseBody public String pojoContainPojoParam(User u){ //封装为了实体类 System.out.println("user = " + u); return "success"; }
2.9JSON数组—字符串数组接收,集合接收
/** * 理论上get请求可以发送json数据,但一般用post请求发送json数据 * @param hobby * @return */ @RequestMapping("/jsonArray") @ResponseBody public String jsonArray(@RequestBody List<String> hobby){ System.out.println("hobby = " + hobby); return "success"; } /**请求 * JSON对象数组,用pojo实体集合接收 * @param list * @return */ @RequestMapping("/listPojoParamForJson") @ResponseBody public String listPojoParamForJson(@RequestBody List<User> list){ System.out.println("list = " + list); return "success"; }
2.10JSON对象—实体类接收
/** * 请求 * @param user * @return */ @RequestMapping("/pojoParamForJson") @ResponseBody public String pojoParamForJson(@RequestBody User user){ System.out.println("user = " + user); return "success"; }
2.11JSON对象数组—实体类集合接收
/**请求 * JSON对象数组,用pojo实体集合接收 * @param list * @return */ @RequestMapping("/listPojoParamForJson") @ResponseBody public String listPojoParamForJson(@RequestBody List<User> list){ System.out.println("list = " + list); return "success"; }
3.测试响应数据
3.1POJO转JSON字符串
/** * 响应:JSON转字符串,响应给前端 * @param user * @return */ @RequestMapping("/toJson") @ResponseBody public User toJson(User user){ User user1 = new User(); user1.setName("张三"); user1.setAge(18); user1.setAddress(new Address("广州省·","深圳市")); return user1; }
3.2POJO集合转JSON数组
/**响应 *pojo集合转json数组 * @param * @return */ @RequestMapping("/toJsonList") @ResponseBody public List<User> toJsonList(){ List<User> users = new ArrayList<>(); User user1 = new User(); User user = user1; user.setName("张三"); user.setAge(25); user.setAddress(new Address("陕西省","西安市")); User user2 = new User(); user2.setName("李四"); user2.setAge(20); user2.setAddress(new Address("陕西省","安康市")); User user3 = new User(); user3.setName("李非"); user3.setAge(21); user3.setAddress(new Address("陕西省","汉中市")); users.add(user); users.add(user2); users.add(user3); return users; }