2020-03-2016:24:48尚筹网项目第一天
【本笔记大多来源于封捷老师写的笔记】
尚硅谷尚筹网项目视频教程
下载链接:https://pan.baidu.com/s/1WOLG7b4yHkQfSMu3fMsOBA
提取码:s5gw
项目概述:
一个金融类项目
项目背景:
略
后台环境搭建:
添加内容:
idea中创建web项目
①创建maven项目,打包方式为war
②pom文件:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.atguigu.crowd</groupId> <artifactId>extra01-ajax</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <!-- SpringMVC 环境 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.20.RELEASE</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> <!-- 引入 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> </dependencies> </project>
③创建web.xml文件
④改变classes文件的路径:
⑤编写web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <!-- 配置 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> <!-- 配置 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> </web-app>
⑥、编写springmvc的配置文件:
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 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"> <!-- 配置自动扫描的包 --> <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>
⑦编写handler
package com.atguigu.crowd.mvc; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class TestHandler { @RequestMapping("/test/page.html") public String test(){ return "target"; } }
⑧编写jsp页面:
<%-- Created by IntelliJ IDEA. User: 25017 Date: 2020/3/20 Time: 23:21 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>搭建环境,测试页面</title> </head> <body> <h1>测试</h1> </body> </html>
⑨将项目发布到tomcat
⑩测试
http://localhost:8080/ajaxTest/test/page.html
1、mybatis逆向工程的使用
maven命令:
mybatis-generator:generate
<!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:3306/project_crowd" userId="root" password="630415"></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>
pom文件:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.atguigu.crowd</groupId> <artifactId>atcrowdfunding01-admin-parent</artifactId> <version>1.0-SNAPSHOT</version> <modules> <module>atcrowdfunding02adminwebui</module> <module>atcrowdfunding03admincomponent</module> <module>atcrowdfunding04adminentity</module> </modules> <packaging>pom</packaging> <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> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <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> <!-- 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> <build> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <plugin> <artifactId>maven-site-plugin</artifactId> <version>3.7.1</version> </plugin> <plugin> <artifactId>maven-project-info-reports-plugin</artifactId> <version>3.0.0</version> </plugin> </plugins> </pluginManagement> </build> <reporting> <plugins> <plugin> <artifactId>maven-project-info-reports-plugin</artifactId> </plugin> </plugins> </reporting> </project>
2、spring整合mybatis
pom依赖:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>atcrowdfunding01-admin-parent</artifactId> <groupId>com.atguigu.crowd</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>atcrowdfunding02-admin-webui</artifactId> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>com.atguigu.crowd</groupId> <artifactId>atcrowdfunding03-admin-component</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <!-- 引入 Servlet 容器中相关依赖 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <scope>provided</scope> </dependency> <!-- JSP 页面使用的依赖 --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <scope>provided</scope> </dependency> </dependencies> </project>
jdbc.properties
jdbc.user=root jdbc.password=630415 jdbc.url=jdbc:mysql://localhost:3306/project_crowd?useUnicode=true&characterEncoding=UTF-8 jdbc.driver=com.mysql.jdbc.Driver
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 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> <!-- 配置 SqlSessionFactoryBean --> <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 装配数据源 --> <property name="dataSource" ref="dataSource"/> <!-- 指定 MyBatis 全局配置文件位置 --> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/> <!-- 指定 Mapper 配置文件位置 --> <property name="mapperLocations" value="classpath:mybatis/mapper/*Mapper.xml"/> </bean> <!-- 配置 MapperScannerConfigurer --> <!-- 把 MyBatis 创建的 Mapper 接口类型的代理对象扫描到 IOC 容器中 --> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 使用 basePackage 属性指定 Mapper 接口所在包 --> <property name="basePackage" value="com.atguigu.crowd.mapper"/> </bean> </beans>
mybatis全局配置文件:
<?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>
package com.atguigu.crowd.test; import com.atguigu.crowd.entity.Admin; import com.atguigu.crowd.service.AdmainService; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; // 指定 Spring 给 Junit 提供的运行器类 @RunWith(SpringJUnit4ClassRunner.class) // 加载 Spring 配置文件的注解 @ContextConfiguration(locations = {"classpath:spring-persist-mybatis.xml", "classpath:spring-persist-tx.xml"}) public class CrowdSpringTest { @Autowired private DataSource dataSource; @Autowired private AdmainService admainService; @Test public void testDataSource(){ try { Connection connection = dataSource.getConnection(); System.out.println(connection+"...."); } catch (SQLException e) { e.printStackTrace(); } } @Test public void testSpringAndMybatis(){ Admin admin = admainService.queryById(1); System.out.println(admin+"..."); // 获取日志记录对象 Logger logger = LoggerFactory.getLogger(CrowdSpringTest.class); // 按照 Debug 级别打印日志 logger.debug(admin.toString()); } }
3、日志系统
logback.xml
使用slf4j作为日志门面,使用logback作为日志实现,需要将logging
<?xml version="1.0" encoding="UTF-8"?> <configuration debug="true"> <!-- 指定日志输出的位置 --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <!-- 日志输出的格式 --> <!-- 按照顺序分别是:时间、日志级别、线程名称、打印日志的类、日志主体 内容、换行 --> <pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%n</pattern> </encoder> </appender> <!-- 设置全局日志级别。日志级别按顺序分别是:DEBUG、INFO、WARN、ERROR --> <!-- 指定任何一个日志级别都只打印当前级别和后面级别的日志。 --> <root level="INFO"> <!-- 指定打印日志的 appender,这里通过“STDOUT”引用了前面配置的 appender --> <appender-ref ref="STDOUT"/> </root> <!-- 根据特殊需求指定局部日志级别 --> <logger name="com.atguigu.crowd.mapper" level="DEBUG"/> </configuration>
pom文件:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>atcrowdfunding01-admin-parent</artifactId> <groupId>com.atguigu.crowd</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>atcrowdfunding03-admin-component</artifactId> <dependencies> <!-- 引入Servlet容器中相关依赖 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.atguigu.crowd</groupId> <artifactId>atcrowdfunding05-common-util</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.atguigu.crowd</groupId> <artifactId>atcrowdfunding04-admin-entity</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <!-- Spring 依赖 --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <exclusions> <exclusion> <artifactId>commons-logging</artifactId> <groupId>commons-logging</groupId> </exclusion> </exclusions> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <!-- aop相关的依赖--> <!-- 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> <!-- 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> <!-- JSTL 标签库 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency> <!-- 测试相关的依赖 --> <!-- junit 测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${atguigu.spring.version}</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> <!-- 排除commons-logging需要添加的转换包 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.7.25</version> </dependency> </dependencies> </project>
4、
<?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" 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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- 扫描业务逻辑层 --> <context:component-scan base-package="com.atguigu.crowd.service"/> <!-- 配置事务管理器 --> <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 装配数据源 --> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置 AOP --> <aop:config> <!-- 配置切入点表达式 --> <!-- public String com.atguigu.crowd.service.AdminService.getXxx(Integer id) --> <aop:pointcut expression="execution(* *..*Service.*(..))" id="txPointCut"/> <!-- 将事务通知和切入点表达式关联到一起 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> </aop:config> <!-- 配置事务通知 --> <!-- id 属性用于在 aop:advisor 中引用事务通知 --> <!-- transaction-manager 属性用于引用事务管理器,如果事务管理器的 bean 的 id 正好是 transactionManager,可以省略这个属性 --> <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager"> <tx:attributes> <!-- name 属性指定当前要配置的事务方法的方法名 --> <!-- 查询的方法通常设置为只读,便于数据库根据只读属性进行相关性能优化 --> <tx:method name="get*" read-only="true"/> <tx:method name="query*" read-only="true"/> <tx:method name="find*" read-only="true"/> <tx:method name="count*" read-only="true"/> <!-- 增删改方法另外配置 --> <!-- propagation 属性配置事务方法的传播行为 --> <!-- 默认值:REQUIRED 表示:当前方法必须运行在事务中,如果没有事务,则开 启事务,在自己的事务中运行。如果已经有了已开启的事务,则在当前事务中运行。有可能 和其他方法共用同一个事务。 --> <!-- 建议值:REQUIRES_NEW 表示:当前方法必须运行在事务中,如果没有事务, 则开启事务,在自己的事务中运行。和 REQUIRED 的区别是就算现在已经有了已开启的事务, 也一定要开启自己的事务,避免和其他方法共用同一个事务。 --> <!-- rollback-for 属性配置回滚的异常 --> <!-- 默认值:运行时异常 --> <!-- 建议值:编译时异常+运行时异常 --> <tx:method name="save*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception"/> <tx:method name="remove*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception"/> <tx:method name="update*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception"/> </tx:attributes> </tx:advice> </beans>
5、表述层环境的搭建
springmvc的配置:
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 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"> <!-- 配置自动扫描的包 --> <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>
web.xml配置:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <!-- 配置 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 解决 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> <!-- 配置 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> </web-app>
6、ajax测试
传输数组的三种方式:
方式一:
页面:
<button id="btn1">测试发送数组[5,8,12]方式1</button> 需要将下面的代码放在文档就绪函数里: //文档就绪函数 $(function(){ //this }); $("#btn1").click(function(){ $.ajax({ "url": "test/array/one.json", "type": "post", "data":{ "empIdArray":[5,8,12] }, //"contentType":"application/json;charset=UTF-8", "dataType":"json", "success":function(response){ alert(response); } }); });
后台:
方式一:
@ResponseBody @RequestMapping("/test/array/one") public Employee testArrayOne(@RequestParam("empIdArray[]") Integer[] empIdArray){ String temp = ""; if(empIdArray != null){ for (int i=0,length = empIdArray.length;i<length;i++){ temp += empIdArray[i]; System.out.println("one:"+temp); } } return new Employee("张三","男","zs@qq.com"+temp); }
方式二:
页面:
<button id="btn2">测试发送数组[5,8,12]方式2</button> $("#btn2").click(function(){ $.ajax({ "url": "test/array/two.json", "type": "post", "data":{ "empIdArray[0]":5, "empIdArray[1]":8, "empIdArray[2]":12 }, //"contentType":"application/json;charset=UTF-8", "dataType":"json", "success":function(response){ alert(response); } }); });
后台:
@ResponseBody @RequestMapping("/test/array/two") public Employee testArrayTwo(ParamData paramData){ Integer[] empIdArray = paramData.getEmpIdArray(); String temp = ""; if(empIdArray != null){ for (int i=0,length = empIdArray.length;i<length;i++){ temp += empIdArray[i]; System.out.println("two:"+temp); } } return new Employee("张三","男","zs@qq.com"+temp); }
package com.atguigu.crowd.entity; public class ParamData { private Integer[] empIdArray; public void setEmpIdArray(Integer[] empIdArray) { this.empIdArray = empIdArray; } public Integer[] getEmpIdArray() { return empIdArray; } }
方式三:
页面:
<button id="btn3">测试发送数组[5,8,12]方式3</button> $("#btn3").click(function(){ // 准备好要发送到服务器端的数组 var array = [5, 8, 12]; console.log(array.length); // 将JSON数组转换为JSON字符串 var requestBody = JSON.stringify(array); // "['5','8','12']" console.log(requestBody.length); $.ajax({ "url": "test/array/three.json",// 请求目标资源的地址 "type": "post", // 请求方式 "data": requestBody, // 请求体 "contentType": "application/json;charset=UTF-8", // 设置请求体的内容类型,告诉服务器端本次请求的请求体是JSON数据 "dataType": "text", // 如何对待服务器端返回的数据 "success": function(response) { // 服务器端成功处理请求后调用的回调函数,response是响应体数据 alert(response); }, "error":function(response) { // 服务器端处理请求失败后调用的回调函数,response是响应体数据 alert(response); } }); });
后台:
@ResponseBody @RequestMapping("/test/array/three") public Employee testArrayThree(@RequestBody Integer[] array1){ String temp = ""; for (int i=0,length = array1.length;i<length;i++){ temp += array1[i]; System.out.println("three:"+temp); } return new Employee("张三","男","zs@qq.com"+temp); }
传输复杂类型:
页面:
<button id="btn4">提交复杂参数student【list、map、对象】</button> $("#btn4").click(function(){ // 准备要发送的数据 var student = { "stuId": 5, "stuName":"tom", "address": { "province": "广东", "city": "深圳", "street":"后瑞" }, "subjectList": [ { "subjectName": "JavaSE", "subjectScore": 100 },{ "subjectName": "SSM", "subjectScore": 99 } ], "map": { "k1":"v1", "k2":"v2" } }; // 将JSON对象转换为JSON字符串 var requestBody = JSON.stringify(student); // 发送Ajax请求 $.ajax({ "url":"test/student.json", "type":"post", "data":requestBody, "contentType":"application/json;charset=UTF-8", "dataType":"json", "success":function(response){ console.log(response); }, "error":function(response){ console.log(response); } }); });
后台:
package com.atguigu.crowd.entity; import java.util.List; import java.util.Map; public class Student { private Integer stuId; private String stuName; private Address address; private List<Subject> subjectList; private Map<String,String> map; @Override public String toString() { return "Student{" + "stuId=" + stuId + ", stuName='" + stuName + '\'' + ", address=" + address + ", subjectList=" + subjectList + ", map=" + map + '}'; } public Integer getStuId() { return stuId; } public void setStuId(Integer stuId) { this.stuId = stuId; } public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public List<Subject> getSubjectList() { return subjectList; } public void setSubjectList(List<Subject> subjectList) { this.subjectList = subjectList; } public Map<String, String> getMap() { return map; } public void setMap(Map<String, String> map) { this.map = map; } }
package com.atguigu.crowd.entity; public class Subject { private String subjectName; private String subjectScore; @Override public String toString() { return "Subject{" + "subjectName='" + subjectName + '\'' + ", subjectScore='" + subjectScore + '\'' + '}'; } public String getSubjectName() { return subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } public String getSubjectScore() { return subjectScore; } public void setSubjectScore(String subjectScore) { this.subjectScore = subjectScore; } }
package com.atguigu.crowd.entity; public class Address { private String province; private String city; private String street; @Override public String toString() { return "Address{" + "province='" + province + '\'' + ", city='" + city + '\'' + ", street='" + street + '\'' + '}'; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } }
@ResponseBody @RequestMapping("/test/student") public Student testStudent(@RequestBody Student student){ System.out.println("查看封装的student对象:"); System.out.println(student); return student; }
7、统一的返回
pom:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.atguigu.crowd</groupId> <artifactId>atcrowdfunding05-common-util</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- 引入Servlet容器中相关依赖 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> </dependencies> </project>
代码:
package com.atguigu.crowd.util; /** * 统一整个项目中Ajax请求返回的结果(未来也可以用于分布式架构各个模块间调用时返回统一类型) * @author Lenovo * * @param <T> */ public class ResultEntity<T> { public static final String SUCCESS = "SUCCESS"; public static final String FAILED = "FAILED"; // 用来封装当前请求处理的结果是成功还是失败 private String result; // 请求处理失败时返回的错误消息 private String message; // 要返回的数据 private T data; /** * 请求处理成功且不需要返回数据时使用的工具方法 * @return */ public static <Type> ResultEntity<Type> successWithoutData() { return new ResultEntity<Type>(SUCCESS, null, null); } /** * 请求处理成功且需要返回数据时使用的工具方法 * @param data 要返回的数据 * @return */ public static <Type> ResultEntity<Type> successWithData(Type data) { return new ResultEntity<Type>(SUCCESS, null, data); } /** * 请求处理失败后使用的工具方法 * @param message 失败的错误消息 * @return */ public static <Type> ResultEntity<Type> failed(String message) { return new ResultEntity<Type>(FAILED, message, null); } public ResultEntity() { } public ResultEntity(String result, String message, T data) { super(); this.result = result; this.message = message; this.data = data; } @Override public String toString() { return "ResultEntity [result=" + result + ", message=" + message + ", data=" + data + "]"; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
8、异常映射
基于配置文件:
springmvc的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>
pom文件:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>atcrowdfunding01-admin-parent</artifactId> <groupId>com.atguigu.crowd</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>atcrowdfunding02-admin-webui</artifactId> <packaging>war</packaging> <dependencies> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>com.atguigu.crowd</groupId> <artifactId>atcrowdfunding03-admin-component</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <!-- 引入 Servlet 容器中相关依赖 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <scope>provided</scope> </dependency> <!-- JSP 页面使用的依赖 --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <scope>provided</scope> </dependency> </dependencies> </project>
基于注解:
springmvc的xml新增:
<!-- 启用注解驱动 --> <mvc:annotation-driven/>
判断请求是否为ajax:
package com.atguigu.crowd.util; import javax.servlet.http.HttpServletRequest; public class CrowdUtil { /** * 判断当前请求是否为Ajax请求 * @param request 请求对象 * @return * true:当前请求是Ajax请求 * false:当前请求不是Ajax请求 */ public static boolean judgeRequestType(HttpServletRequest request) { // 1.获取请求消息头 String acceptHeader = request.getHeader("Accept"); String xRequestHeader = request.getHeader("X-Requested-With"); // 2.判断 return (acceptHeader != null && acceptHeader.contains("application/json")) || (xRequestHeader != null && xRequestHeader.equals("XMLHttpRequest")); } }
异常处理的代码:
package com.atguigu.crowd.mvc.config; import com.atguigu.crowd.util.CrowdUtil; import com.atguigu.crowd.util.ResultEntity; import com.google.gson.Gson; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @ControllerAdvice public class CrowdExceptionResolver { @ExceptionHandler(value = ArithmeticException.class) public ModelAndView resolveMathException( ArithmeticException exception, HttpServletRequest request, HttpServletResponse response ) throws IOException { String viewName = "system-error"; return commonResolve(viewName, exception, request, response); } @ExceptionHandler(value = NullPointerException.class) public ModelAndView resolveNullPointerException( NullPointerException exception, HttpServletRequest request, HttpServletResponse response) throws IOException { String viewName = "system-error"; return commonResolve(viewName, exception, request, response); } // @ExceptionHandler将一个具体的异常类型和一个方法关联起来 private ModelAndView commonResolve( // 异常处理完成后要去的页面 String viewName, // 实际捕获到的异常类型 Exception exception, // 当前请求对象 HttpServletRequest request, // 当前响应对象 HttpServletResponse response) throws IOException { // 1.判断当前请求类型 boolean judgeResult = CrowdUtil.judgeRequestType(request); // 2.如果是Ajax请求 if(judgeResult) { // 3.创建ResultEntity对象 ResultEntity<Object> resultEntity = ResultEntity.failed(exception.getMessage()); // 4.创建Gson对象 Gson gson = new Gson(); // 5.将ResultEntity对象转换为JSON字符串 String json = gson.toJson(resultEntity); // 6.将JSON字符串作为响应体返回给浏览器 response.getWriter().write(json); // 7.由于上面已经通过原生的response对象返回了响应,所以不提供ModelAndView对象 return null; } // 8.如果不是Ajax请求则创建ModelAndView对象 ModelAndView modelAndView = new ModelAndView(); // 9.将Exception对象存入模型 modelAndView.addObject("exception", exception); // 10.设置对应的视图名称 modelAndView.setViewName(viewName); // 11.返回modelAndView对象 return modelAndView; } }