一、SSM框架理解
Spring(业务层)
Spring就像是整个项目中装配bean的大工厂,在配置文件中可以指定使用特定的参数去调用实体类的构造方法来实例化对象。
Spring的核心思想是IoC(控制反转),即不再需要程序员去显式地`new`一个对象,而是让Spring框架帮你来完成这一切。
Spring IOC:负责创建对象、管理对象(通过依赖注入)、整合对象、配置对象以及管理这些对象的生命周期。IOC主要来解决对象之间的依赖问题,把所有的bean的依赖关系通过配置文件或者注解关联起来,降低了耦合度。控制反转是把dao依赖注入到servic层,然后service层反转给action层,Spring的顶层容器为BeanFactory,常用的ApplicationContext为它的子接口,实现了工厂模式。
SpringMVC(表现层)
SpringMVC在项目中拦截用户请求,它的核心Servlet(前端控制器)即DispatcherServlet承担中介或是前台这样的职责,将用户请求通过HandlerMapping去匹配Controller,Controller就是具体对应请求所执行的操作。SpringMVC相当于SSH框架中struts。
M:model :模型是一个广义上的概念,一般用来处理业务的java类都可以称之为模型
C:controller : 主要用来接收客户端的请求,不能处理业务,控制器调用模型处理业务,然后得到模型返回的结果。
V:view : 控制器得到模型返回的结果以后,需要通过视图 向用户展示。
Mybatis(持久层)
Mybatis是对jdbc的封装,它让数据库底层操作变的透明。Mybatis的操作都是围绕一个SqlSessionFactory实例展开的。Mybatis通过配置文件关联到各实体类的Mapper文件,Mapper文件中配置了每个类对数据库所需进行的sql语句映射。在每次与数据库交互时,通过SqlSessionFactory拿到一个SqlSession,再执行Sql命令。
二、SSM框架实现原理
1.客户端发送请求到DispacherServlet(分发器)
2.由DispacherServlet控制器查询HanderMapping,找到处理请求的Controller
3.Controller调用业务逻辑处理后,返回ModelAndView
4.DispacherSerclet查询视图解析器,找到ModelAndView指定的视图
5.视图负责将结果显示到客户端
三、SSM整合
3.1新建一个Maven Project
建好之后会提示下面的错误:
1 The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path index.jsp
在项目右键 Java Build Path
添加 Tomcat 服务器的依赖
修改 JRE 版本,Edit更改为 Eclipse 工作空间默认的 JRE 版本,
之后还要在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>
3.2 配置Maven Project的pom.xml 文件
在配置 pom.xml 过程中,遇到了的几个问题:
3.2.1 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> <!-- 2.0版本之前 引入JSON --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency>
3.2.2 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> org.mybatis.spring.SqlSessionFactoryBean找不到 配置mybatis spring的版本不对
Maven引入需要的SSM 框架jar包,修改后:
pom.xml
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 <groupId>com.jxust</groupId> 5 <artifactId>SSM-Test2</artifactId> 6 <packaging>war</packaging> 7 <version>0.0.1-SNAPSHOT</version> 8 <name>SSM-Test2 Maven Webapp</name> 9 <url>http://maven.apache.org</url> 10 <properties> 11 <!-- spring版本号 --> 12 <spring.version>4.3.3.RELEASE</spring.version> 13 <!-- mybatis版本号 --> 14 <mybatis.version>3.4.0</mybatis.version> 15 <!-- log4j日志文件管理包版本 --> 16 <slf4j.version>1.7.7</slf4j.version> 17 <log4j.version>1.2.17</log4j.version> 18 </properties> 19 20 <dependencies> 21 <dependency> 22 <groupId>junit</groupId> 23 <artifactId>junit</artifactId> 24 <version>4.12</version> 25 <!-- 表示开发的时候引入,发布的时候不会加载此包 --> 26 <scope>test</scope> 27 </dependency> 28 <!-- spring核心包 --> 29 <dependency> 30 <groupId>org.springframework</groupId> 31 <artifactId>spring-core</artifactId> 32 <version>${spring.version}</version> 33 </dependency> 34 35 <dependency> 36 <groupId>org.springframework</groupId> 37 <artifactId>spring-web</artifactId> 38 <version>${spring.version}</version> 39 </dependency> 40 <dependency> 41 <groupId>org.springframework</groupId> 42 <artifactId>spring-oxm</artifactId> 43 <version>${spring.version}</version> 44 </dependency> 45 <dependency> 46 <groupId>org.springframework</groupId> 47 <artifactId>spring-tx</artifactId> 48 <version>${spring.version}</version> 49 </dependency> 50 51 <dependency> 52 <groupId>org.springframework</groupId> 53 <artifactId>spring-jdbc</artifactId> 54 <version>${spring.version}</version> 55 </dependency> 56 57 <dependency> 58 <groupId>org.springframework</groupId> 59 <artifactId>spring-webmvc</artifactId> 60 <version>${spring.version}</version> 61 </dependency> 62 <dependency> 63 <groupId>org.springframework</groupId> 64 <artifactId>spring-aop</artifactId> 65 <version>${spring.version}</version> 66 </dependency> 67 68 <dependency> 69 <groupId>org.springframework</groupId> 70 <artifactId>spring-context-support</artifactId> 71 <version>${spring.version}</version> 72 </dependency> 73 74 <dependency> 75 <groupId>org.springframework</groupId> 76 <artifactId>spring-test</artifactId> 77 <version>${spring.version}</version> 78 </dependency> 79 <!-- mybatis核心包 --> 80 <dependency> 81 <groupId>org.mybatis</groupId> 82 <artifactId>mybatis</artifactId> 83 <version>${mybatis.version}</version> 84 </dependency> 85 86 <!--mybatis spring 插件 --> 87 <dependency> 88 <groupId>org.mybatis</groupId> 89 <artifactId>mybatis-spring</artifactId> 90 <version>1.3.0</version> 91 </dependency> 92 <!-- 导入java ee jar 包 --> 93 <dependency> 94 <groupId>javax</groupId> 95 <artifactId>javaee-api</artifactId> 96 <version>7.0</version> 97 </dependency> 98 <!-- 导入Mysql数据库链接jar包 --> 99 <dependency> 100 <groupId>mysql</groupId> 101 <artifactId>mysql-connector-java</artifactId> 102 <version>5.1.25</version> 103 </dependency> 104 <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --> 105 <dependency> 106 <groupId>commons-dbcp</groupId> 107 <artifactId>commons-dbcp</artifactId> 108 <version>1.2.2</version> 109 </dependency> 110 <!-- JSTL标签类 --> 111 <dependency> 112 <groupId>jstl</groupId> 113 <artifactId>jstl</artifactId> 114 <version>1.2</version> 115 </dependency> 116 <!-- 日志文件管理包 --> 117 <!-- log start --> 118 <dependency> 119 <groupId>log4j</groupId> 120 <artifactId>log4j</artifactId> 121 <version>${log4j.version}</version> 122 </dependency> 123 124 125 <!-- 格式化对象,方便输出日志 --> 126 <dependency> 127 <groupId>com.alibaba</groupId> 128 <artifactId>fastjson</artifactId> 129 <version>1.1.41</version> 130 </dependency> 131 132 133 <dependency> 134 <groupId>org.slf4j</groupId> 135 <artifactId>slf4j-api</artifactId> 136 <version>${slf4j.version}</version> 137 </dependency> 138 139 <dependency> 140 <groupId>org.slf4j</groupId> 141 <artifactId>slf4j-log4j12</artifactId> 142 <version>${slf4j.version}</version> 143 </dependency> 144 <!-- log end --> 145 <!-- 引入JSON --> 146 <dependency> 147 <groupId>com.fasterxml.jackson.core</groupId> 148 <artifactId>jackson-databind</artifactId> 149 <version>2.7.5</version> 150 </dependency> 151 <!-- 上传组件包 --> 152 <dependency> 153 <groupId>commons-fileupload</groupId> 154 <artifactId>commons-fileupload</artifactId> 155 <version>1.3.1</version> 156 </dependency> 157 <dependency> 158 <groupId>commons-io</groupId> 159 <artifactId>commons-io</artifactId> 160 <version>2.4</version> 161 </dependency> 162 <dependency> 163 <groupId>commons-codec</groupId> 164 <artifactId>commons-codec</artifactId> 165 <version>1.9</version> 166 </dependency> 167 168 </dependencies> 169 <build> 170 <finalName>SSM-Test2</finalName> 171 <plugins> 172 <!-- 修改maven默认的JRE编译版本 173 防止maven update project之后 把jre配置的成默认的1.5 174 根据自己的情况更改为1.7或1.8 175 --> 176 <plugin> 177 <groupId>org.apache.maven.plugins</groupId> 178 <artifactId>maven-compiler-plugin</artifactId> 179 <version>2.3.2</version> 180 <configuration> 181 <source>1.8</source> 182 <target>1.8</target> 183 </configuration> 184 </plugin> 185 </plugins> 186 </build> 187 </project>
之后保存,右击项目-maven-update project,如果出现以下的异常:
1 JavaServer Faces 2.2 can not be installed : One or more constraints have not been satisfied. 2 JavaServer Faces 2.2 requires Dynamic Web Module 2.5 or newer. SSM-Test2
这是web.xml
文件头信息配置的不正确,原来的2.3,不符合要求。
解决步骤1:web.xml
头信息替换为下面的代码:
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 id="WebApp_ID" version="3.0"> 6 7 </web-app>
解决步骤2:关闭Eclipse,修改项目目录下.settings/org.eclipse.wst.common.project.facet.core.xml
的配置
1 <installed facet="jst.web" version="2.3"/> 2 3 改为 4 5 <installed facet="jst.web" version="3.0"/>
重启Eclipse,右击项目-maven-update project(不行,就先移除项目,导入)
具体步骤参考:http://www.cnblogs.com/jebeljebel/p/4421098.html
项目结构为:
之后可以在 Java Build Path
中查看自己 maven 下载的jar包。
3.3 Spring与MyBatis的整合
3.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
3.3.2 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" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xmlns:tx="http://www.springframework.org/schema/tx" 7 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 8 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd 9 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 10 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> 11 12 <!-- 自动扫描 --> 13 <context:component-scan base-package="com.jxust.ssm" > 14 <!-- 不扫描@Controller注解的类--> 15 <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> 16 </context:component-scan> 17 18 <!-- 引入配置文件 --> 19 <bean id="propertyConfigurer" 20 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 21 <property name="location" value="classpath:jdbc.properties" /> 22 </bean> 23 24 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 25 destroy-method="close"> 26 <property name="driverClassName" value="${driver}" /> 27 <property name="url" value="${url}" /> 28 <property name="username" value="${username}" /> 29 <property name="password" value="${password}" /> 30 <!-- 初始化连接大小 --> 31 <property name="initialSize" value="${initialSize}"></property> 32 <!-- 连接池最大数量 --> 33 <property name="maxActive" value="${maxActive}"></property> 34 <!-- 连接池最大空闲 --> 35 <property name="maxIdle" value="${maxIdle}"></property> 36 <!-- 连接池最小空闲 --> 37 <property name="minIdle" value="${minIdle}"></property> 38 <!-- 获取连接最大等待时间 --> 39 <property name="maxWait" value="${maxWait}"></property> 40 </bean> 41 42 <!-- spring和MyBatis整合,不需要mybatis的配置映射文件 --> 43 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 44 <property name="dataSource" ref="dataSource" /> 45 <!-- 自动扫描mapping.xml文件 --> 46 <property name="mapperLocations" value="classpath:com/jxust/ssm/mapping/*.xml"></property> 47 </bean> 48 49 <!-- DAO接口所在包名,Spring会自动查找其下的类 动态代理实现 不用写dao的实现类--> 50 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 51 <property name="basePackage" value="com.jxust.ssm.dao" /> 52 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> 53 </bean> 54 55 <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> 56 <bean id="transactionManager" 57 class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 58 <property name="dataSource" ref="dataSource" /> 59 </bean> 60 61 <tx:annotation-driven transaction-manager="transactionManager"/> 62 </beans>
3.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
3.3.4 创建 MySQL 数据库和表
建表语句和原始数据
1 mysql> use db_ssm; 2 Database changed 3 4 mysql> CREATE TABLE tb_user( 5 -> id int(11) NOT NULL AUTO_INCREMENT, 6 -> user_name varchar(40) NOT NULL, 7 -> password varchar(40) NOT NULL, 8 -> age int(4) NOT NULL, 9 -> PRIMARY KEY(id)) 10 -> ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; 11 Query OK, 0 rows affected (0.33 sec) 12 13 mysql> select * from tb_user; 14 +----+-----------+----------+-----+ 15 | id | user_name | password | age | 16 +----+-----------+----------+-----+ 17 | 1 | 李白 | 123454 | 23 | 18 | 2 | 杜甫 | 234234 | 23 | 19 +----+-----------+----------+-----+ 20 2 rows in set (0.00 sec)
3.3.5 利用MyBatis Generator自动创建代码
该工具可根据MySQL中的表(tb_user)自动创建实体类、MyBatis映射文件以及Dao接口 参考博文:http://blog.csdn.net/zhshulin/article/details/23912615
红色部分为自动生成的文件,UserMaping.xml里各种包路径,要修改成自己的,尤其是namespace,要关联为创建的UserDao(因为使用了动态代理实现)
User.java
1 package com.jxust.ssm.pojo; 2 /** 3 * 用户实体类 4 * 对应数据表tb_user 7 */ 8 public class User { 9 private Integer id; 10 11 private String userName; 12 13 private String password; 14 15 private Integer age; 16 17 public Integer getId() { 18 return id; 19 } 20 21 public void setId(Integer id) { 22 this.id = id; 23 } 24 25 public String getUserName() { 26 return userName; 27 } 28 29 public void setUserName(String userName) { 30 this.userName = userName == null ? null : userName.trim(); 31 } 32 33 public String getPassword() { 34 return password; 35 } 36 37 public void setPassword(String password) { 38 this.password = password == null ? null : password.trim(); 39 } 40 41 public Integer getAge() { 42 return age; 43 } 44 45 public void setAge(Integer age) { 46 this.age = age; 47 } 48 49 @Override 50 public String toString() { 51 return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", age=" + age + "]"; 52 } 53 }
UserDao.java
1 package com.jxust.ssm.dao; 2 3 import com.jxust.ssm.pojo.User; 4 /** 5 * User类Dao层接口 6 * 之前我们会在dao层自己手动实现dao层然后自动注入SqlSessionTemplate 实例 7 * 来调用具体的方法 比如 insert("","") selectOne("","") 等方法 8 * 其中第一个参数就是映射文件的地址: namespace+id 而第二个参数就是传递的条件这样mybatis 9 * 就会按照我们传递的这两个参数找到具体的映射文件进行解析查询。 10 * 而这里使用动态代理就省去了我们实现dao接口的这一步骤,而是由spring提我们实现了 11 */ 12 public interface UserDao { 13 int deleteByPrimaryKey(Integer id); 14 int insert(User record); 15 int insertSelective(User record); 16 User selectByPrimaryKey(Integer id); 17 int updateByPrimaryKeySelective(User record); 18 int updateByPrimaryKey(User record); 19 } 自动创建的文件中,有增删改查的各种方法,动态SQL等,如果你想了解详细的使用方法:http://blog.csdn.net/peng_hong_fu/article/details/53235271
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 <!-- namespace的值就是dao接口的完整路径,就这个demo而言namespace 就是userDao.java的完整路径--> 4 <mapper namespace="com.jxust.ssm.dao.UserDao"> 5 <resultMap id="BaseResultMap" type="com.jxust.ssm.pojo.User"> 6 <id column="id" property="id" jdbcType="INTEGER" /> 7 <result column="user_name" property="userName" jdbcType="VARCHAR" /> 8 <result column="password" property="password" jdbcType="VARCHAR" /> 9 <result column="age" property="age" jdbcType="INTEGER" /> 10 </resultMap> 11 <sql id="Base_Column_List"> 12 id, user_name, password, age 13 </sql> 14 <select id="selectByPrimaryKey" resultMap="BaseResultMap" 15 parameterType="java.lang.Integer"> 16 select 17 <include refid="Base_Column_List" /> 18 from tb_user 19 where id = #{id,jdbcType=INTEGER} 20 </select> 21 22 <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> 23 delete from 24 tb_user 25 where id = #{id,jdbcType=INTEGER} 26 </delete> 27 28 <insert id="insert" parameterType="com.jxust.ssm.pojo.User"> 29 insert into tb_user (id, 30 user_name, password, 31 age) 32 values (#{id,jdbcType=INTEGER}, 33 #{userName,jdbcType=VARCHAR}, 34 #{password,jdbcType=VARCHAR}, 35 #{age,jdbcType=INTEGER}) 36 </insert> 37 38 <insert id="insertSelective" parameterType="com.jxust.ssm.pojo.User"> 39 insert into tb_user 40 <trim prefix="(" suffix=")" suffixOverrides=","> 41 <if test="id != null"> 42 id, 43 </if> 44 <if test="userName != null"> 45 user_name, 46 </if> 47 <if test="password != null"> 48 password, 49 </if> 50 <if test="age != null"> 51 age, 52 </if> 53 </trim> 54 <trim prefix="values (" suffix=")" suffixOverrides=","> 55 <if test="id != null"> 56 #{id,jdbcType=INTEGER}, 57 </if> 58 <if test="userName != null"> 59 #{userName,jdbcType=VARCHAR}, 60 </if> 61 <if test="password != null"> 62 #{password,jdbcType=VARCHAR}, 63 </if> 64 <if test="age != null"> 65 #{age,jdbcType=INTEGER}, 66 </if> 67 </trim> 68 </insert> 69 70 <update id="updateByPrimaryKeySelective" parameterType="com.jxust.ssm.pojo.User"> 71 update tb_user 72 <set> 73 <if test="userName != null"> 74 user_name = #{userName,jdbcType=VARCHAR}, 75 </if> 76 <if test="password != null"> 77 password = #{password,jdbcType=VARCHAR}, 78 </if> 79 <if test="age != null"> 80 age = #{age,jdbcType=INTEGER}, 81 </if> 82 </set> 83 where id = #{id,jdbcType=INTEGER} 84 </update> 85 86 <update id="updateByPrimaryKey" parameterType="com.jxust.ssm.pojo.User"> 87 update tb_user 88 set 89 user_name = #{userName,jdbcType=VARCHAR}, 90 password = 91 #{password,jdbcType=VARCHAR}, 92 age = #{age,jdbcType=INTEGER} 93 where id = 94 #{id,jdbcType=INTEGER} 95 </update> 96 </mapper>
3.3.6 创建 Service层 接口和实现类
UserService.java
1 package com.jxust.ssm.service; 2 3 import com.jxust.ssm.pojo.User; 4 /** 5 * Service层接口 6 */ 7 public interface UserService { 8 //根据id查找 9 public User getUserById(Integer userid); 10 11 //添加一条数据 12 public int insert(User user); 13 }
UserServiceImpl.java
1 /** 2 * userService 接口的实现类 3 * 4 */ 5 @Transactional 6 @Service("userService") 7 public class UserServiceImpl implements UserService { 8 /** 9 * 因为没有在spring的文件中显式的声明userService实现类,直接通过getBean得到 userService 会找不到 10 * 需要显式配置 @Service ("userService"),指定bean的名称 11 * 相当与<bean id="userService" class="com.jxust.ssm.service.impl.UserServiceImpl"></bean> 12 */ 13 @Resource 14 private UserDao userDao; 15 16 public User getUserById(Integer userid) { 17 return this.userDao.selectByPrimaryKey(userid); 18 } 19 20 @Override 21 public int insert(User user) { 22 return this.userDao.insert(user); 23 } 24 }
3.3.7 Junit 测试Spring整合Mybatis
使用Junit测试,TestMyBatis为使用 spring 的测试方法,TestMyBatis2为不使用 spring 的普通方法
TestMyBatis.java
1 package com.test; 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 import com.jxust.ssm.pojo.User; 13 import com.jxust.ssm.service.UserService; 14 15 @RunWith(SpringJUnit4ClassRunner.class) // 表示继承了SpringJUnit4ClassRunner类 16 @ContextConfiguration(locations = { "classpath:spring-mybatis.xml" }) 17 /** 18 * 测试spring整合mybatis spring方式 19 * 20 */ 21 public class TestMyBatis { 22 private static Logger logger = Logger.getLogger(TestMyBatis.class); 23 24 @Resource 25 private UserService userService = null; 26 27 /** 28 * 测试查询 29 */ 30 @Test 31 public void test1() { 32 User user = userService.getUserById(2); 33 logger.info("值:" + user.getUserName()); 34 logger.info(JSON.toJSONString(user)); 35 } 36 /** 37 * 测试添加 38 */ 39 @Test 40 public void test2() { 41 User user = new User(); 42 user.setUserName("杜甫3"); 43 user.setPassword("234234"); 44 user.setAge(23); 45 int count = userService.insert(user); 46 logger.info("count:" +count); 47 } 48 }
TestMyBatis2.java
1 package com.test; 2 3 import org.junit.Before; 4 import org.junit.Test; 5 import org.springframework.context.ApplicationContext; 6 import org.springframework.context.support.ClassPathXmlApplicationContext; 7 8 import com.jxust.ssm.pojo.User; 9 import com.jxust.ssm.service.UserService; 10 /** 11 * 测试spring整合mybatis 普通方式 12 */ 13 public class TestMyBatis2 { 14 15 private ApplicationContext ac = null; 16 17 private UserService userService = null; 18 19 @Before 20 public void before() { 21 ac = new ClassPathXmlApplicationContext("classpath:spring-mybatis.xml"); 22 userService = (UserService) ac.getBean("userService"); 23 } 24 /** 25 * 测试查询 26 */ 27 @Test 28 public void test1() { 29 User user = userService.getUserById(2); 30 System.out.println(user.toString()); 31 } 32 /** 33 * 测试添加 34 */ 35 @Test 36 public void test2() { 37 User user = new User(); 38 user.setUserName("杜甫"); 39 user.setPassword("234234"); 40 user.setAge(23); 41 int count = userService.insert(user); 42 System.out.println("插入"+count+"条数据成功"); 43 } 44 }
测试结果:
... [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 [email protected]d56113: startup date [Sun Dec 11 20:23:43 CST 2016]; root of context hierarchy
3.4.项目整合 SpringMVC
3.4.1配置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 id="WebApp_ID" version="3.0"> 6 7 <!-- 编码过滤器 --> 8 <filter> 9 <filter-name>encodingFilter</filter-name> 10 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 11 <async-supported>true</async-supported> 12 <init-param> 13 <param-name>encoding</param-name> 14 <param-value>UTF-8</param-value> 15 </init-param> 16 </filter> 17 <filter-mapping> 18 <filter-name>encodingFilter</filter-name> 19 <url-pattern>/*</url-pattern> 20 </filter-mapping> 21 22 <!-- Spring监听器 --> 23 <context-param> 24 <param-name>contextConfigLocation</param-name> 25 <param-value>classpath:spring-mybatis.xml</param-value> 26 </context-param> 27 28 <listener> 29 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 30 </listener> 31 32 <!--Spring MVC 配置servlet --> 33 <servlet> 34 <servlet-name>springDispatcherServlet</servlet-name> 35 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 36 <init-param> 37 <param-name>contextConfigLocation</param-name> 38 <param-value>classpath:springmvc.xml</param-value> 39 </init-param> 40 <load-on-startup>1</load-on-startup> 41 </servlet> 42 43 <servlet-mapping> 44 <servlet-name>springDispatcherServlet</servlet-name> 45 <url-pattern>/</url-pattern> 46 </servlet-mapping> 47 </web-app>
3.4.2 配置SpringMVC配置文件springmvc.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" 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 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd 8 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> 9 10 <!-- 自动扫描该包 @controller注解的类--> 11 <context:component-scan base-package="com.jxust.ssm.controller"/> 12 13 <!-- 静态资源处理 --> 14 <mvc:default-servlet-handler/> 15 16 <!--自动注册 RequestMappingHandlerMapping、RequestMappingHandlerAdapter 等bean --> 17 <mvc:annotation-driven></mvc:annotation-driven> 18 19 <!-- 定义跳转的文件的前后缀 ,视图模式配置--> 20 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 21 <property name="prefix" value="/WEB-INF/views/" /> 22 <property name="suffix" value=".jsp" /> 23 </bean> 24 </beans>spring配置文件和springmvc配置文件的两个自动扫描的路径范围,最好不要重复,使用<context:exclude-filter/>
和<context:include-filter/>
指定不扫描和扫描的条件
3.4.3 创建 SpringMVC 的Controller
UserController.java
1 package com.jxust.ssm.controller; 2 3 import javax.annotation.Resource; 4 5 import org.springframework.stereotype.Controller; 6 import org.springframework.ui.Model; 7 import org.springframework.web.bind.annotation.RequestMapping; 8 import org.springframework.web.bind.annotation.RequestParam; 9 10 import com.jxust.ssm.pojo.User; 11 import com.jxust.ssm.service.UserService; 12 13 @Controller 14 public class UserController { 15 /** 16 * 使用@Autowired也可以,@Autowired默认按类型装配 17 * @Resource 默认按名称装配,当找不到与名称匹配的bean才会按类型装配。 18 */ 19 @Resource 20 private UserService userService; 21 22 /** 23 * 测试查询 24 * 25 * @param id 26 * @param model 27 * @return 28 */ 29 @RequestMapping("/showUser") 30 public String testtoshowUser(@RequestParam(value = "id") Integer id, Model model) { 31 System.out.println("id:" + id); 32 User user = userService.getUserById(id); 33 model.addAttribute("user", user); 34 return "showUser"; 35 } 36 37 /** 38 * 测试添加数据 39 * 40 * @param id 41 * @param model 42 * @return 43 */ 44 @RequestMapping("/insertUser") 45 public String testinsertUser() { 46 User user = new User(); 47 user.setUserName("李清照"); 48 user.setPassword("3232322"); 49 user.setAge(22); 50 int count = userService.insert(user); 51 System.out.println("插入" + count + "条数据成功"); 52 return "showUser"; 53 } 54 }
3.4.4 JSP页面
index.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>index.jsp</title> 8 </head> 9 <body> 10 <a href="showUser?id=2">ShowUser page</a><br> 11 <a href="insertUser">insertUser </a> 12 </body> 13 </html>
showUser.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> 10 id:${user.id} <br> 11 userName: ${user.userName} <br> 12 password: ${user.password} <br> 13 age: ${user.age} <br> 14 </body> 15 </html>
3.4.5 项目发布到Tomcat服务器上
原文地址:https://www.cnblogs.com/wang-Java-begining/p/9906493.html