Maven+SSM框架(Spring+SpringMVC+MyBatis)(二)

1.基本概念

 

2.支出环境搭建

 

3.Maven Web项目开创

 

4.SSM整合

此次重组我分点儿单布局文件:

  1)分别是spring-mybatis.xml,包含spring和mybatis的安排文件,

  2)还起个是spring-mvc的布局文件,

  3)其余有2个资源文件:jdbc.propertis和log4j.properties

以下是框架版本和来源

  Spring 4.0.2 RELEASE(PS:无需手动下载,Maven会自动下)

  Spring MVC 4.0.2 RELEASE(PS:无需手动下载,Maven会自动下)

  MyBatis
3.2.6(下载:https://github.com/mybatis/mybatis-3/releases?after=mybatis-3.2.7

*设置 xml 文件之代码提醒成效 

MyBatis,打 开 Eclipse 依次选用 Window > Preferences > Xml > Xml Files > Editor > Content Assist > Auto activation > Prompt when these characters are inserted,设置框中默认是 <=: ,改成为<=:qwertyuioplkjhgfdsazxcvbnm就ok了。

脚是路总体结构,先有只印象

MyBatis 1

4.1 Maven引入需要的jar包

为便于前面说之早晚不欲引入JAR包,我这里间接叫起有需要之JAR包,这依旧核心的JAR包,每个包之是怎的都出注释,就不再多说了

pom.xml

  1 <properties>
  2       <!-- spring版本号 -->
  3       <spring.version>4.0.2.RELEASE</spring.version>
  4       <!-- mybatis版本号 -->
  5     <mybatis.version>3.2.6</mybatis.version>
  6     <!-- log4j日志文件管理包版本 -->
  7     <slf4j.version>1.7.7</slf4j.version>
  8     <log4j.version>1.2.17</log4j.version>
  9   </properties>
 10   <dependencies>
 11     <dependency>
 12       <groupId>junit</groupId>
 13       <artifactId>junit</artifactId>
 14       <version>3.8.1</version>
 15       <scope>test</scope>
 16     </dependency>
 17     <!-- 导入java ee jar包(可以去除index.jsp报错) -->
 18     <dependency>
 19         <groupId>javax</groupId>
 20         <artifactId>javaee-api</artifactId>
 21         <version>7.0</version>
 22     </dependency>
 23     <dependency>
 24         <groupId>junit</groupId>
 25         <artifactId>junit</artifactId>
 26         <version>4.11</version>
 27         <!-- 表示开发的时候引入,发布的时候不会加载此包 -->
 28         <scope>test</scope>
 29     </dependency>
 30     <!-- spring核心包 -->
 31     <dependency>
 32         <groupId>org.springframework</groupId>
 33         <artifactId>spring-core</artifactId>
 34         <version>${spring.version}</version>
 35     </dependency>
 36     <dependency>
 37         <groupId>org.springframework</groupId>
 38         <artifactId>spring-web</artifactId>
 39         <version>${spring.version}</version>
 40     </dependency>
 41     <dependency>
 42         <groupId>org.springframework</groupId>
 43         <artifactId>spring-oxm</artifactId>
 44         <version>${spring.version}</version>
 45     </dependency>
 46     <dependency>
 47         <groupId>org.springframework</groupId>
 48         <artifactId>spring-tx</artifactId>
 49         <version>${spring.version}</version>
 50     </dependency>
 51     <dependency>
 52         <groupId>org.springframework</groupId>
 53         <artifactId>spring-jdbc</artifactId>
 54         <version>${spring.version}</version>
 55     </dependency>
 56     <dependency>
 57         <groupId>org.springframework</groupId>
 58         <artifactId>spring-webmvc</artifactId>
 59         <version>${spring.version}</version>
 60     </dependency>
 61     <dependency>
 62         <groupId>org.springframework</groupId>
 63         <artifactId>spring-aop</artifactId>
 64         <version>${spring.version}</version>
 65     </dependency>
 66     <dependency>
 67         <groupId>org.springframework</groupId>
 68         <artifactId>spring-context-support</artifactId>
 69         <version>${spring.version}</version>
 70     </dependency>
 71     <dependency>
 72         <groupId>org.springframework</groupId>
 73         <artifactId>spring-test</artifactId>
 74         <version>${spring.version}</version>
 75     </dependency>
 76     <!-- mybatis核心包 -->
 77     <dependency>
 78         <groupId>org.mybatis</groupId>
 79         <artifactId>mybatis</artifactId>
 80         <version>${mybatis.version}</version>
 81     </dependency>
 82     <!-- mybatis/spring包 -->
 83     <dependency>
 84         <groupId>org.mybatis</groupId>
 85         <artifactId>mybatis-spring</artifactId>
 86         <version>1.2.2</version>
 87     </dependency>
 88     <!-- 导入Mysql数据库链接jar包 -->
 89     <dependency>
 90         <groupId>mysql</groupId>
 91         <artifactId>mysql-connector-java</artifactId>
 92         <version>5.1.30</version>
 93     </dependency>
 94     <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
 95     <dependency>
 96         <groupId>commons-dbcp</groupId>
 97         <artifactId>commons-dbcp</artifactId>
 98         <version>1.2.2</version>
 99     </dependency>
100     <!-- JSTL标签类 -->
101     <dependency>
102         <groupId>jstl</groupId>
103         <artifactId>jstl</artifactId>
104         <version>1.2</version>
105     </dependency>
106     <!-- 日志文件管理包 -->
107     <!-- log start -->
108     <dependency>
109         <groupId>log4j</groupId>
110         <artifactId>log4j</artifactId>
111         <version>${log4j.version}</version>
112     </dependency>
113     <!-- 格式化对象,方便输出日志 -->
114     <dependency>
115         <groupId>com.alibaba</groupId>
116         <artifactId>fastjson</artifactId>
117         <version>1.1.41</version>
118     </dependency>
119     <dependency>
120         <groupId>org.slf4j</groupId>
121         <artifactId>slf4j-api</artifactId>
122         <version>${slf4j.version}</version>
123     </dependency>
124     <dependency>
125         <groupId>org.slf4j</groupId>
126         <artifactId>slf4j-log4j12</artifactId>
127         <version>${slf4j.version}</version>
128     </dependency>
129     <!-- log end -->
130     <!-- 映入JSON -->
131     <dependency>
132         <groupId>org.codehaus.jackson</groupId>
133         <artifactId>jackson-mapper-asl</artifactId>
134         <version>1.9.13</version>
135     </dependency>
136     <!-- 上传组件包 -->
137     <dependency>
138         <groupId>commons-fileupload</groupId>
139         <artifactId>commons-fileupload</artifactId>
140         <version>1.3.1</version>
141     </dependency>
142     <dependency>
143         <groupId>commons-io</groupId>
144         <artifactId>commons-io</artifactId>
145         <version>2.4</version>
146     </dependency>
147     <dependency>
148         <groupId>commons-codec</groupId>
149         <artifactId>commons-codec</artifactId>
150         <version>1.9</version>
151     </dependency>
152   </dependencies>
153   <build>
154     <finalName>hongceshi</finalName>
155     <plugins>
156      <plugin>
157         <groupId>org.apache.maven.plugins</groupId>
158         <artifactId>maven-compiler-plugin</artifactId>
159         <version>3.5.1</version>
160         <configuration>
161             <source>1.8</source>
162             <target>1.8</target>
163             <encoding>UTF-8</encoding>
164         </configuration>
165      </plugin>
166   </plugins>
167   </build>

MyBatis 2

4.2 Spring与MyBatis的整合

4.1之jar包引入之后,首先进行Spring和MyBatis整合,然后再次拓展JUnit测试,先押一个门类协会图:

MyBatis 3

4.2.1 建立JDBC属性文件(有背景颜色有用依照自己音讯修改)

jdbc.properties

 1 driver=com.mysql.jdbc.Driver
 2 url=jdbc:mysql://127.0.0.1:3306/ceshi?useUnicode=true&characterEncoding=UTF-8
 3 username=root
 4 password=root
 5 #定义初始连接数
 6 initialSize=0
 7 #定义最大连接数
 8 maxActive=20
 9 #定义最大空闲
10 maxIdle=20
11 #定义最小空闲
12 minIdle=1
13 #定义最长等待时间
14 maxWait=60000

4.2.2 Log4j的配备(跳了此步也从没影响)

为了有利于调试,一般还会面使用日志来输出消息,Log4j是Apache的一个开放源代码项目,通过接纳Log4j,大家得控制日志新闻输送的目的地是控制台、文件、GUI组件,甚至是拟接口服务器、NT的风波记录器、UNIX
Syslog守护进程等;我们啊得决定每一样漫长日志的出口格式;通过定义每一样修日志信息的级别,大家能越来越周到地操纵日志的浮动过程。
Log4j的配置不行粗略,而且为是通用的,下边给出一个核心的安排,换到其他门类面临呢管需做多特别之调动,假诺想做调整仍旧想询问Log4j的各个配置,可以参考:Log4j配置详解 

log4j.properties

 1 #定义LOG输出级别
 2 log4j.rootLogger=INFO,Console,File
 3 #定义日志输出目的地为控制台
 4 log4j.appender.Console=org.apache.log4j.ConsoleAppender
 5 log4j.appender.Console.Target=System.out
 6 #可以灵活地指定日志输出格式,下面一行是指定具体的格式
 7 log4j.appender.Console.layout = org.apache.log4j.PatternLayout
 8 log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
 9 
10 #文件大小到达指定尺寸的时候产生一个新的文件
11 log4j.appender.File = org.apache.log4j.RollingFileAppender
12 #指定输出目录
13 log4j.appender.File.File = logs/springmvcMybist/ssm.log
14 #定义文件最大大小
15 log4j.appender.File.MaxFileSize = 10MB
16 #输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
17 log4j.appender.File.Threshold = ALL
18 log4j.appender.File.layout = org.apache.log4j.PatternLayout
19 log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

4.2.3、建立spring-mybatis.xml配置文件

是文件就用来完成spring和mybatis的构成的。这之中也从不小行安排,首要的就是是自动扫描,自动注入,配置数据库

spring-mybatis.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:mvc="http://www.springframework.org/schema/mvc"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans  
 7                         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
 8                         http://www.springframework.org/schema/context  
 9                         http://www.springframework.org/schema/context/spring-context-4.0.xsd  
10                         http://www.springframework.org/schema/mvc  
11                         http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
12     <!-- 自动扫描 -->
13     <context:component-scan base-package="hzm.ssm" />
14 
15     <!-- 引入配置文件 -->
16     <bean id="propertyConfigurer"
17         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
18         <property name="location" value="classpath:jdbc.properties" />
19     </bean>
20 
21     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
22         destroy-method="close">
23         <property name="driverClassName" value="${driver}" />
24         <property name="url" value="${url}" />
25         <property name="username" value="${username}" />
26         <property name="password" value="${password}" />
27         <!-- 初始化连接大小 -->
28         <property name="initialSize" value="${initialSize}"></property>
29         <!-- 连接池最大数量 -->
30         <property name="maxActive" value="${maxActive}"></property>
31         <!-- 连接池最大空闲 -->
32         <property name="maxIdle" value="${maxIdle}"></property>
33         <!-- 连接池最小空闲 -->
34         <property name="minIdle" value="${minIdle}"></property>
35         <!-- 获取连接最大等待时间 -->
36         <property name="maxWait" value="${maxWait}"></property>
37     </bean>
38 
39     <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
40     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
41         <property name="dataSource" ref="dataSource" />
42         <!-- 自动扫描mapping.xml文件 -->
43         <property name="mapperLocations" value="classpath:hzm/ssm/mapping/*.xml"></property>
44     </bean>
45 
46     <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
47     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
48         <property name="basePackage" value="hzm.ssm.dao" />
49         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
50     </bean>
51 
52     <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
53     <bean id="transactionManager"
54         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
55         <property name="dataSource" ref="dataSource" />
56     </bean>
57 </beans>

4.2.4、JUnit测试

经过以上步骤(log4j不流啊从没影响),我们已形成了Spring和mybatis的三结合,这样我们虽可编制一截测试代码来尝试是否成功了。

4.2.4.1 创设测试用表

既然大家要测试,那么我们就需建立在数据库被树立一个测试表,这个表建的百般简短,SQL语句也:

Mysql新建数据库,执行下语句

 1 #
 2 # Structure for table "user_t"
 3 #
 4 
 5 DROP TABLE IF EXISTS `user_t`;
 6 CREATE TABLE `user_t` (
 7   `id` int(11) NOT NULL AUTO_INCREMENT,
 8   `user_name` varchar(40) NOT NULL,
 9   `password` varchar(255) NOT NULL,
10   `age` int(4) NOT NULL,
11   PRIMARY KEY (`id`)
12 ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
13 
14 #
15 # Data for table "user_t"
16 #
17 
18 INSERT INTO `user_t` VALUES (1,'测试','123456',24);

4.2.4.2、利用MyBatis Generator自动创立代码

不管找找个职务建文件夹(路径最好都是英文),然后以里面盖个src文件夹,下载下面那片独jar包,并手动将generatorConfig.xml拷进去,最后当拖欠公文夹下,执行下的授命(java
-jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml
-overwrite),代码就相会转移到src文件夹里(dao/vo/impl):

以下是欠文件下所需文的截图:

MyBatis 4

 

Mybatis-Generator的下载好到此地方:https://github.com/mybatis/generator/releases

Mysql-connector-java的下载好到之地址:https://dev.mysql.com/downloads/connector/j/

和Hibernate逆向生成一样,这里为需一个布局文件:

generatorConfig.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE generatorConfiguration
 3 PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
 4 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
 5 <generatorConfiguration>
 6     <!-- 数据库驱动 -->
 7     <classPathEntry location="mysql-connector-java-5.1.45-bin.jar" />
 8     <context id="DB2Tables" targetRuntime="MyBatis3">
 9         <commentGenerator>
10             <property name="suppressDate" value="true" />
11             <!-- 是否去除自动生成的注释 true:是 : false:否 -->
12             <property name="suppressAllComments" value="true" />
13         </commentGenerator>
14         <!--数据库链接URL,用户名、密码 -->
15         <jdbcConnection driverClass="com.mysql.jdbc.Driver"
16             connectionURL="jdbc:mysql://127.0.0.1:3306/ceshi" userId="root"
17             password="root">
18         </jdbcConnection>
19         <javaTypeResolver>
20             <property name="forceBigDecimals" value="false" />
21         </javaTypeResolver>
22         <!-- 生成模型的包名和位置 -->
23         <javaModelGenerator targetPackage="hzm.ssm.vo"
24             targetProject="src">
25             <property name="enableSubPackages" value="true" />
26             <property name="trimStrings" value="true" />
27         </javaModelGenerator>
28         <!-- 生成映射文件的包名和位置 -->
29         <sqlMapGenerator targetPackage="hzm.ssm.mapping"
30             targetProject="src">
31             <property name="enableSubPackages" value="true" />
32         </sqlMapGenerator>
33         <!-- 生成DAO的包名和位置 -->
34         <javaClientGenerator type="XMLMAPPER"
35             targetPackage="hzm.ssm.dao" targetProject="src">
36             <property name="enableSubPackages" value="true" />
37         </javaClientGenerator>
38         <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名 -->
39         <table tableName="user_t" domainObjectName="User"
40             enableCountByExample="false" enableUpdateByExample="false"
41             enableDeleteByExample="false" enableSelectByExample="false"
42             selectByExampleQueryId="false"></table>
43     </context>
44 </generatorConfiguration>

急需修改文件配置的地点我都曾拿注释标注出来了,这里的相关路线(如数据库驱动包,生成对应之相干文书地方好由定义)不可知带有中文

点配置文件被的:

1         <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名 -->
2         <table tableName="user_t" domainObjectName="User"
3             enableCountByExample="false" enableUpdateByExample="false"
4             enableDeleteByExample="false" enableSelectByExample="false"
5             selectByExampleQueryId="false"></table>

tableName和domainObjectName为自然择项,分别代表数据库表名和变化的实体vo类名,其它的足打定义去选(一般境况下都为false)

接纳形式介绍:

每当拖欠目录按停Shift键,右键鼠标采用”在此地打开命令窗口”,复制粘贴生成语句之公文代码即可。

MyBatis 5

执行后,src就好成了底3个文本,复制到路对承诺目录下

MyBatis 6

vo:user.java

 1 package hzm.ssm.vo;
 2 
 3 public class User {
 4     private Integer id;
 5 
 6     private String userName;
 7 
 8     private String password;
 9 
10     private Integer age;
11 
12     public Integer getId() {
13         return id;
14     }
15 
16     public void setId(Integer id) {
17         this.id = id;
18     }
19 
20     public String getUserName() {
21         return userName;
22     }
23 
24     public void setUserName(String userName) {
25         this.userName = userName == null ? null : userName.trim();
26     }
27 
28     public String getPassword() {
29         return password;
30     }
31 
32     public void setPassword(String password) {
33         this.password = password == null ? null : password.trim();
34     }
35 
36     public Integer getAge() {
37         return age;
38     }
39 
40     public void setAge(Integer age) {
41         this.age = age;
42     }
43 }

dao:UserMapper

 1 package hzm.ssm.dao;
 2 
 3 import hzm.ssm.vo.User;
 4 
 5 public interface UserMapper {
 6     int deleteByPrimaryKey(Integer id);
 7 
 8     int insert(User record);
 9 
10     int insertSelective(User record);
11 
12     User selectByPrimaryKey(Integer id);
13 
14     int updateByPrimaryKeySelective(User record);
15 
16     int updateByPrimaryKey(User record);
17 }

mapping:UserMapper.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
 3 <mapper namespace="hzm.ssm.dao.UserMapper" >
 4   <resultMap id="BaseResultMap" type="hzm.ssm.vo.User" >
 5     <id column="id" property="id" jdbcType="INTEGER" />
 6     <result column="user_name" property="userName" jdbcType="VARCHAR" />
 7     <result column="password" property="password" jdbcType="VARCHAR" />
 8     <result column="age" property="age" jdbcType="INTEGER" />
 9   </resultMap>
10   <sql id="Base_Column_List" >
11     id, user_name, password, age
12   </sql>
13   <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
14     select 
15     <include refid="Base_Column_List" />
16     from user_t
17     where id = #{id,jdbcType=INTEGER}
18   </select>
19   <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
20     delete from user_t
21     where id = #{id,jdbcType=INTEGER}
22   </delete>
23   <insert id="insert" parameterType="hzm.ssm.vo.User" >
24     insert into user_t (id, user_name, password, 
25       age)
26     values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
27       #{age,jdbcType=INTEGER})
28   </insert>
29   <insert id="insertSelective" parameterType="hzm.ssm.vo.User" >
30     insert into user_t
31     <trim prefix="(" suffix=")" suffixOverrides="," >
32       <if test="id != null" >
33         id,
34       </if>
35       <if test="userName != null" >
36         user_name,
37       </if>
38       <if test="password != null" >
39         password,
40       </if>
41       <if test="age != null" >
42         age,
43       </if>
44     </trim>
45     <trim prefix="values (" suffix=")" suffixOverrides="," >
46       <if test="id != null" >
47         #{id,jdbcType=INTEGER},
48       </if>
49       <if test="userName != null" >
50         #{userName,jdbcType=VARCHAR},
51       </if>
52       <if test="password != null" >
53         #{password,jdbcType=VARCHAR},
54       </if>
55       <if test="age != null" >
56         #{age,jdbcType=INTEGER},
57       </if>
58     </trim>
59   </insert>
60   <update id="updateByPrimaryKeySelective" parameterType="hzm.ssm.vo.User" >
61     update user_t
62     <set >
63       <if test="userName != null" >
64         user_name = #{userName,jdbcType=VARCHAR},
65       </if>
66       <if test="password != null" >
67         password = #{password,jdbcType=VARCHAR},
68       </if>
69       <if test="age != null" >
70         age = #{age,jdbcType=INTEGER},
71       </if>
72     </set>
73     where id = #{id,jdbcType=INTEGER}
74   </update>
75   <update id="updateByPrimaryKey" parameterType="hzm.ssm.vo.User" >
76     update user_t
77     set user_name = #{userName,jdbcType=VARCHAR},
78       password = #{password,jdbcType=VARCHAR},
79       age = #{age,jdbcType=INTEGER}
80     where id = #{id,jdbcType=INTEGER}
81   </update>
82 </mapper>

以入手动创造:

IUserService.java

1 package hzm.ssm.service;
2 
3 import hzm.ssm.vo.User;
4 
5 public interface IUserService {
6     public User getUserById(int userId);
7 }

UserService.java

 1 package hzm.ssm.service.impl;
 2 
 3 import javax.annotation.Resource;
 4 
 5 import org.springframework.stereotype.Service;
 6 
 7 import hzm.ssm.dao.UserMapper;
 8 import hzm.ssm.service.IUserService;
 9 import hzm.ssm.vo.User;
10 
11 @Service("userService")
12 public class UserService implements IUserService {
13     @Resource
14     private UserMapper userDao;
15 
16     public User getUserById(int userId) {
17         return this.userDao.selectByPrimaryKey(userId);
18     }
19 }

4.2.4.4、建立测试类

测试类在src/test/java中确立,上边测试类中注释掉的有的是不以Spring时,一般景色下之同等种植测试方法;假诺使用了Spring那么即便得用声明的方来引入配置文件和类,然后再次以service接口对象注入,就可开展测试了。即便测试成功,表示Spring和Mybatis已经结成了。输出消息运用的凡Log4j打印至控制台

MyBatis 7

TestMyBatis.java

 1 package hzm.ssm.testmybatis;
 2 
 3 import javax.annotation.Resource;
 4 
 5 import org.apache.log4j.Logger;
 6 import org.junit.Test;
 7 import org.junit.runner.RunWith;
 8 import org.springframework.test.context.ContextConfiguration;
 9 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
10 
11 import com.alibaba.fastjson.JSON;
12 
13 import hzm.ssm.service.IUserService;
14 import hzm.ssm.vo.User;
15 
16 @RunWith(SpringJUnit4ClassRunner.class) // 表示继承了这个类
17 @ContextConfiguration(locations = { "classpath:spring-mybatis.xml" })
18 public class TestMyBatis {
19     private static Logger logger = Logger.getLogger(TestMyBatis.class);
20     @Resource
21     private IUserService userService = null;
22 
23     @Test
24     public void test() {
25         User user = userService.getUserById(1);
26         logger.info(user);
27         logger.info("user转为json");
28         logger.info(JSON.toJSONString(user));
29     }
30 }

起头测试:

品种右键Maven->Update Project…(重点),等立异了,右击项目->Run
As->JUnit Test

MyBatis 8

4.3、整合SpringMVC

下边已经完结了2卓殊框架的重组,SpringMVC的配置文件单独放,然后以web.xml中配备结合

4.3.1、配置spring-mvc.xml

重大是活动扫描控制器,视图形式,阐明的启动这三独

spring-mvc.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:mvc="http://www.springframework.org/schema/mvc"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans  
 7                             http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
 8                             http://www.springframework.org/schema/context  
 9                             http://www.springframework.org/schema/context/spring-context-4.0.xsd  
10                             http://www.springframework.org/schema/mvc  
11                             http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
12 
13     <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
14     <bean id="mappingJacksonHttpMessageConverter"
15         class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
16         <property name="supportedMediaTypes">
17             <list>
18                 <value>text/html;charset=UTF-8</value>
19             </list>
20         </property>
21     </bean>
22 
23     <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
24     <bean
25         class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
26         <property name="messageConverters">
27             <list>
28                 <!-- JSON转换器 -->
29                 <ref bean="mappingJacksonHttpMessageConverter" />    
30             </list>
31         </property>
32     </bean>
33 
34     <!-- 对静态资源的访问 -->
35     <!-- <mvc:resources mapping="/js/**" location="/js/" /> 
36         <mvc:resources mapping="/css/**" location="/css/" /> -->
37 
38     <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
39     <context:component-scan base-package="hzm.ssm.controller" />
40 
41     <!-- 添加注解驱动 -->
42     <mvc:annotation-driven enable-matrix-variables="true" />
43     <!-- 允许对静态资源文件的访问 -->
44 
45     <mvc:default-servlet-handler />
46 
47     <!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
48     <bean
49         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
50         <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
51         <property name="prefix" value="/WEB-INF/jsp/" />
52         <property name="suffix" value=".jsp" />
53     </bean>
54 
55     <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
56     <bean id="multipartResolver"
57         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
58         <!-- 默认编码 -->
59         <property name="defaultEncoding" value="UTF-8" />
60         <!-- 文件大小最大值 -->
61         <property name="maxUploadSize" value="10485760000" />
62         <!-- 内存中的最大值 -->
63         <property name="maxInMemorySize" value="40960" />
64     </bean>
65 </beans>

4.3.2、配置web.xml文件

此给spring-mybatis.xml的引入和配备的spring-mvc的Servlet就是以成功SSM整合,从前2框架整合不需要在此地举办任何配置。配置一样发生详细阐明,不多说了。

web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xmlns="http://java.sun.com/xml/ns/javaee"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 5     version="3.0">
 6     <display-name>Archetype Created Web Application</display-name>
 7     
 8     <!-- Spring和mybatis的配置文件 -->
 9     <context-param>
10         <param-name>contextConfigLocation</param-name>
11         <param-value>classpath:spring-mybatis.xml</param-value>
12     </context-param>
13     
14     <!-- 编码过滤器 -->
15     <filter>
16         <filter-name>encodingFilter</filter-name>
17         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
18         <async-supported>true</async-supported>
19         <init-param>
20             <param-name>encoding</param-name>
21             <param-value>UTF-8</param-value>
22         </init-param>
23     </filter>
24     <filter-mapping>
25         <filter-name>encodingFilter</filter-name>
26         <url-pattern>/*</url-pattern>
27     </filter-mapping>
28     
29     <!-- Spring监听器 -->
30     <listener>
31         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
32     </listener>
33     
34     <!-- 防止Spring内存溢出监听器 -->
35     <listener>
36         <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
37     </listener>
38     
39     <!-- Spring MVC servlet -->
40     <servlet>
41         <servlet-name>SpringMVC</servlet-name>
42         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
43         <init-param>
44             <param-name>contextConfigLocation</param-name>
45             <param-value>classpath:spring-mvc.xml</param-value>
46         </init-param>
47         <load-on-startup>1</load-on-startup>
48         <async-supported>true</async-supported>
49     </servlet>
50     <servlet-mapping>
51         <servlet-name>SpringMVC</servlet-name>
52         <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
53         <url-pattern>/</url-pattern>
54     </servlet-mapping>
55     
56     <welcome-file-list>
57         <welcome-file>/index.html</welcome-file>
58         <welcome-file>/index.jsp</welcome-file>
59     </welcome-file-list>
60 </web-app>

4.3.3、测试

时至明日已完结了SSM三大框架的构成了,接下测试一下,假诺成功了,那么恭喜你,假设失败了,继续调试吧,作为程序员就是不歇的和BUG做努力!

4.3.3.1、新建jsp页面

User.jsp   此页面只输出一下用户称,完成一个完好的简流程

MyBatis 9

User.jsp

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

4.3.3.2、建立UserController类

UserController.java

 1 package hzm.ssm.controller;
 2 
 3 import javax.annotation.Resource;
 4 import javax.servlet.http.HttpServletRequest;
 5 
 6 import org.springframework.stereotype.Controller;
 7 import org.springframework.ui.Model;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 
10 import hzm.ssm.service.IUserService;
11 import hzm.ssm.vo.User;
12 
13 @Controller
14 @RequestMapping("/user")
15 public class UserController {
16 
17     @Resource
18     private IUserService userService;
19 
20     @RequestMapping("/showUser")
21     public String toIndex(HttpServletRequest request, Model model) {
22         int userId = Integer.parseInt(request.getParameter("id"));
23         User user = this.userService.getUserById(userId);
24         model.addAttribute("user", user);
25         return "User";
26     }
27 }

4.3.3.3、部署项目

MyBatis 10

MyBatis 11

点击Finish,启动项目,浏览器输入http://localhost:8080/hongceshi/user/showUser?id=1

MyBatis 12

由来SSM框架整合成。

 

然,有一个题目:

MyBatis 13

原因即是编译时莫复制依赖包及WEB-INF/lib里,编译时为平素不生成lib文件夹

MyBatis 14

到解决办法:

以该目录下实施:

cmd命令(依照Java Build
Path的列表得知,只要不改动动包,就无欲更运行是命令) 1 mvn
eclipse:eclipse -Dwtpversion=2.0 

至此clean都可运作。

网站地图xml地图