1、首先我们要new一个Project,然后创建的是一个Maven工程,一定要勾选Maven工程中的webapp应用,才能创建一个web项目!
为了加快创建web项目时候的速度,我们可以在Maven页面中添加一个键值对,加快项目的下载和创建速度
【archetypeCatalog-internal】
2、在创建好项目之后,我们要开始搭建我们的WEB项目。因为Maven默认的环境并不满足我们的需要,我们需要在main目录下创建两个文件,一个是java(Sources Root),一个是resources(Resources Root),然后分别对这两个文件进行Mark Directory as操作:
3、在创建好这两个文件之后,我们首先搭建好项目的整体结构,在java文件中创建好所有需要使用的包,项目最终的目录结构如下图所示:
4、首先,我们要在pom.xml文件中,导入我们本次项目所需要的坐标依赖:
<?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.ysw</groupId>
<artifactId>SSM_Adams</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>SSM_Adams Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!-- 版本锁定 -->
<!-- Spring版本锁定 -->
<spring.version>5.0.2.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<!--阿里Druid数据库连接池-->
<druid.version>1.1.10</druid.version>
<!-- 打印日志的log4j版本锁定 -->
<log4j.version>1.2.12</log4j.version>
<!-- 数据库版本锁定 -->
<mysql.version>5.1.6</mysql.version>
<!-- mybatis版本锁定 -->
<mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies>
<!-- Spring start -->
<!-- 切入点表达式 start -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<!-- 切入点表达式 end -->
<!-- AOP -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring 扩展依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring end -->
<!-- SpringMVC start -->
<dependency>
<!-- 这个可以加载监听器,加载我们的spring配置文件 -->
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- SpringMVC end -->
<!-- 单元测试 start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 单元测试 end -->
<!-- Spring事务 start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring事务 end -->
<!-- jdbc start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- jdbc end -->
<!-- junit单元测试 start -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<!-- junit单元测试 end -->
<!-- 数据库mysql start -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- 数据库mysql end -->
<!-- servlet start -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- servlet end -->
<!-- Jsp start -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Jsp end -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
<!-- Mybatis start -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- Spring整合Mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!-- Mybatis end -->
<!-- 数据库连接池 start -->
<!-- c3p0数据库连接池 -->
<!--<dependency>-->
<!--<groupId>c3p0</groupId>-->
<!--<artifactId>c3p0</artifactId>-->
<!--<version>0.9.1.2</version>-->
<!--<type>jar</type>-->
<!--<scope>compile</scope>-->
<!--</dependency>-->
<!-- 这里改用Druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!--数据库连接池 end-->
<!-- 导入jackson,转换JSON和实体类所用的 start -->
<!-- 字符串转对象,或者对象转字符串,导入jackson的jar包 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<!-- 导入jackson,转换JSON和实体类所用的 end -->
<!-- 文件上传需要导入的坐标依赖 start -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- 文件上传需要导入的坐标依赖 end -->
</dependencies>
<build>
<finalName>SSM_Adams</finalName>
<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>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
5、配置在WEB-INF下的web.xml文件,因为在web程序执行的时候会首先加载这个文件里面的配置内容。
<!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>
<display-name>Archetype Created Web Application</display-name>
<!--
配置Spring的监听器,
默认只加载WEB-INF下的applicationContext.xml文件,
虽然是这个文件在类路径下,当启动的时候依然会加载到WEB-INF的classes路径下
-->
<listener>
<!-- 这个listener意思是要读取我们的spring配置 -->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 设置配置文件路径,将类路径下的applicationContext.xml进行读取 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置前端控制器,只有扫描的时候才经过这个前端控制器,并且在初始化的时候就完成了扫描 -->
<!-- 加载完类库的时候开始扫描注解,扫描跟注入bean完成了就加载完成了 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 加载SpringMVC的配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:SpringMVC.xml</param-value>
</init-param>
<!-- 启动服务器,就创建该servlet -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 解决中文乱码的过滤器 -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 配置字节码格式为UTF-8 -->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<!-- 拦截所有的servlet -->
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
6、在创建好这个web.xml文件之后,我们就需要在resources目录下创建:
(1)jdbcConfig.properties 主要用于配置数据库连接所用的(resources右键,创建file,自定义命名,但是一定要是properties结尾)
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=UTF-8&useSSL=false
jdbc.username=root
jdbc.password=123456
jdbc.filters=stat
jdbc.maxActive=20
jdbc.initialSize=1
jdbc.maxWait=60000
jdbc.minIdle=10
jdbc.maxIdle=15
jdbc.timeBetweenEvictionRunsMillis=60000
jdbc.minEvictableIdleTimeMillis=300000
jdbc.validationQuery=SELECT 'x'
jdbc.testWhileIdle=true
jdbc.testOnBorrow=false
jdbc.testOnReturn=false
jdbc.maxOpenPreparedStatements=20
jdbc.removeAbandoned=true
jdbc.removeAbandonedTimeout=1800
jdbc.logAbandoned=true
# ↑↑↑↑↑↑↑↑ Druid连接池 ↑↑↑↑↑↑↑↑↑
# ↓↓↓↓↓↓ C3P0连接池 ↓↓↓↓↓↓
#jdbc.driver=com.mysql.jdbc.Driver
#jdbc.url=jdbc:mysql://localhost:3306/ssm
#jdbc.username=root
#jdbc.password=123456
(2)log4j.properties 主要是用于打印日志的(resources右键,创建file,自定义命名,但是一定要是properties结尾)
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=info, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
(3)applicationContext.xml和SpringMVC.xml文件 创建方式都如上图所示。前者是用于配置Spring框架的,后者是用于配置SpringMVC框架的。
applicationContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 开启注解的扫描,但是不需要扫描controller层(SpringMVC来处理),只扫描service、dao -->
<context:component-scan base-package="com.ysw">
<!-- 配置不扫描controller层的注解,因为controller层由SpringMVC来扫描注解 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
</context:component-scan>
<!-- Spring整合Mybatis框架 start 将接口生成代理对象存入SpringIoC容器 -->
<!-- 加载配置文件 -->
<!-- C3P0加载配置文件的方式 -->
<!--<context:property-placeholder location="classpath:jdbcConfig.properties"></context:property-placeholder>-->
<!-- 加载配置文件 -->
<!-- Druid加载配置文件的方式 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbcConfig.properties"></property>
</bean>
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
<property name="mapperLocations">
<list>
<!--D:\IDEA_ProjectSpace\BBS_Adams_v1.0\src\main\resources\com\ysw\dao\AccountDao.xml-->
<value>classpath:/com/ysw/dao/*.xml</value>
</list>
</property>
</bean>
<!-- 配置DataSource数据源 -->
<!-- 阿里 druid 数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<!-- 数据库基本信息配置 -->
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="filters" value="${jdbc.filters}"/>
<!-- 最大并发连接数 -->
<property name="maxActive" value="${jdbc.maxActive}"/>
<!-- 初始化连接数量 -->
<property name="initialSize" value="${jdbc.initialSize}"/>
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="${jdbc.maxWait}"/>
<!-- 最小空闲连接数 -->
<property name="minIdle" value="${jdbc.minIdle}"/>
<!-- 最大空闲连接数 -->
<property name="maxIdle" value="${jdbc.maxIdle}"/>
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}"/>
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}"/>
<property name="validationQuery" value="${jdbc.validationQuery}"/>
<property name="testWhileIdle" value="${jdbc.testWhileIdle}"/>
<property name="testOnBorrow" value="${jdbc.testOnBorrow}"/>
<property name="testOnReturn" value="${jdbc.testOnReturn}"/>
<property name="maxOpenPreparedStatements" value="${jdbc.maxOpenPreparedStatements}"/>
<!-- 超过时间限制是否回收 -->
<property name="removeAbandoned" value="${jdbc.removeAbandoned}"/>
<!-- 1800 秒,也就是 30 分钟 -->
<property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}"/>
<!-- 关闭 abanded 连接时输出错误日志 -->
<property name="logAbandoned" value="${jdbc.logAbandoned}"/>
</bean>
<!-- ↓↓↓↓ C3P0连接池 ↓↓↓↓ -->
<!--<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">-->
<!--<property name="driverClass" value="${jdbc.driver}"></property>-->
<!--<property name="jdbcUrl" value="${jdbc.url}"></property>-->
<!--<property name="user" value="${jdbc.username}"></property>-->
<!--<property name="password" value="${jdbc.password}"></property>-->
<!--</bean>-->
<!-- 配置自动扫描dao包下的所有内容 -->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ysw.dao"></property>
</bean>
<!-- Spring整合Mybatis框架 end -->
<!-- 配置Spring事务管理器 start -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 配置好这里之后就自动配置好了事务的自动提交了 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务的通知(REQUIRES_NEW的话,就是要不断地new出来,第一个使用了,第二个一定要NEW一个事务来进行) -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 事务开启之后,可以有两个方法都过来执行之后,最后才提交事务 -->
<tx:method name="*" propagation="REQUIRED" read-only="false"/>
<!-- 以find方法为头的话,自身不会开启事务,就是不在事务范围内就无法使用事务 -->
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置 aop -->
<aop:config>
<!-- 配置切入点表达式,一般配置业务层实现类serviceImpl目录下的文件 -->
<aop:pointcut expression="execution(* com.ysw.service.impl.*.*(..))" id="pt1"/>
<!-- 建立通知和切入点表达式的关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
<!-- 配置Spring事务管理器 end -->
</beans>
SpringMVC.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 开启注解扫描,只扫描controller层的注解 -->
<context:component-scan base-package="com.ysw">
<!-- 配置的SpringMVC文件只扫描controller层文件的注解 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter>
</context:component-scan>
<!-- 配置视图解析器,成功之后往哪里跳 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 文件前缀,这里指定到根路径 -->
<property name="prefix" value="/"></property>
<!-- 文件后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置过滤静态资源,可以让我们类似于css、js、imgages之类的可以进行访问 -->
<mvc:resources location="/css/" mapping="/css/**" />
<mvc:resources location="/images/" mapping="/images/**" />
<mvc:resources location="/js/" mapping="/js/**" />
<!-- 配置文件解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件大小10M = 10 * 1024 * 1024 -->
<property name="maxUploadSize" value="10485760"></property>
</bean>
<!-- 开启SpringMVC对注解的支持 -->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
(4)创建SqlMapConfig.xml文件 主要是用于配置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>
<!-- 这里的配置内容已经整合到Spring的配置文件中去了 -->
</configuration>
(5)AccountDao.xml文件 主要是用于配置AccountDao接口的映射对象所用的,这里主要是写sql语句用。(右键,创建第一层Directory目录com,继续在com右键,创建第二个directory目录ysw,继续在ysw文件右键,创建第三个directory目录dao)。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- !!!!!声明名称空间!!!!! -->
<mapper namespace="com.ysw.dao.AccountDao">
<!-- 查询所有 -->
<select id="findAll" resultType="com.ysw.domain.Account">
select * from account
</select>
<insert id="saveAccount" parameterType="com.ysw.domain.Account">
insert into account(name,money) values (#{name},#{money})
</insert>
</mapper>
↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
基本环境搭建完毕,接下来就是举例一些Demo案例:
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
第一,在domain下创建Account对象,然后getter和setter,以及toString()直接导入即可。
package com.ysw.domain;
import java.io.Serializable;
/**
* 账户实体类,实现序列化接口
*/
public class Account implements Serializable
private Integer id; //编号
private String name; //姓名
private Double money; //金额
第二,在AccountDao下写入方法,一个是添入数据库,一个是查询所有方法,记得要使用 @Repostitory 注解,记得不能定义名称,否则就定义了多个bean对象
package com.ysw.dao;
import com.ysw.domain.Account;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 账户的接口类
*/
@Repository
public interface AccountDao {
/**
* 查询所有
*
* @return
*/
List<Account> findAll();
/**
* 保存账户信息
*
* @param account
*/
void saveAccount(Account account);
}
第三,在service层写一个AccountService接口
package com.ysw.service;
import com.ysw.domain.Account;
import java.util.List;
/**
* 账户的业务层接口
*/
public interface AccountService {
/**
* 查询所有
*
* @return
*/
List<Account> findAll();
/**
* 保存账户信息
*
* @param account
*/
void saveAccount(Account account);
}
第四,在impl目录下创建一个AccountServiceImpl的AccountService实现类,但是记得要使用 @Service 注解
package com.ysw.service.impl;
import com.ysw.dao.AccountDao;
import com.ysw.domain.Account;
import com.ysw.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
/**
* 查询所有
*
* @return
*/
public List<Account> findAll(){
System.out.println("service层执行了");
//返回一个封装好对象的List集合
return accountDao.findAll();
}
/**
* 插入Account对象
*
* @param account
*/
public void saveAccount(Account account){
//将account对象保存到数据库
accountDao.saveAccount(account);
}
}
第五,最后定义Controller层的代码即可,但是一定要注意使用 @Controller 和 @RequestMapping 等的注解。
package com.ysw.controller;
import com.ysw.domain.Account;
import com.ysw.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 账户的controller层
*/
@Controller
@RequestMapping("/accountController")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/testFindAll")
public String findAll(Model model){
System.out.println("MVC查询成功");
//调用service层
List<Account> accounts = accountService.findAll();
model.addAttribute("accounts",accounts);
return "list";
}
@RequestMapping("/saveAccount")
public void SaveAccount(Account account, HttpServletRequest request, HttpServletResponse response) throws Exception{
accountService.saveAccount(account);
response.sendRedirect(request.getContextPath() + "/accountController/testFindAll");
return;
}
}
如果要想单独进行单元测试的话,在单元测试类中一定要记得导入注解:
@RunWith(SpringJUnit4ClassRunner.class) 用于定义当前类为测试类
@ContextConfiguration(locations = {"classpath:applicationContext.xml"}) 用于加载applicationContext.xml配置文件内容
package com.ysw.test;
import com.ysw.dao.AccountDao;
import com.ysw.domain.Account;
import com.ysw.service.AccountService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.InputStream;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class TestSSM {
@Autowired
private AccountService accountService;
@Test
public void test(){
//加载Spring配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取对象
AccountService accountService = (AccountService)ac.getBean("accountService");
//调用方法
System.out.println(accountService.findAll());
}
@Test
public void testMybatis() throws Exception{
//加载Mybatis文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建sqlsessionfactory对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//使用sql工厂创建sqlsession对象
SqlSession session = factory.openSession();
//获取代理对象
AccountDao accountDao = session.getMapper(AccountDao.class);
System.out.println(accountDao.findAll());
//关闭资源
// 但是记得增删改要记得提交session.commit()来提交事务
session.close();
in.close();
}
@Test
public void testService(){
System.out.println(accountService.findAll());
}
}
---------------------------------------------
最后,献上运行测试结果图,
index.jsp
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
<%--
Created by IntelliJ IDEA.
User: Simon
Date: 2020/3/9
Time: 15:42
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>
<a href="accountController/testFindAll">欢迎来到SSM</a>
<h3>测试保存</h3>
<form action="accountController/saveAccount" method="post">
姓名:<input type="text" name="name"><br/>
金额:<input type="text" name="money"><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
----------------------------------------------------------------
list.jsp
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
<%--
Created by IntelliJ IDEA.
User: Simon
Date: 2020/3/9
Time: 15:44
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>查询成功,环境搭建</h3>
<c:forEach items="${accounts}" var="account">
${account.id}
${account.name}
${account.money}
</c:forEach>
</body>
</html>
数据库表的内容:
如果想进行单元测试的话,单元测试类类名上方一定要注意使用注解:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")