01-Restful风格查询用户(掌握)
-
需求
- 根据id查询用户
-
分析
http://localhost:8080/day23/user/selectUserById?id=1 : GET请求 http://localhost:8080/day23/user/1 : GET请求
-
代码实现
<a th:href="@{/user/1}">selectUserById</a>
@GetMapping("/user/{userId}") public String selectUserById(@PathVariable Integer userId){ System.out.println("userId = " + userId); return "index"; }
02-Restful风格删除用户(掌握)
-
需求
- 根据id删除用户
-
分析
http://localhost:8080/day23/user/deleteUserById?userId=1 : POST请求 http://localhost:8080/day23/user/1 : DELETE请求
-
代码实现
<div id="app"> <!--02-Restful风格删除用户--> <form method="post" id="deleteUserById"> <input type="hidden" name="_method" value="delete"> </form> <a th:href="@{/user/1}" @click.prevent="deleteUserById()">deleteUserById</a> </div> </body> <script th:src="@{/js/vue.js}"></script> <script> var vue = new Vue({ el: "#app", data: {}, methods: { deleteUserById(){ var formEle = document.getElementById("deleteUserById"); var href = event.target.href; formEle.action = href; formEle.submit(); } } }) </script>
@DeleteMapping("/user/{userId}") public String deleteUserById(@PathVariable Integer userId) { System.out.println("deleteUserById userId = " + userId); return "index"; }
03-Restful风格添加用户(掌握)
-
需求
- 添加用户
-
分析
http://localhost:8080/day23/user/addUser?userName=liaoxurui&userPwd=250 : POST请求 http://localhost:8080/day23/user?userName=liaoxurui&userPwd=250 : POST请求
-
代码实现
<form th:action="@{/user}" method="post"> 账户:<input type="text" name="userName" ><br> 密码:<input type="text" name="userPwd"><br> <button type="submit">addUser</button> </form>
@PostMapping("/user") public String addUser(String userName , String userPwd){ System.out.println("addUser userName = " + userName); System.out.println("addUser userPwd = " + userPwd); return "index"; }
04-Restful风格登录功能(掌握)
-
需求
- 用户登录功能
-
分析
http://localhost:8080/day23/user/login?userName=root&userPwd=root : POST请求 http://localhost:8080/day23/user/login?userName=root&userPwd=root : POST请求
-
代码实现
<form th:action="@{/user/login}" method="post"> 账户:<input type="text" name="userName" ><br> 密码:<input type="text" name="userPwd"><br> <button type="submit">login</button> </form>
@PostMapping("/user/login") public String login(String userName , String userPwd){ System.out.println("login userName = " + userName); System.out.println("login userPwd = " + userPwd); return "index"; }
05-Restful风格修改用户功能(掌握)
-
需求
- 修改用户
-
分析
http://localhost:8080/day23/user/updateUser?userId=1&userName=root&userPwd=root : POST请求 http://localhost:8080/day23/user?userId=1&userName=root&userPwd=root : PUT请求
-
代码实现
<form th:action="@{/user}" method="post"> <input type="hidden" name="_method" value="put"> <input type="hidden" name="userId" value="1"> 账户:<input type="text" name="userName" ><br> 密码:<input type="text" name="userPwd"><br> <button type="submit">updateUser</button> </form>
@PutMapping("/user") public String updateUser(Integer userId , String userName , String userPwd) { System.out.println("updateUser userId = " + userId); System.out.println("updateUser userName = " + userName); System.out.println("updateUser userPwd = " + userPwd); return "index"; }
06-SpringMVC获取AJAX发送的普通参数(掌握)
-
概述
- SpringMVC接收异步请求发送的普通参数(键值对)
-
代码实现
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>AJAX请求</title> </head> <body> <div id="app"> <form @submit.prevent="updateUser()"> <input type="hidden" v-model="user.userId"> 账户:<input type="text" v-model="user.userName"><br> 密码:<input type="text" v-model="user.userPwd"><br> <button>发送普通参数</button> </form> </div> </body> <script th:src="@{/js/vue.js}"></script> <script th:src="@{/js/axios.js}"></script> <script> var vue = new Vue({ el: "#app", data: { user: { userId: 1 } }, methods: { updateUser() { axios({ method: "put", url: "/day23/ajax/updateUser", params: { userId: this.user.userId, userName: this.user.userName, userPwd: this.user.userPwd } }).then(function (res) { console.log(res); }) } } }) </script> </html>
@PutMapping("/ajax/updateUser") public String updateUser(User user){ System.out.println("updateUser user = " + user); return "index"; }
07-SpringMVC获取AJAX发送的请求体json(掌握)
-
@RequestBody
- ①获取请求体
- ②将json字符串转换为javabean对象
-
代码实现
updateUser2(){ axios({ method: "put", url: "/day23/ajax/updateUser4", data: { userId: this.user.userId, userName: this.user.userName, userPwd: this.user.userPwd } }).then(function (res) { console.log(res); }) }
@PutMapping("/ajax/updateUser2") public String updateUser2(HttpServletRequest request) throws IOException { //①获取请求体 BufferedReader reader = request.getReader(); StringBuilder sb = new StringBuilder(); String content = null; while ((content = reader.readLine()) != null) { sb.append(content); } String jsonStr = sb.toString(); //②将json字符串转换为javabean对象 User user = new ObjectMapper().readValue(jsonStr, User.class); System.out.println("updateUser2 user = " + user); return "index"; } @PutMapping("/ajax/updateUser3") public String updateUser3(@RequestBody String jsonStr) throws IOException { //①获取请求体 //②将json字符串转换为javabean对象 User user = new ObjectMapper().readValue(jsonStr, User.class); System.out.println("updateUser3 user = " + user); return "index"; } /** * 推荐 */ @PutMapping("/ajax/updateUser4") public String updateUser4(@RequestBody User user) throws IOException { //①获取请求体 //②将json字符串转换为javabean对象 System.out.println("updateUser4 user = " + user); return "index"; }
08-SpringMVC响应json字符串(掌握)
-
@ResponseBody
- ①将javabean对象转换为json字符串
- ②将json字符串作为响应正文返回
- ③解决响应正文中文乱码问题
-
代码实现
@PutMapping("/ajax/updateUser5") public void updateUser5(@RequestBody User user, HttpServletResponse response) throws IOException { //①获取请求体 //②将json字符串转换为javabean对象 System.out.println("updateUser4 user = " + user); //①将javabean对象转换为json字符串 response.setContentType("application/json;charset=utf-8"); String jsonStr = new ObjectMapper().writeValueAsString(new ResultVO<>(true, "修改成功!", null)); //②将json字符串作为响应正文返回 response.getWriter().write(jsonStr); } @ResponseBody @PutMapping("/ajax/updateUser6") public String updateUser6(@RequestBody User user, HttpServletResponse response) throws IOException { //①获取请求体 //②将json字符串转换为javabean对象 System.out.println("updateUser4 user = " + user); //①将javabean对象转换为json字符串 String jsonStr = new ObjectMapper().writeValueAsString(new ResultVO<>(true, "修改成功!", null)); //②将json字符串作为响应正文返回 return jsonStr; } /** * 推荐 */ @ResponseBody @PutMapping("/ajax/updateUser7") public ResultVO updateUser7(@RequestBody User user, HttpServletResponse response) throws IOException { //①获取请求体 //②将json字符串转换为javabean对象 System.out.println("updateUser4 user = " + user); //①将javabean对象转换为json字符串 //②将json字符串作为响应正文返回 return new ResultVO<>(true,"修改成功!",null); }
09-SpringMVC异常处理概述(掌握)
- 概述
- 一个项目中会包含很多个模块,各个模块需要分工完成。如果张三负责的模块按照 A 方案处理异常, 李四负责的模块按照 B 方法处理异常……各个模块处理异常的思路、代码、命名细节都不一样,那么 就会让整个项目非常混乱。
- 将异常类型和某个具体的视图关联起来,建立映射关系。可以通过 SpringMVC 框架来帮助我们管理 异常。
- 好处
- 让异常控制和核心业务解耦,二者各自维护,结构性更好
- 整个项目层面使用同一套规则来管理异常
10-注解开发异常处理器(掌握)
-
概述
- 使用@ControllerAdvice, @ExceptionHandler这两个注解来处理异常.
- @ControllerAdvice用于标注异常处理类
- @ExceptionHandler用于标注异常处理方法
- 使用@ControllerAdvice, @ExceptionHandler这两个注解来处理异常.
-
代码实现
@ControllerAdvice public class MyExceptionAdvice { @ExceptionHandler(ArithmeticException.class) public String handleArithmeticException(Exception e, Model model) { model.addAttribute("errorMsg", e.getMessage()); return "error"; } @ExceptionHandler(NullPointerException.class) public String handleNullPointerException(Exception e , Model model){ model.addAttribute("errorMsg", "空指针异常!"); return "error"; } }
@Controller public class ExceptionController { /** * 10-注解开发异常处理器 * * @return */ @RequestMapping("/exception/test1") public String test1() { //System.out.println(1 / 0); String msg = null; System.out.println(msg.length()); return "index"; } }
11-SpringMVC异常处理解决方案(掌握)
-
概述
- 项目开发过程中,会有很多种异常产生,如果单独对每个异常进行处理,代码会非常麻烦,且维护起 来也非常繁琐,所以,此时应该对异常进行分类。
-
异常分类
- 业务异常 : 用户行为(规范/不规范)产生的异常
- 系统异常 : 项目运行过程中可预计且无法避免的异常
-
解决方案
- 业务异常 : 发送对应消息传递给用户,提醒规范操作
- 系统异常 : 发送对应消息传递给用户 , 安抚用户;发送对应消息传递给开发人员;记录日志
-
开发步骤
- ①自定义业务异常,系统异常
- ②编写MyExceptionAdvice
- ③代码测试
-
代码实现
public class MyBusinessException extends RuntimeException { public MyBusinessException() { super(); } public MyBusinessException(String message) { super(message); } public MyBusinessException(String message, Throwable cause) { super(message, cause); } public MyBusinessException(Throwable cause) { super(cause); } protected MyBusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
public class MySystemException extends RuntimeException { public MySystemException() { super(); } public MySystemException(String message) { super(message); } public MySystemException(String message, Throwable cause) { super(message, cause); } public MySystemException(Throwable cause) { super(cause); } protected MySystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
@ControllerAdvice public class MyExceptionAdvice { @ExceptionHandler(MyBusinessException.class) public String handleBusinessException(Exception e, Model model) { //提醒用户规范操作 model.addAttribute("errorMsg", e.getMessage()); return "error"; } @ExceptionHandler(MySystemException.class) public String handleSystemException(Exception e , Model model){ //安抚用户,发送消息给开发人员,记录日志 model.addAttribute("errorMsg", e.getMessage()); return "error"; } }
@RequestMapping("/exception/test2") public String test2(int num){ if (num == 1) { //num=1 : 产生了业务异常 throw new MyBusinessException("您的操作不规范!"); } else if (num == 2){ //num=2 : 产生了系统异常 throw new MySystemException("网络出现故障,请稍后再试!"); } return "index"; }
12-Spring,SpringMVC,MyBatis整合(掌握)
-
开发步骤
- ①引入依赖
- ②整合spring,mybatis : mapper接口代理开发
- 编写spring-core.xml
- 扫描注解
- 配置MapperScannerConfigurer,加载dao接口代理对象
- 配置SqlSessionFactoryBean对象
- 注入configLocation,加载mybatis-config.xml
- 注入dataSource
- 配置DruidDataSource对象
- 注入driverClassName , url , username , password
- 编写mybatis-config.xml
- 配置别名
- 编写spring-core.xml
- ③整合SpringMVC
- 编写web.xml
- 配置DispatcherServlet
- 加载spring-mvc.xml
- 配置ContextLoaderListener
- 加载spring-core.xml
- 配置DispatcherServlet
- 编写spring-mvc.xml
- 扫描注解
- 配置HandlerAdapter,HandlerMapping…
- 放行静态资源
- 配置ThymeleafViewResolver
- 编写web.xml
- ④代码测试
-
①引入依赖
<properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> <servlet.version>4.0.1</servlet.version> <jsp.version>2.3.3</jsp.version> <thymeleaf.version>3.0.12.RELEASE</thymeleaf.version> <spring.version>5.3.9</spring.version> <lombok.version>1.18.20</lombok.version> <slf4j.version>1.7.30</slf4j.version> <logback.version>1.2.5</logback.version> <hibernate-validator.version>7.0.1.Final</hibernate-validator.version> <fileupload.version>1.4</fileupload.version> <mybatis-spring.version>2.0.6</mybatis-spring.version> <druid.version>1.2.6</druid.version> <mybatis.version>3.5.7</mybatis.version> <mysql.version>5.1.48</mysql.version> </properties> <dependencies> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${fileupload.version}</version> </dependency> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>${hibernate-validator.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet.version}</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>${jsp.version}</version> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>${thymeleaf.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> </dependencies>
-
②整合spring,mybatis
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.atguigu"></context:component-scan> <!--加载dao接口代理对象--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.atguigu.dao"></property> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--加载mybatis-config.xml--> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <property name="dataSource" ref="dataSource"></property> </bean> <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${driverClassName}"></property> <property name="url" value="${jdbcUrl}"></property> <property name="username" value="${user}"></property> <property name="password" value="${password}"></property> </bean> </beans>
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <package name="com.atguigu.pojo"/> </typeAliases> </configuration>
-
③整合SpringMVC
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-core.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <!-- <param-value>classpath:spring-*.xml</param-value>--> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.atguigu"></context:component-scan> <mvc:annotation-driven></mvc:annotation-driven> <mvc:default-servlet-handler></mvc:default-servlet-handler> <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver"> <property name="order" value="1"/> <property name="characterEncoding" value="UTF-8"/> <property name="templateEngine"> <bean class="org.thymeleaf.spring5.SpringTemplateEngine"> <property name="templateResolver"> <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver"> <!--视图前缀--> <property name="prefix" value="/WEB-INF/pages/"/> <!--视图后缀--> <property name="suffix" value=".html"/> <property name="templateMode" value="HTML5"/> <property name="characterEncoding" value="UTF-8"/> </bean> </property> </bean> </property> </bean> <!-- <import resource="classpath:spring-core.xml"></import>--> </beans>
-
④代码测试
13-两个Spring容器的问题(掌握)
- 两个Spring容器
- ①ContextLoaderListener调用ContextLoader的initWebApplicationContext方法初始化Spring容器
- 创建的Spring容器对象存放到ServletContext中,名称为:“org.springframework.web.context.WebApplicationContext.ROOT”
- 父容器
- ②DispatcherServlet调用FrameworkServlet的initWebApplicationContext方法初始化Spring容器
- 创建的Spring容器对象存放到ServletContext中,名称为:"
org.springframework.web.servlet.FrameworkServlet.CONTEXT.mvc" - 子容器
- 创建的Spring容器对象存放到ServletContext中,名称为:"
- ①ContextLoaderListener调用ContextLoader的initWebApplicationContext方法初始化Spring容器
14-两个Spring容器重复创建对象问题(掌握)
-
代码实现
<!--spring-core.xml--> <context:component-scan base-package="com.atguigu"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
<!--spring-mvc.xml--> <context:component-scan base-package="com.atguigu" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>