【后台】搭建环境
一、环境搭建总体目标
二、创建工程
(1) 项目架构图
(2) 项目创建计划
atcrowdfunding01-admin-parent
groupId:com.atguigu.crowd
artifactId:atcrowdfunding01-admin-parent
packaging:pom
atcrowdfunding02-admin-webui
groupId:com.atguigu.crowd
artifactId:atcrowdfunding02-admin-webui
packaging:war
atcrowdfunding03-admin-component
groupId:com.atguigu.crowd
artifactId:atcrowdfunding03-admin-component
packaging:jar
atcrowdfunding04-admin-entity
groupId:com.atguigu.crowd
artifactId:atcrowdfunding04-admin-entity
packaging:jar
atcrowdfunding05-common-util
groupId:com.atguigu.crowd
artifactId:atcrowdfunding05-common-util
packaging:jar
atcrowdfunding06-common-reverse
groupId:com.atguigu.crowd
artifactId:atcrowdfunding06-common-reverse
packaging:jar
(3) 详细步骤
① 创建Empty Project
File -> New -> Project -> Empty Project
② 创建 各个module
参照 项目创建计划
③ 添加工程之间的依赖
然后添加依赖代码,例如 在 component 的 pom.xml 中添加 entity依赖
<dependency>
<artifactId>atcrowdfunding04-admin-entity</artifactId>
<groupId>com.atguigu.crowd</groupId>
<version>1.0-SNAPSHOT</version>
</dependency>
三、创建数据库和数据库表
(1) 创建数据库
CREATE DATABASE `project_crowd` CHARACTER SET utf8;
(2) 创建管理员数据库表
use project_crowd;
drop table if exists t_admin;
create table t_admin
(
id int not null auto_increment, # 主键
login_acct varchar(255) not null, # 登录账号
user_pswd char(32) not null, # 登录密码
user_name varchar(255) not null, # 昵称
email varchar(255) not null, # 邮件地址
create_time char(19), # 创建时间
primary key (id)
);
四、基于 Maven 的 MyBatis 逆向工程
(1) pom配置
在 atcrowdfunding06-common-reverse 的 pom.xml 文件中
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!-- 控制 Maven 在构建过程中相关配置 -->
<build>
<!-- 构建过程中用到的插件 -->
<plugins>
<!-- 具体插件, 逆向工程的操作是以构建过程中插件形式出现的 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.0</version>
<!-- 插件的依赖 -->
<dependencies>
<!-- 逆向工程的核心依赖 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.2</version>
</dependency>
<!-- MySQL 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.8</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
(2) 创建 generatorConfig.xml
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- mybatis-generator:generate -->
<context id="atguiguTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释true:是;false:否-->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码-->
<jdbcConnection
driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3307/project_crowd"
userId="root"
password="123456">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和NUMERIC 类型解析为Integer,为true 时把
JDBC DECIMAL
和NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成Entity 类的路径-->
<javaModelGenerator targetProject=".\src\main\java"
targetPackage="com.atguigu.crowd.entity">
<!-- enableSubPackages:是否让schema 作为包的后缀-->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格-->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:XxxMapper.xml 映射文件生成的路径-->
<sqlMapGenerator targetProject=".\src\main\java"
targetPackage="com.atguigu.crowd.mapper">
<!-- enableSubPackages:是否让schema 作为包的后缀-->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:Mapper 接口生成的位置-->
<javaClientGenerator type="XMLMAPPER"
targetProject=".\src\main\java"
targetPackage="com.atguigu.crowd.mapper">
<!-- enableSubPackages:是否让schema 作为包的后缀-->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 数据库表名字和我们的entity 类对应的映射指定-->
<table tableName="t_admin" domainObjectName="Admin" />
</context>
</generatorConfiguration>
★ 遇到的问题:
“http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd” 飘红
(3) 执行逆向生成操作的Maven 命令
如果maven里看不到上面这个,可以换一种给方法
(4) 逆向工程生成的资源各归各位
生成的资源
归位
五、父工程依赖管理
(1) 版本声明
<properties>
<!-- 声明属性,对Spring 的版本进行统一管理-->
<atguigu.spring.version>4.3.20.RELEASE</atguigu.spring.version>
<!-- 声明属性,对SpringSecurity 的版本进行统一管理-->
<atguigu.spring.security.version>4.2.10.RELEASE</atguigu.spring.security.version>
</properties>
(2) 依赖管理
<dependencyManagement>
<dependencies>
<!-- Spring 依赖 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${atguigu.spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${atguigu.spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${atguigu.spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
<!-- 数据库依赖 -->
<!-- MySQL 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.3</version>
</dependency>
<!-- 数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.31</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!-- MyBatis 与 Spring 整合 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- MyBatis 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.0.0</version>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- 其他日志框架的中间转换包 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>1.7.25</version>
</dependency>
<!-- Spring 进行 JSON 数据转换依赖 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.8</version>
</dependency>
<!-- JSTL 标签库 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- junit 测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- 引入 Servlet 容器中相关依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- JSP 页面使用的依赖 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1.3-b06</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<!-- SpringSecurity 对 Web 应用进行权限管理 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.10.RELEASE</version>
</dependency>
<!-- SpringSecurity 配置 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.10.RELEASE</version>
</dependency>
<!-- SpringSecurity 标签库 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>4.2.10.RELEASE</version>
</dependency>
</dependencies>
</dependencyManagement>
六、Spring 整合MyBatis
(1) 思路
(2) 操作步骤详解
① 在子工程中加入搭建环境所需的具体依赖
子工程:选择component 工程。原因是具体依赖和component 工程相关。
<!-- Spring依赖 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
</dependency>
<!-- 数据库依赖 -->
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<!-- MyBatis与Spring整合 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
<!-- MyBatis分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<!-- 其他日志框架的中间转换包 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</dependency>
<!-- Spring进行JSON数据转换依赖 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<!-- JSTL标签库 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- 引入Servlet容器中相关依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
② 数据库连接信息
jdbc.user=root
jdbc.password=123456
jdbc.url=jdbc:mysql://localhost:3307/project_crowd?useUnicode=true&characterEncoding=UTF-8
jdbc.driver=com.mysql.jdbc.Driver
③ mybatis-config.xml
<?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>
</configuration>
④ 创建spring-persist-mybatis.xml
⑤ Spring 具体配置:第一步配置数据源
<?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 http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 加载jdbc.properties -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<!-- 连接数据库的用户名-->
<property name="username" value="${jdbc.user}"/>
<!-- 连接数据库的密码-->
<property name="password" value="${jdbc.password}"/>
<!-- 目标数据库的URL 地址-->
<property name="url" value="${jdbc.url}"/>
<!-- 数据库驱动全类名-->
<property name="driverClassName" value="${jdbc.driver}"/>
</bean>
</beans>
★ 遇到问题:
applicationContext not configu…的解决方案
测试:
// 指定Spring 给Junit 提供的运行器类
@RunWith(SpringJUnit4ClassRunner.class)
// 加载Spring 配置文件的注解
@ContextConfiguration(locations = {"classpath:spring-persist-mybatis.xml"})
public class CrowdTest {
@Autowired
private DataSource dataSource;
@Test
public void testDataSource() throws SQLException {
// 1.通过数据源对象获取数据源连接
Connection connection = dataSource.getConnection();
// 2.打印数据库连接
System.out.println(connection);
}
}
★ 遇到问题:java entity包找不到
把以下依赖放到 webui 的 pom.xml 下
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
⑥ Spring 具体配置:第二步配置SqlSessionFactoryBean
在 spring-persist-mybatis.xml 中配置
<!-- 配置SqlSessionFactoryBean -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 装配数据源-->
<property name="dataSource" ref="dataSource"/>
<!-- 指定MyBatis 全局配置文件位置-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 指定Mapper 配置文件位置-->
<property name="mapperLocations" value="classpath:mybatis/mapper/*Mapper.xml"/>
</bean>
⑦ Spring 具体配置:第三步配置MapperScannerConfigurer
在 spring-persist-mybatis.xml 中配置
<!-- 配置MapperScannerConfigurer -->
<!-- 把MyBatis 创建的Mapper 接口类型的代理对象扫描到IOC 容器中-->
<bean id="mapperScannerConfigurer"
class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 使用basePackage 属性指定Mapper 接口所在包-->
<property name="basePackage" value="com.atguigu.crowd.mapper"/>
</bean>
测试插入
@Autowired
private AdminMapper adminMapper;
@Test
public void testInsertAdmin() {
Admin admin = new Admin(null,"tom","123123","汤姆","tom@qq.com",null);
int count = adminMapper.insert(admin);
System.out.println("插入行数: " + count);
}
七、日志
// 测试日志
@RequestMapping("/test/log.html")
public void testLog() {
List<Admin> all = adminService.getAll();
// TestHandler.class 为当前类
Logger logger = LoggerFactory.getLogger(TestHandler.class);
logger.info("log: " + all);
}
八、声明式事务 (先不配了,一堆错误)
(1) 思路
(2) 操作
九、表述层工作机制
(1) 启动过程
(2) 访问过程
十、表述层环境搭建
(1) web.xml配置
① ContextLoaderListener
<!-- 配置ContextLoaderListener 加载Spring 配置文件-->
<!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-persist-*.xml</param-value>
</context-param>
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
② CharacterEncodingFilter
<!-- 配置CharacterEncodingFilter 解决POST 请求的字符乱码问题-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 指定字符集-->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<!-- 强制请求进行编码-->
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<!-- 强制响应进行编码-->
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
★ 遇到问题:web-app报错,好像是没按规定顺序写,将前面的<doc…全删掉即可
③ HiddenHttpMethodFilter
遵循RESTFUL 风格将POST 请求转换为PUT 请求、DELETE 请求时使用。省略不配。
之前学springmvc和springboot的时候都说过,遵循rest风格,转换为 put,delete请求时,需要使用过滤器
④ DispatcherServlet 基本配置
<!-- 配置SpringMVC 的前端控制器-->
<!-- The front controller of this Spring Web application, responsible for handling all application
requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 以初始化参数的形式指定SpringMVC 配置文件的位置-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-web-mvc.xml</param-value>
</init-param>
<!-- 让DispatcherServlet 在Web 应用启动时创建对象、初始化-->
<!-- 默认情况:Servlet 在第一次请求的时候创建对象、初始化-->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<!-- DispatcherServlet 映射的URL 地址-->
<!-- 大白话:什么样的访问地址会交给SpringMVC 来处理-->
<!-- 配置方式一:符合RESTFUL 风格使用“/” -->
<!-- <url-pattern>/</url-pattern> -->
<!-- 配置方式二:请求扩展名-->
<url-pattern>*.html</url-pattern>
<url-pattern>*.json</url-pattern>
</servlet-mapping>
(2) spring-web-mvc.xml 配置
① 导入命名空间
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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 http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
</beans>
② 创建SpringMVC 扫描的包
③ 具体配置
<!-- 配置自动扫描的包-->
<context:component-scan base-package="com.atguigu.crowd.mvc"/>
<!-- 配置视图解析器-->
<!-- 拼接公式→前缀+逻辑视图+后缀=物理视图-->
<!--
@RequestMapping("/xxx/xxx")
public String xxx() {
// 这个返回值就是逻辑视图
return "target";
}
物理视图是一个可以直接转发过去的地址
物理视图:"/WEB-INF/"+"target"+".jsp"
转发路径:"/WEB-INF/target.jsp"
-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀:附加到逻辑视图名称前-->
<property name="prefix" value="/WEB-INF/"/>
<!-- 后缀:附加到逻辑视图名称后-->
<property name="suffix" value=".jsp"/>
</bean>
<!-- 启用注解驱动-->
<mvc:annotation-driven/>
</beans>
④ 测试
在 webui工程 中加入依赖
⑤ 页面上的base 标签
<base href="http://${pageContext.request.serverName }:${pageContext.request.serverPort}${pageContext.request.contextPath}/"/>
十一、SpringMVC 环境下的Ajax 请求
(1) 建立意识
(2) Ajax 发送请求
前端发送的数据
$(function () {
// 准备要发送得数组
var array = [5,8,12];
// 将JSON数组转换为JSON字符串
var arrayStr = JSON.stringify(array);
$.ajax({
"url": "send/array.html", // 请求目标资源的地址
"type": "post", // 请求方式
"data": arrayStr, // 要发送的请求参数
"contentType":"application/json;charset=UTF-8", // 告诉服务器端当前请求的请求体是JSON 格式
"success": function (response) { // 服务器端成功处理请求后调用的回调函数,response是响应体数据
alert(response);
},
"error":function (response) { // 服务器端处理请求失败后调用的回调函数,response是响应体数据
alert(response);
}
});
});
后端接收数据 (ResponseBody,RequestMapping)
@ResponseBody
@RequestMapping("/send/array.html")
public String testReceiveArrayOne(@RequestBody Integer[] array) {
for (Integer number : array) {
System.out.println("number = " + number);
}
return "success";
}
(3) 需要注意的点
前端
首先准备好要发送的JSON 数据
1.JSON 对象
2.JSON 数组
将JSON 对象或JSON 数组转换为JSON 字符串
var arrayStr = JSON.stringify(array);
将JSON 字符串直接赋值给data 属性
“data”:arrayStr
必须要设置contentType
“contentType”:“application/json;charset=UTF-8”
后端
加入jackson 依赖
开启注解驱动
使用注解 @RequestBody Integer[] Array
(4) @RequestBody 使用的场景
@RequestBody 使用的场景 :传统发送请求参数方式不方便发送的数据,使用JSON 请求体的方式发送。特别是要发送复杂对象的时候。
(5) 统一返回数据格式
package com.atguigu.crowd.util;
/**
* @author ht
* @date 2021/3/29 - 10:42
* 用于统一项目中所有Ajax 请求的返回值类型
*/
public class ResultEntity<T> {
public static final String SUCCESS = "SUCCESS";
public static final String FAILED = "FAILED";
public static final String NO_MESSAGE = "NO_MESSAGE";
public static final String NO_DATA = "NO_DATA";
/**
* 返回操作结果为成功,不带数据
* @return
*/
public static <E> ResultEntity<E> successWithoutData() {
return new ResultEntity<E>(SUCCESS, NO_MESSAGE, null);
}
/**
* 返回操作结果为成功,携带数据
* @param data
* @return
*/
public static <E> ResultEntity<E> successWithData(E data) {
return new ResultEntity<E>(SUCCESS, NO_MESSAGE, data);
}
/**
* 返回操作结果为失败,不带数据
* @param message
* @return
*/
public static <E> ResultEntity<E> failed(String message) {
return new ResultEntity<E>(FAILED, message, null);
}
private String operationResult;
private String operationMessage;
private T queryData;
public ResultEntity() {
}
public ResultEntity(String operationResult, String operationMessage, T queryData) {
super();
this.operationResult = operationResult;
this.operationMessage = operationMessage;
this.queryData = queryData;
}
@Override
public String toString() {
return "AjaxResultEntity [operationResult=" + operationResult + ", operationMessage="
+ operationMessage
+ ", queryData=" + queryData + "]";
}
public String getOperationResult() {
return operationResult;
}
public void setOperationResult(String operationResult) {
this.operationResult = operationResult;
}
public String getOperationMessage() {
return operationMessage;
}
public void setOperationMessage(String operationMessage) {
this.operationMessage = operationMessage;
}
public T getQueryData() {
return queryData;
}
public void setQueryData(T queryData) {
this.queryData = queryData;
}
}
十二、异常映射
(1) 作用
(2) 异常映射实现方式
① 基于XML
spring-web-mvc.xml 文件中的配置
<!-- 配置基于XML 的异常映射-->
<bean id="simpleMappingExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- 指定异常类型和逻辑视图名称的对应关系-->
<property name="exceptionMappings">
<props>
<!-- key 属性指定异常类型(全类名) -->
<!-- 文本标签体中指定异常对应的逻辑视图名称-->
<prop key="java.lang.NullPointerException">system-error</prop>
</props>
</property>
<!-- 使用exceptionAttribute 可以修改异常对象存入请求域时使用的属性名-->
<!-- <property name="exceptionAttribute"></property> -->
</bean>
② 新建system-error.jsp 页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script type="text/javascript">
$(function(){
$("button").click(function(){
// 调用back()方法类似于点击浏览器的后退按钮
window.history.back();
});
});
</script>
</head>
<body>
<div class="container" style="text-align: center;">
<h3>系统信息页面</h3>
<h4>${requestScope.exception.message }</h4>
<button style="width: 300px;margin: 0px auto 0px auto;" class="btn btn-lg btn-success btn-block">返回刚才页面</button>
</div>
</body>
</html>
③ 判断请求类型的工具方法
判断依据:
④ 创建constant类
public class CrowdConstant {
public static final String ATTR_NAME_EXCEPTION = "exception";
public static final String MESSAGE_LOGIN_FAILED = "登录失败!请确认账号密码是否正确!";
}
⑤ 创建异常处理器类
// @ControllerAdvice表示当前类是一个基于注解的异常处理器类
@ControllerAdvice
public class CrowdExceptionResolver {
@ExceptionHandler(value = NullPointerException.class) //ExceptionHandler 将一个具体的异常类型和一个方法关联起来
public ModelAndView resolveNullPointerException(NullPointerException exception, HttpServletRequest request, HttpServletResponse response, String viewName) throws IOException {
// 只是指定当前异常对应的页面即可
viewName = "error";
return commonResolveException(exception, request, response, viewName);
}
/**
* 核心异常处理方法
*
* @param exception SpringMVC 捕获到的异常对象
* @param request 为了判断当前请求是“普通请求”还是“Ajax 请求”
* 需要传入原生request 对象
* @param response 为了能够将JSON 字符串作为当前请求的响应数
* 据返回给浏览器
* @param viewName 指定要前往的视图名称
* @return ModelAndView
* @throws IOException
*/
private ModelAndView commonResolveException(
Exception exception,
HttpServletRequest request,
HttpServletResponse response,
String viewName
) throws IOException {
// 1.判断当前请求是“普通请求”还是“Ajax 请求”
boolean judgeResult = CrowdUtil.judgeRequestType(request);
// 2.如果是Ajax 请求
if (judgeResult) {
// 3.从当前异常对象中获取异常信息
String message = exception.getMessage();
// 4.创建ResultEntity
ResultEntity<Object> resultEntity = ResultEntity.failed(message);
// 5.创建Gson 对象
Gson gson = new Gson();
// 6.将resultEntity 转化为JSON 字符串
String json = gson.toJson(resultEntity);
// 7.把当前JSON 字符串作为当前请求的响应体数据返回给浏览器
// ①获取Writer 对象
PrintWriter writer = response.getWriter();
// ②写入数据
writer.write(json);
// 8.返回null,不给SpringMVC 提供ModelAndView 对象
// 这样SpringMVC 就知道不需要框架解析视图来提供响应,而是程序员自己提供了响应
return null;
}
// 9.创建ModelAndView 对象
ModelAndView modelAndView = new ModelAndView();
// 10.将Exception 对象存入模型
modelAndView.addObject(CrowdConstant.ATTR_NAME_EXCEPTION, exception);
// 11.设置目标视图名称
modelAndView.setViewName(viewName);
// 12.返回ModelAndView 对象
return modelAndView;
}
}
⑥ 测试异常处理器类
先把xml中这个bean注了,不然会被这货截胡;或者用其他异常类型测试也行
在 index.jsp 中
<a href="test/exception.html">测试异常</a>
在 TestHandler 中
// 测试空指针异常
@RequestMapping("/test/exception.html")
public void testException() {
String a = null;
System.out.println(a.length());
}
跳转的页面
环境搭建终于完事了~ 花了三四天,真是要搭 tu 了,中途一堆错误,心态接近崩溃,好在最终还是基本完成了环境的搭建