项目整合数据库使用Mysql,数据访问框架采用mybatis3.4.5,继承spring+spring mvc,版本4.3.12,前端采用freemarker2.3.23,项目日志采用log4j1.2.17,并做一些常用配置。
File
–>New
–>Other
–>Maven Project
注意:在新建maven项目时打包类型选择war
Properties
–>Project Facets
–>Dynamic Web Module
–>Eurther configuration available...
Content directory : src/main/webapp
[x] Grenerate web.xml deployment descriptor
注意:content directory:建议填写src/main/webapp
因为利用Maven 的jetty插件运行项目时,这是默认路径,否则需要自行配置,
还有便是Maven打war包时,这也是默认路径,否则也需要专门配置,比较麻烦^_^。
建议将项目编码改为utf-8
打开项目的pom.xml,添加以下代码
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<maven.compiler.encoding>UTF-8maven.compiler.encoding>
properties>
右键项目–>Properties
–>Resource
–>Other
–>UTF-8
–>Apply and Close
打开pom.xml,添加以下代码,版本可以自行修改
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<version>3.1version>
<configuration>
<source>1.7source>
<target>1.7target>
configuration>
plugin>
plugins>
build>
也可以不配置,配置了可以mvn jetty:run直接运行项目,如果不配置需要打成war包放到web服务器中运行。
在pom.xml中添加如下代码,当然jetty插件的版本,自己可以自行配置
<build>
<plugins>
<plugin>
<groupId>org.eclipse.jettygroupId>
<artifactId>jetty-maven-pluginartifactId>
<version>9.4.4.v20170414version>
<configuration>
<scanIntervalSeconds>30scanIntervalSeconds>
configuration>
plugin>
plugins>
build>
注意:既然是maven项目,添加依赖jar包就是往pom.xml添加依赖配置。
maven库查询网站http://mvnrepository.com/,可以从里面搜索依赖
首先让我们看看sprng的架构图(可以去spring官网看官方文档,有架构图),核心包必须导入
spring-beans,spring-core,spring-context,spring-expression
因为我们搭建的是基于spring mvc的web程序,
所以我们需要导入servlet模块,即spring-mvc,因为spring-mvc依赖于spring-web,和spring-aop以及核心包。
因为一会要整合mybatis,还需要导入Transactions模块,即spring-tx,为了接管mybatis的事务,还有需要导入spring-jdbc(mybatis-spring需要的依赖,且配置事务也需要)。
json处理是web程序处理的家常便饭,spring-mvc还有一个可选的依赖jackson-databind用来处理json,这个jar包还有两个必选依赖jackson-core和jackson-annotations。
如果项目采用jsp作为页面的话,就不需要导入了,不过我们这里采用freemarker作为页面处理类库,所以我们还要导入freemarker依赖,在整合freemarker时需要导入spring-context-support依赖。
需要导入的依赖:
spring-beans
spring-core
spring-context
spring-expression
spring-web
spring-aop
spring-tx
spring-jdbc
jackson-databind
jackson-core
jackson-annotations
freemarker
spring-context-support
添加mybatis依赖,添加mybatis-spring依赖(整合spring使用),连接数据库需要数据库驱动,我们这里连接mysql,所以需要mysql-connector-java(mysql java版数据库驱动包)依赖。我们采用数据dbcp2数据源,所以我们需要添加commons-dbcp2依赖,commons-dbcp2又有两个必选依赖commons-pool2和commons-logging。
需要导入的依赖:
mybatis
mybatis-spring
mysql-connector-java
commons-dbcp2
commons-pool2
commons-logging
这里采用log4j作为日志处理。
需要导入的依赖:
log4j
<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.0modelVersion>
<groupId>com.basegroupId>
<artifactId>ssmartifactId>
<packaging>warpackaging>
<version>0.0.1-SNAPSHOTversion>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<maven.compiler.encoding>UTF-8maven.compiler.encoding>
<spring.version>4.3.12.RELEASEspring.version>
<log4j.version>1.2.17log4j.version>
<jackson.version>2.8.10jackson.version>
<freemarker.version>2.3.23freemarker.version>
<commons-logging.version>1.2commons-logging.version>
<commons-dbcp2.version>2.1.1commons-dbcp2.version>
<commons-pool2.version>2.4.2commons-pool2.version>
<mybatis.version>3.4.5mybatis.version>
<spring-mybatis.version>1.3.1spring-mybatis.version>
<mysql-connector-java.version>6.0.6mysql-connector-java.version>
properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<configuration>
<source>1.7source>
<target>1.7target>
configuration>
plugin>
<plugin>
<groupId>org.eclipse.jettygroupId>
<artifactId>jetty-maven-pluginartifactId>
<version>9.4.4.v20170414version>
<configuration>
<scanIntervalSeconds>30scanIntervalSeconds>
configuration>
plugin>
plugins>
build>
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>${spring-mybatis.version}version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql-connector-java.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-expressionartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>${jackson.version}version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>${jackson.version}version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>${jackson.version}version>
dependency>
<dependency>
<groupId>org.freemarkergroupId>
<artifactId>freemarkerartifactId>
<version>${freemarker.version}version>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-dbcp2artifactId>
<version>${commons-dbcp2.version}version>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-pool2artifactId>
<version>${commons-pool2.version}version>
dependency>
<dependency>
<groupId>commons-logginggroupId>
<artifactId>commons-loggingartifactId>
<version>${commons-logging.version}version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
dependency>
dependencies>
project>
虽然写了很多,但在这个教程里项目采用方式一配置日志。
在src/main/resources文件夹下建立log4j.properties,代码如下,可以根据需求自行配置
log4j.rootLogger=INFO,Console,File
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
log4j.appender.File = org.apache.log4j.RollingFileAppender
log4j.appender.File.File = logs/ssm.log
log4j.appender.File.MaxFileSize = 10MB
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
注意:log4j框架会自动去classpath路径下加载log4j.properties文件,也就是说按照以上规则配置,会自动生效,当然采用这种方式配置每次更改配置后都需要重启项目才能生效,且文件名不能更改,且不能放在classpath以外的路径。
我们还有一种配置方式,那便是在web.xml配置监听的方式,这种方式改完配置后不需要每次都重启项目且配置文件名可以随意,路径随意,只要配置好就可以,当然这种方式也必须先配置好log4j.properties(可以不叫log4j),代码如下:
<context-param>
<param-name>log4jConfigLocationparam-name>
<param-value>classpath:log4j.propertiesparam-value>
context-param>
<context-param>
<param-name>log4jRefreshIntervalparam-name>
<param-value>6000param-value>
context-param>
<context-param>
<param-name>webAppRootKeyparam-name>
<param-value>com.base.ssmparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListenerlistener-class>
listener>
log4jConfigLocation: log4j配置文件路径,既然可以指定路径当然名字可以随便起,路径也自由选择。
log4jRefreshInterval:为6000表示 开一条watchdog线程每6秒扫描一下配置文件的变化
webAppRootKey:不配置默认是webapp.root,webAppRootKey
为web
工程的根目录在系统环境变量中的key
,如果web容器中有多个项目都没有设置webAppRootKey或者重复,如果都向系统变量中去注册,那么就会报错,即抛出异常。在配置log4j.properties时可以使用${com.base.ssm}引用项目根目录,例如:
log4j.appender.file.File=${ com.base.ssm }/WEB-INF/logs/sample.log
在声明一遍,我们采用的是dbcp2数据源,当然也可以不用它的^_^。
首先让我们在src/main/resources文件夹下创建jdbc.properties,内容如下
#数据库驱动类
driver=com.mysql.jdbc.Driver
#连接url
url=jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true&serverTimezone=UTC
#用户名
username=root
#密码
password=root
#连接池最大空闲
maxIdle=4
#连接池最小空闲
minIdle=2
#最大活动数
maxTotal=4
注意:配置文件在创建数据源的时候使用关于dbcp2数据源的具体配置,请自行百度^_^, url serverTimezone参数如果不指定容易抛出异常
com.mysql.cj.core.exceptions.InvalidConnectionAttributeException:
The server time zone value '���
还要说明的一点是,使用6.0.6 版本的mysql驱动,控制台报这么一句话,是说明我们用的驱动类是过时的,且数据库驱动会自动注册,不需要手动配置,也就是说配置datasource时不需要配置驱动类了。
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
在src/main/resources文件夹下新建mybatisConfig.xml配置文件,mybatis和spring整合后,mybatisConfig.xml文件的作用就小了很多,但是还是有些用的吗,比如可以为实体类起别名,方便访问,例如
<typeAliases>
<typeAlias type="com.base.domain.Test" alias="Test" />
typeAliases>
完整代码如下,具体配置根据需要自行添加:
<configuration>
<typeAliases>
typeAliases>
<mappers>
mappers>
configuration>
在src/main/resources文件夹下创建spring-dao.xml(名字随便起)。
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties">property>
bean>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<property name="maxIdle" value="${maxIdle}"/>
<property name="minIdle" value="${minIdle}"/>
<property name="maxTotal" value="${maxTotal}"/>
bean>
<bean id="sqlSessionBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource">property>
<property name="configLocation" value="classpath:mybatisConfig.xml">property>
bean>
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.base.dao">property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionBean">property>
bean>
什么是事务?摘抄自网上(csdn shu_lin博客)
在编写业务的过程中,会需要进行事务处理,当需要执行多条插入语句时,如果前几条成功,而最后一条失败,那么我们需要回滚数据库操作,保持数据的一致性和完整性,此时,就需要利用DB的事务处理。事务是恢复和并发控制的基本单位。
简单来说,所谓的事务,是一个操作序列,这些操作要么都执行,要么都不执行,它是一个不可分割的工作单位。
事务应该具有4个属性:原子性、一致性、隔离性、持久性。这四个属性通常称为ACID特性。
原子性(atomicity)。一个事务是一个不可分割的工作单位,事务中包括的诸操作要么都做,要么都不做。
一致性(consistency)。事务必须是使数据库从一个一致性状态变到另一个一致性状态。一致性与原子性是密切相关的。
隔离性(isolation)。一个事务的执行不能被其他事务干扰。即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰。
持久性(durability)。持续性也称永久性(permanence),指一个事务一旦提交,它对数据库中数据的改变就应该是永久性的。接下来的其他操作或故障不应该对其有任何影响。
以下两种方式可以同时配置,项目中可以同时使用^_^,如果想了解具体请看文档或找度娘。
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
注意:在代码中可以使用@Transactional注解到方法上使用事务,@Transactional只能被应用到public方法上,对于其它非public的方法,如果标记了@Transactional也不会报错,但方法没有事务功能。
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<bean id="transactionTemplate"
class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager">
<ref bean="transactionManager"/>
property>
bean>
使用事务模板需要首先在代码中加入事务模板的注入
@Autowired
private TransactionTemplate transactionTemplate;
使用:
//返回值根据需求自己调整
int result = (int)transactionTemplate
.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
//要执行的代码
return 1;
}
});
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties">property>
bean>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<property name="maxIdle" value="${maxIdle}" />
<property name="minIdle" value="${minIdle}" />
<property name="maxTotal" value="${maxTotal}" />
bean>
<bean id="sqlSessionBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource">property>
<property name="configLocation" value="classpath:mybatisConfig.xml">property>
bean>
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.base.dao">property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionBean">property>
bean>
<!—事务管理器-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionTemplate"
class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager">
<ref bean="transactionManager" />
property>
bean>
beans>
在src/main/java下新建包com.base.service,用来存储业务代码
在src/main/resources下新建spring-service.xml文件,配置如下:
<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">
<context:component-scan base-package="com.base.service"/>
<context:annotation-config/>
beans>
在src/main/java下新建包com.base.web.controller,用来存放控制器
在src/main/webapp/WEB-INF新建views文件夹,用来存放视图文件
在src/main/webapp/WEB-INF下新建spring-mvc.xml文件
<mvc:annotation-driven>
<mvc:message-converters>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8value>
list>
property>
bean>
mvc:message-converters>
mvc:annotation-driven>
<context:component-scan base-package="com.base.web.controller"/>
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/views/" />
<property name="defaultEncoding" value="UTF-8" />
bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true" />
<property name="prefix" value="" />
<property name="suffix" value=".ftl" />
<property name="contentType" value="text/html;charset=UTF-8" />
<property name="exposeSpringMacroHelpers" value="true" />
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
bean>
<mvc:resources location="/static/js/" mapping="/js/**"/>
<mvc:resources location="/static/css/" mapping="/css/**"/>
<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.base.web.controller"/>
<mvc:resources location="/static/js/" mapping="/js/**"/>
<mvc:resources location="/static/css/" mapping="/css/**"/>
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/views/" />
<property name="defaultEncoding" value="UTF-8" />
bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true" />
<property name="prefix" value="" />
<property name="suffix" value=".ftl" />
<property name="contentType" value="text/html;charset=UTF-8" />
<property name="exposeSpringMacroHelpers" value="true" />
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
bean>
<mvc:annotation-driven>
<mvc:message-converters>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8value>
list>
property>
bean>
mvc:message-converters>
mvc:annotation-driven>
beans>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>ssmdisplay-name>
<welcome-file-list>
<welcome-file>index.htmlwelcome-file>
welcome-file-list>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>
classpath:spring-dao.xml,
classpath:spring-service.xml
param-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>appServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>/WEB-INF/spring-mvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>appServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>characterFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
-- MySQL Script generated by MySQL Workbench
-- Wed Nov 8 17:14:18 2017
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
DROP SCHEMA IF EXISTS `mydb` ;
-- --s---------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET utf8 ;
USE `mydb` ;
-- -----------------------------------------------------
-- Table `mydb`.`test`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`test` (
`test_id` VARCHAR(64) NOT NULL,
`test_content` TEXT NULL,
PRIMARY KEY (`test_id`))
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
INSERT INTO `test` VALUES ('1','ssm框架整合!');
在src/main/java下创建com.base.domain包,在包中创建Test类,代码如下
package com.base.domain;
import java.io.Serializable;
/**
* @author xuzhen
*
*/
public class Test implements Serializable{
private static final long serialVersionUID = -227124296105328094L;
private String testId;
private String testContent;
public Test() {}
public String getTestId() {
return testId;
}
public void setTestId(String testId) {
this.testId = testId;
}
public String getTestContent() {
return testContent;
}
public void setTestContent(String testContent) {
this.testContent = testContent;
}
}
在com.base.dao包下创建TestMapper.接口,代码如下:
package com.base.dao;
import java.util.List;
import com.base.domain.Test;
public interface TestMapper {
List getTests();
}
在src/main/resources/mapper文件夹下创建TestMapper.xml,配置如下:
<mapper namespace="com.base.dao.TestMapper">
<resultMap type="com.base.domain.Test" id="TESTMAP">
<id column="test_id" property="testId"/>
<result column="test_content" property="testContent"/>
resultMap>
<select id="getTests" resultMap="TESTMAP">
select * from test
select>
mapper>
在mappers标签内添加
<mapper resource="mapper/TestMapper.xml"/>
在com.base.service包下创建TestManager接口
创建com.base.service.impl包,在包中创建TestManager的实现类TestManagerImpl,代码如下
TestManager.java
package com.base.service;
import java.util.List;
import com.base.domain.Test;
public interface TestManager {
List list();
}
TestManagerImpl.java
package com.base.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.base.dao.TestMapper;
import com.base.domain.Test;
import com.base.service.TestManager;
@Service
public class TestManagerImpl implements TestManager {
@Autowired
private TestMapper testMapper;
@Override
public List list() {
// TODO Auto-generated method stub
return testMapper.getTests();
}
}
在com.base.web.controller包中创建TestController类,代码如下
package com.base.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.base.service.TestManager;
@Controller
public class TestController {
@Autowired
private TestManager testManager;
@RequestMapping("/")
public ModelAndView index() {
ModelAndView mav = new ModelAndView("index");
mav.addObject("tests", testManager.list());
return mav;
}
}
在src/main/webapp/WEB-INF/views下新建index.ftl文件,代码如下
<html>
<head>
<meta charset="utf-8"/>
<title>indextitle>
head>
<body>
<h1>欢迎来到ssm框架整合!h1>
<#list tests as test>
<p>${test.testId} ------ ${test.testContent}p>
#list>
body>
html>
右键项目,点击Run As,然后点击Maven Build,命令中输入jetty:run
在浏览器上输入localhost:8080(maven jetty插件默认端口8080)
下载代码