分享

SSM 框架 Maven项目整合实例

 Levy_X 2017-10-10

这里写图片描述


我是根据这篇博客自己学习这个实例的:AndyLizh的专栏 SSM框架——详细整合教程(Spring SpringMVC MyBatis)
上面的这篇博客里有怎么搭建 Maven 环境,根据数据表自动生成 Mybatis 的Dao层,Service层,Maping xml文件等教程。

下面是我的实例实现的详细步骤、源代码和一些笔记、遇到的问题

版本信息

Eclipse版本 Neon.1a Release (4.6.1) apache-maven-3.3.9 数据库 MySQL5.7.12
  • 1
  • 2
  • 3

maven 配置的中央仓库阿里云地址

setting.xml

. . <mirrors> <mirror> <id>alimaven</id> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror> </mirrors> . .
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

完整项目结构

这里写图片描述

SSM项目创建过程

源代码下载

1.新建一个Maven Project

这里写图片描述

建好之后会提示下面的错误:

The superclass 'javax.servlet.http.HttpServlet' was not found on the Java Build Path index.jsp
  • 1

在项目右键 Java Build Path 添加 Tomcat 服务器的依赖

这里写图片描述

修改 JRE 版本, Edit 更改为 Eclipse 工作空间默认的 JRE 版本,我的是1.8

之后还要在pom.xml文件中声明 jre 的版本(配置pom.xml文件时给出),和你Java Build Path中配置的版本要相同,否则 maven update project又会回到1.5版本,这个版本和项目目录下.settings/org.eclipse.wst.common.project.facet.core.xml的配置有关

... <plugins> <!-- 修改maven默认的JRE编译版本 防止maven update project之后 把jre配置的成默认的1.5 根据自己的情况更改为1.7或1.8 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

这里写图片描述

2.配置Maven Project的pom.xml 文件

默认的 pom.xml 内容:

pom.xml

<project xmlns='http://maven./POM/4.0.0' xmlns:xsi='http://www./2001/XMLSchema-instance' xsi:schemaLocation='http://maven./POM/4.0.0 http://maven./maven-v4_0_0.xsd'> <modelVersion>4.0.0</modelVersion> <groupId>com.jxust</groupId> <artifactId>SSM-Test2</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SSM-Test2 Maven Webapp</name> <url>http://maven.</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>SSM-Test2</finalName> </build> </project>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

Maven Project 最重要的就是配置这个 pom.xml 文件,我在引用别人的pom.xml文件时,发生了很多问题,这和 maven 中央仓库的地址应该也有关系。

说到阿里云的maven中央仓库的jar包,在我的测试中,像Spring 和Mybatis 最新的jar包都还没有,需要低一个版本才有

在配置 pom.xml 过程中,遇到了的几个问题:


  • jackjson

2.0版本前叫org.codehaus.jackson ,2.0版本之后com.fasterxml.jackson ,配置方式不同
<!-- 2.0版本之后引入JSON --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.5</version> </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
<!-- 2.0版本之前 引入JSON --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6


  • mybatis-spring

升级 Spring 或者 Mybatis 的版本是,mybatis-spring 包的版本也要跟着升级
spring 版本 4.0.2,Mybatis 的版本为3.2.6时,mybatis-spring的jar包1.2.0就行
spring 版本 4.3.3,Mybatis 的版本为3.4.0时,mybatis-spring的jar包1.3.0才可以
<!--mybatis spring 插件 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7


  • org.mybatis.spring.SqlSessionFactoryBean找不到

配置了mybatis spring 版本的不对
.


Maven引入需要的SSM 框架jar包,修改后:
pom.xml

<project xmlns='http://maven./POM/4.0.0' xmlns:xsi='http://www./2001/XMLSchema-instance' xsi:schemaLocation='http://maven./POM/4.0.0 http://maven./maven-v4_0_0.xsd'> <modelVersion>4.0.0</modelVersion> <groupId>com.jxust</groupId> <artifactId>SSM-Test2</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SSM-Test2 Maven Webapp</name> <url>http://maven.</url> <properties> <!-- spring版本号 --> <spring.version>4.3.3.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.4.0</mybatis.version> <!-- log4j日志文件管理包版本 --> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <!-- 表示开发的时候引入,发布的时候不会加载此包 --> <scope>test</scope> </dependency> <!-- spring核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!--mybatis spring 插件 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!-- 导入java ee jar 包 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- 导入Mysql数据库链接jar包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.25</version> </dependency> <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- JSTL标签类 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 日志文件管理包 --> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- 格式化对象,方便输出日志 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</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 --> <!-- 引入JSON --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.5</version> </dependency> <!-- 上传组件包 --> <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> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> </dependencies> <build> <finalName>SSM-Test2</finalName> <plugins> <!-- 修改maven默认的JRE编译版本 防止maven update project之后 把jre配置的成默认的1.5 根据自己的情况更改为1.7或1.8 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187

有些jar包并不一定会用到

之后保存,右击项目-maven-update project,如果出现以下的异常

JavaServer Faces 2.2 can not be installed : One or more constraints have not been satisfied. JavaServer Faces 2.2 requires Dynamic Web Module 2.5 or newer. SSM-Test2
  • 1
  • 2

这是web.xml文件头信息配置的不正确,原来的2.3,不符合要求。

解决步骤1:web.xml头信息替换为下面的代码:

web.xml

<?xml version='1.0' encoding='UTF-8'?> <web-app xmlns:xsi='http://www./2001/XMLSchema-instance' xmlns='http://java./xml/ns/javaee' xsi:schemaLocation='http://java./xml/ns/javaee http://java./xml/ns/javaee/web-app_3_0.xsd' id='WebApp_ID' version='3.0'> </web-app>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

解决步骤2:关闭Eclipse,修改项目目录下.settings/org.eclipse.wst.common.project.facet.core.xml的配置

<installed facet='jst.web' version='2.3'/>
  • 1

改为

<installed facet='jst.web' version='3.0'/>
  • 1

重启Eclipse,右击项目-maven-update project(不行,就先移除项目,导入)

具体步骤参考:http://www.cnblogs.com/jebeljebel/p/4421098.html

项目结构为:
这里写图片描述

之后可以在 Java Build Path 中查看自己 maven 下载的jar包。

这里写图片描述

3.Spring与MyBatis的整合

这里写图片描述

3.1数据库连接配置文件

jdbc.properties

driver=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/db_ssm username=root password=root initialSize=0 maxActive=20 maxIdle=20 minIdle=1 maxWait=60000
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

注意字符后面不要带空格,特别是当你复制别人的代码时,例如 ‘root ‘,我就是犯了这个错误

3.2 Spring文件中配置mybatis

包的路径,在创建之后,记得改为自己的路径

spring-mybatis.xml

<?xml version='1.0' encoding='UTF-8'?> <beans xmlns='http://www./schema/beans' xmlns:xsi='http://www./2001/XMLSchema-instance' xmlns:context='http://www./schema/context' xmlns:mvc='http://www./schema/mvc' xmlns:tx='http://www./schema/tx' xsi:schemaLocation='http://www./schema/beans http://www./schema/beans/spring-beans-4.2.xsd http://www./schema/context http://www./schema/context/spring-context-4.3.xsd http://www./schema/mvc http://www./schema/mvc/spring-mvc-4.3.xsd http://www./schema/tx http://www./schema/tx/spring-tx-4.3.xsd'> <!-- 自动扫描 --> <context:component-scan base-package='com.jxust.ssm' > <!-- 不扫描@Controller注解的类--> <context:exclude-filter type='annotation' expression='org.springframework.stereotype.Controller'/> </context:component-scan> <!-- 引入配置文件 --> <bean id='propertyConfigurer' class='org.springframework.beans.factory.config.PropertyPlaceholderConfigurer'> <property name='location' value='classpath:jdbc.properties' /> </bean> <bean id='dataSource' class='org.apache.commons.dbcp.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='initialSize' value='${initialSize}'></property> <!-- 连接池最大数量 --> <property name='maxActive' value='${maxActive}'></property> <!-- 连接池最大空闲 --> <property name='maxIdle' value='${maxIdle}'></property> <!-- 连接池最小空闲 --> <property name='minIdle' value='${minIdle}'></property> <!-- 获取连接最大等待时间 --> <property name='maxWait' value='${maxWait}'></property> </bean> <!-- spring和MyBatis整合,不需要mybatis的配置映射文件 --> <bean id='sqlSessionFactory' class='org.mybatis.spring.SqlSessionFactoryBean'> <property name='dataSource' ref='dataSource' /> <!-- 自动扫描mapping.xml文件 --> <property name='mapperLocations' value='classpath:com/jxust/ssm/mapping/*.xml'></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 动态代理实现 不用写dao的实现类--> <bean class='org.mybatis.spring.mapper.MapperScannerConfigurer'> <property name='basePackage' value='com.jxust.ssm.dao' /> <property name='sqlSessionFactoryBeanName' value='sqlSessionFactory'></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id='transactionManager' class='org.springframework.jdbc.datasource.DataSourceTransactionManager'> <property name='dataSource' ref='dataSource' /> </bean> <tx:annotation-driven transaction-manager='transactionManager'/> <!-- 在这里我有一个疑惑,原文博客这里并没有配置事务注解,我测试了向数据库添加数据,也能成功,(我在写Hibernate是需要配置事务注解的) 不知道是不是,service实现类,bean 使用了注解的方式,还是其他什么的 这里我把事务注解加上 spring、mybatis 配置方式 可以看这篇博客:http://blog.csdn.net/qh_java/article/details/51601139 --> </beans>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69

3.3 log4j 的配置

通过日志来输出各种调试信息

log4j.properties

#定义LOG输出级别 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 # 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志 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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

3.4 创建 MySQL 数据库和表

建表语句和原始数据

mysql> use db_ssm; Database changed mysql> CREATE TABLE tb_user( -> id int(11) NOT NULL AUTO_INCREMENT, -> user_name varchar(40) NOT NULL, -> password varchar(40) NOT NULL, -> age int(4) NOT NULL, -> PRIMARY KEY(id)) -> ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; Query OK, 0 rows affected (0.33 sec) mysql> select * from tb_user; ---- ----------- ---------- ----- | id | user_name | password | age | ---- ----------- ---------- ----- | 1 | 李白 | 123454 | 23 | | 2 | 杜甫 | 234234 | 23 | ---- ----------- ---------- ----- 2 rows in set (0.00 sec)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

3.5 利用MyBatis Generator自动创建代码

该工具可根据MySQL中的表(tb_user)自动创建实体类、MyBatis映射文件以及Dao接口
参考博文:http://blog.csdn.net/zhshulin/article/details/23912615

这里写图片描述

红色部分为自动生成的文件,UserMaping.xml里各种包路径,要修改成自己的,尤其是namespace,要关联为创建的UserDao(因为使用了动态代理实现)

你可以自己去尝试自动创建,下面给出这3个文件(注释是我加的)。

User.java

package com.jxust.ssm.pojo; /** * 用户实体类 * 对应数据表tb_user * @author Peng * @Date2016年12月10日下午10:30:16 */ public class User { private Integer id; private String userName; private String password; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return 'User [id=' id ', userName=' userName ', password=' password ', age=' age ']'; } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53

UserDao.java

package com.jxust.ssm.dao; import com.jxust.ssm.pojo.User; /** * User类Dao层接口 * * 之前我们会在dao层自己手动实现dao层然后自动注入SqlSessionTemplate 实例 * 来调用具体的方法 比如 insert('','') selectOne('','') 等方法 * 其中第一个参数就是映射文件的地址: namespace id 而第二个参数就是传递的条件这样mybatis * 就会按照我们传递的这两个参数找到具体的映射文件进行解析查询。 * 而这里使用动态代理就省去了我们实现dao接口的这一步骤,而是由spring提我们实现了 * @author Peng * @Date2016年12月10日下午10:31:27 */ public interface UserDao { int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

自动创建的文件中,有增删改查的各种方法,动态SQL等,如果你想了解详细的使用方法:http://blog.csdn.net/peng_hong_fu/article/details/53235271

UserMapper.xml

<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE mapper PUBLIC '-////DTD Mapper 3.0//EN' 'http:///dtd/mybatis-3-mapper.dtd' > <!-- namespace的值就是dao接口的完整路径,就这个demo而言namespace 就是userDao.java的完整路径--> <mapper namespace='com.jxust.ssm.dao.UserDao'> <resultMap id='BaseResultMap' type='com.jxust.ssm.pojo.User'> <id column='id' property='id' jdbcType='INTEGER' /> <result column='user_name' property='userName' jdbcType='VARCHAR' /> <result column='password' property='password' jdbcType='VARCHAR' /> <result column='age' property='age' jdbcType='INTEGER' /> </resultMap> <sql id='Base_Column_List'> id, user_name, password, age </sql> <select id='selectByPrimaryKey' resultMap='BaseResultMap' parameterType='java.lang.Integer'> select <include refid='Base_Column_List' /> from tb_user where id = #{id,jdbcType=INTEGER} </select> <delete id='deleteByPrimaryKey' parameterType='java.lang.Integer'> delete from tb_user where id = #{id,jdbcType=INTEGER} </delete> <insert id='insert' parameterType='com.jxust.ssm.pojo.User'> insert into tb_user (id, user_name, password, age) values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}) </insert> <insert id='insertSelective' parameterType='com.jxust.ssm.pojo.User'> insert into tb_user <trim prefix='(' suffix=')' suffixOverrides=','> <if test='id != null'> id, </if> <if test='userName != null'> user_name, </if> <if test='password != null'> password, </if> <if test='age != null'> age, </if> </trim> <trim prefix='values (' suffix=')' suffixOverrides=','> <if test='id != null'> #{id,jdbcType=INTEGER}, </if> <if test='userName != null'> #{userName,jdbcType=VARCHAR}, </if> <if test='password != null'> #{password,jdbcType=VARCHAR}, </if> <if test='age != null'> #{age,jdbcType=INTEGER}, </if> </trim> </insert> <update id='updateByPrimaryKeySelective' parameterType='com.jxust.ssm.pojo.User'> update tb_user <set> <if test='userName != null'> user_name = #{userName,jdbcType=VARCHAR}, </if> <if test='password != null'> password = #{password,jdbcType=VARCHAR}, </if> <if test='age != null'> age = #{age,jdbcType=INTEGER}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id='updateByPrimaryKey' parameterType='com.jxust.ssm.pojo.User'> update tb_user set user_name = #{userName,jdbcType=VARCHAR}, password = #{password,jdbcType=VARCHAR}, age = #{age,jdbcType=INTEGER} where id = #{id,jdbcType=INTEGER} </update> </mapper>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96

3.6 创建 Service层 接口和实现类

这里写图片描述

UserService.java

package com.jxust.ssm.service; import com.jxust.ssm.pojo.User; /** * Service层接口 * @author Peng * @Date2016年12月11日下午7:05:05 */ public interface UserService { //根据id查找 public User getUserById(Integer userid); //添加一条数据 public int insert(User user); }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

UserServiceImpl.java

package com.jxust.ssm.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.jxust.ssm.dao.UserDao; import com.jxust.ssm.pojo.User; import com.jxust.ssm.service.UserService; /** * userService 接口的实现类 * * @author Peng * @Date2016年12月11日上午11:50:01 */ @Transactional @Service('userService') public class UserServiceImpl implements UserService { /** * 因为没有在spring的文件中显式的声明userService实现类,直接通过getBean得到 userService 会找不到 * 需要显式配置 @Service ('userService'),指定bean的名称 * 相当与<bean id='userService' class='com.jxust.ssm.service.impl.UserServiceImpl'></bean> */ @Resource private UserDao userDao; public User getUserById(Integer userid) { return this.userDao.selectByPrimaryKey(userid); } @Override public int insert(User user) { return this.userDao.insert(user); } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

3.7 Junit 测试Spring整合Mybatis

这里写图片描述

使用Junit测试,TestMyBatis为使用 spring 的测试方法,TestMyBatis2为不使用 spring 的普通方法

TestMyBatis.java

package com.test; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.alibaba.fastjson.JSON; import com.jxust.ssm.pojo.User; import com.jxust.ssm.service.UserService; @RunWith(SpringJUnit4ClassRunner.class) // 表示继承了SpringJUnit4ClassRunner类 @ContextConfiguration(locations = { 'classpath:spring-mybatis.xml' }) /** * 测试spring整合mybatis spring方式 * * @author Peng * @Date2016年12月11日上午11:52:56 */ public class TestMyBatis { private static Logger logger = Logger.getLogger(TestMyBatis.class); @Resource private UserService userService = null; /** * 测试查询 */ @Test public void test1() { User user = userService.getUserById(2); logger.info('值:' user.getUserName()); logger.info(JSON.toJSONString(user)); } /** * 测试添加 */ @Test public void test2() { User user = new User(); user.setUserName('杜甫3'); user.setPassword('234234'); user.setAge(23); int count = userService.insert(user); logger.info('count:' count); } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

TestMyBatis2.java

package com.test; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.jxust.ssm.pojo.User; import com.jxust.ssm.service.UserService; /** * 测试spring整合mybatis 普通方式 * @author Peng * @Date2016年12月11日上午11:52:11 */ public class TestMyBatis2 { private ApplicationContext ac = null; private UserService userService = null; @Before public void before() { ac = new ClassPathXmlApplicationContext('classpath:spring-mybatis.xml'); userService = (UserService) ac.getBean('userService'); } /** * 测试查询 */ @Test public void test1() { User user = userService.getUserById(2); System.out.println(user.toString()); } /** * 测试添加 */ @Test public void test2() { User user = new User(); user.setUserName('杜甫'); user.setPassword('234234'); user.setAge(23); int count = userService.insert(user); System.out.println('插入' count '条数据成功'); } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

测试结果:

... [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring [com.test.TestMyBatis] - 值:杜甫 [com.test.TestMyBatis] - {'age':23,'id':2,'password':'234234','userName':'杜甫'} [org.springframework.context.support.GenericApplicationContext] - Closing org.springframework.context.support.GenericApplicationContext@55d56113: startup date [Sun Dec 11 20:23:43 CST 2016]; root of context hierarchy
  • 1
  • 2
  • 3
  • 4
  • 5

正确输入结果,则测试成功!

项目结构为:

这里写图片描述
这里写图片描述

4.项目整合 SpringMVC

SpringMVC 涉及到视图了,需要配置web.xml文件和SpringMVC的配置文件了

4.1配置web.xml

web.xml

<?xml version='1.0' encoding='UTF-8'?> <web-app xmlns:xsi='http://www./2001/XMLSchema-instance' xmlns='http://java./xml/ns/javaee' xsi:schemaLocation='http://java./xml/ns/javaee http://java./xml/ns/javaee/web-app_3_0.xsd' id='WebApp_ID' version='3.0'> <!-- 编码过滤器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring监听器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--Spring MVC 配置servlet --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48

使用 Eclipse在 web.xml 文件中,可以使用 Alt /快速创建ContextLoaderListenerDispatcherServlet两个过滤器配置

这里写图片描述

4.2 配置SpringMVC配置文件springmvc.xml

这里写图片描述

springmvc.xml

<?xml version='1.0' encoding='UTF-8'?> <beans xmlns='http://www./schema/beans' xmlns:xsi='http://www./2001/XMLSchema-instance' xmlns:context='http://www./schema/context' xmlns:mvc='http://www./schema/mvc' xsi:schemaLocation='http://www./schema/beans http://www./schema/beans/spring-beans.xsd http://www./schema/context http://www./schema/context/spring-context-4.0.xsd http://www./schema/mvc http://www./schema/mvc/spring-mvc-4.0.xsd'> <!-- 自动扫描该包 @controller注解的类--> <context:component-scan base-package='com.jxust.ssm.controller'/> <!-- 静态资源处理 --> <mvc:default-servlet-handler/> <!--自动注册 RequestMappingHandlerMapping、RequestMappingHandlerAdapter 等bean --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 定义跳转的文件的前后缀 ,视图模式配置--> <bean class='org.springframework.web.servlet.view.InternalResourceViewResolver'> <property name='prefix' value='/WEB-INF/views/' /> <property name='suffix' value='.jsp' /> </bean> </beans>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

spring配置文件和springmvc配置文件的两个自动扫描的路径范围,最好不要重复,使用<context:exclude-filter/><context:include-filter/>指定不扫描和扫描的条件

4.3 创建 SpringMVC 的Controller

这里写图片描述

UserController.java

package com.jxust.ssm.controller; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.jxust.ssm.pojo.User; import com.jxust.ssm.service.UserService; @Controller public class UserController { /** * 使用@Autowired也可以,@Autowired默认按类型装配 * @Resource 默认按名称装配,当找不到与名称匹配的bean才会按类型装配。 */ @Resource private UserService userService; /** * 测试查询 * * @param id * @param model * @return */ @RequestMapping('/showUser') public String testtoshowUser(@RequestParam(value = 'id') Integer id, Model model) { System.out.println('id:' id); User user = userService.getUserById(id); model.addAttribute('user', user); return 'showUser'; } /** * 测试添加数据 * * @param id * @param model * @return */ @RequestMapping('/insertUser') public String testinsertUser() { User user = new User(); user.setUserName('李清照'); user.setPassword('3232322'); user.setAge(22); int count = userService.insert(user); System.out.println('插入' count '条数据成功'); return 'showUser'; } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54

4.4 JSP页面

这里写图片描述

index.jsp

<%@ page language='java' contentType='text/html; charset=UTF-8' pageEncoding='UTF-8'%> <!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www./TR/html4/loose.dtd'> <html> <head> <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'> <title>index.jsp</title> </head> <body> <a href='showUser?id=2'>ShowUser page</a><br> <a href='insertUser'>insertUser </a> </body> </html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

showUser.jsp

<%@ page language='java' contentType='text/html; charset=UTF-8' pageEncoding='UTF-8'%> <!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www./TR/html4/loose.dtd'> <html> <head> <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'> <title>测试</title> </head> <body> id:${user.id} <br> userName: ${user.userName} <br> password: ${user.password} <br> age: ${user.age} <br> </body> </html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

JSP页面写完,就可以发布了

4.5 项目发布到Tomcat服务器上

这里写图片描述

源码下载

Maven 项目就是小,没有jar包,只有 30k

源代码下载:http://download.csdn.net/detail/peng_hong_fu/9708357

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多