国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php框架 > 框架设计 > SSM(spring mvc+spring+Mybatis)框架整合

SSM(spring mvc+spring+Mybatis)框架整合

来源:程序员人生   发布时间:2016-06-03 08:13:18 阅读次数:3592次

最近用Idea开发,idea是1款综合的相对较新的Java IDE。Idea支持很多整合功能,我觉得挺好用的。Idea可以校订xml,支持jsp的调试。最使我喜欢的是,写spring配置文件的时候,写的1些路径都可以自己找到。classpath自己有代码的提示,超级的智能。

环境配置

在整合框架之前,先配置1下JER运行环境,配置maven仓库。
1.File——ProjectStructure——Project——New… 选择jdk的安装环境
选择sdk的安装路径

2.File——Settings——Maven——Maven home directory选择自己maven的安装目录。下面是maven管理jar包的地方。
这里写图片描述

概念

1.spring

Spring目的:就是让对象与对象(模块与模块)之间的关系没有通过代码来关联,都是通过配置类说明管理的,简单的说,不用在代码里写死new某个对象,而是全部在配置文件中进行了配置。Spring是1个容器,凡是在容器里的对象才会有Spring所提供的这些服务和功能。

2.Spring MVC

Spring MVC属于SpringFrameWork的后续产品,已融会在Spring Web Flow里面。Spring MVC 分离了控制器、模型对象、分派器和处理程序对象的角色,这类分离让它们更容易进行定制。

3.Mybatis

MyBatis 是支持普通 SQL查询,存储进程和高级映照的优秀持久层框架。MyBatis 消除几近所有的JDBC代码和参数的手工设置和结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映照,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映照成数据库中的记录。

spring Mybatis整合

用的框架的版本分别是:
spring版本号 4.0.2.RELEASE
mybatis版本号 3.2.6
Spring MVC版本号 4.0.2 RELEASE
log4j日志文件管理包版本号 {slf4j |1.7.7} { log4j |1.2.17}

项目目录以下:
这里写图片描述

1.编写pom.xml,引入jar包

<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tgb</groupId> <artifactId>Order</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>Order Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- spring版本号 --> <spring.version>4.0.2.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.2.6</mybatis.version> <!-- log4j日志文件管理包版本 --> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> <project.build.sourceEncoding> UTF⑻ </project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</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.2.2</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.30</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>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</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>Order</finalName> </build> </project>

2.建立jdbc.properties,配置数据库信息

driver=com.mysql.jdbc.Driver url=jdbc:mysql:///ordersystem username=root password=123456 #定义初始连接数 initialSize=0 #定义最大连接数 maxActive=20 #定义最大空闲 maxIdle=20 #定义最小空闲 minIdle=1 #定义最长等待时间 maxWait=60000

3.log4j.properties配置文件

#定义LOG输出级别 log4j.rootLogger=INFO,Console,File #定义日志输出目的地为控制台 log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.Target=System.out #可以灵活地指定日志输出格式,下面1行是指定具体的格式 log4j.appender.Console.layout = org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n #文件大小到达指定尺寸的时候产生1个新的文件 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

4.建立spring-Mybatis.xml配置文件

<?xml version="1.0" encoding="UTF⑻"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans⑶.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context⑶.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc⑷.0.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.cn.order" /> <!-- 引入配置文件 --> <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/cn/order/mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.cn.order.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> </beans>

5.服务层接口 service

package com.cn.order.service; import com.cn.order.pojo.User; /** * Created by azz-pc on 2016/5/24. */ public interface IUserService { User getUserById(int userId); }

6.服务层实现serviceImpl

package com.cn.order.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.cn.order.dao.IUserDao; import com.cn.order.pojo.User; import com.cn.order.service.IUserService; /** * Created by azz-pc on 2016/5/24. */ @Service("userService") public class UserServiceImpl implements IUserService { @Resource private IUserDao userDao; public User getUserById(int userId) { return this.userDao.selectByPrimaryKey(userId); } }

7.Junit测试
测试类编写:

package org.zsl.testmybatis; import javax.annotation.Resource; import com.cn.order.pojo.*; import com.cn.order.service.*; import org.apache.log4j.Logger; /*import org.apache.log4j.net.SyslogAppender;*/ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) //表示继承了SpringJUnit4ClassRunner类 @ContextConfiguration(locations = {"classpath:spring-mybatis.xml"}) public class TestMyBatis { private static Logger logger = Logger.getLogger(TestMyBatis.class); private ApplicationContext ac = null; @Resource //private IUserService userService = null; private ICardService cardService=null; private Card card=new Card(); // @Before // public void before() { // ac = new ClassPathXmlApplicationContext("applicationContext.xml"); // userService = (IUserService) ac.getBean("userService"); // } @Test public void test1() { // User user = userService.getUserById(1); // System.out.println(user.getUsername()); // System.out.println(user.getPassword()); // System.out.println(user.getState()); // logger.info("值:"+user.getUsername()); // logger.info(JSON.toJSONString(user)); card.setCardid("E000010"); card.setPassword("33333"); card.setOwnername("xiaozhou"); card.setCash("10.0"); card.setCardtypeid(1); card.setStatus("T"); cardService.insert(card); System.out.println("insert success"); } }

利用MyBatis Generator自动创建mapping,dao,pojo层,详情参见博客:http://blog.csdn.net/zhou2s_101216/article/details/51175818

这里写图片描述

输出insert success 证明 测试成功。

整合springMVC

1.配置spring-mvc.xml

<?xml version="1.0" encoding="UTF⑻"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans⑶.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context⑶.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="com.cn.order.controller"/> <!--<mvc:default-servlet-handler/>--> <!--避免IE履行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF⑻</value> </list> </property> </bean> <!-- 启动SpringMVC的注解功能,完成要求和注解POJO的映照 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter"/> <!-- JSON转换器 --> </list> </property> </bean> <!-- 定义跳转的文件的前后缀 ,视图模式配置--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成1个 可用的url地址 --> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默许编码 --> <property name="defaultEncoding" value="utf⑻"/> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000"/> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960"/> </bean> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"/> </bean> </beans>

2.配置web.xml

<?xml version="1.0" encoding="UTF⑻"?> <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>Archetype Created Web Application</display-name> <!-- Spring和mybatis的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <!-- 编码过滤器 --> <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⑻</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 避免Spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- Spring MVC servlet --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 --> <url-pattern>/</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> <!-- 配置SESSION超时,单位是分钟 --> <session-config> <session-timeout>15</session-timeout> </session-config> </web-app>

3.前台使用的是,spring mvc、bootstrap、angularjs
showUser.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf⑻" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta name="viewport" content="width=decive-width,initial-scale=1.0"> <title>测试</title> <!--import js in bootstrap--> <script type="text/javascript" src="../lib/js/jquery/jquery.js"></script> <script type="text/javascript" src="../lib/js/bootstrap/bootstrap.min.js"></script> <!--import css in bootstrap--> <link rel="stylesheet" href="../lib/css/bootstrap.min.css"> <!--import angularjs--> <script type="text/javascript" src="../lib/js/angular/angular.js"></script> </head> <body> <div class="panel panel-primary"> <div class="panel-heading"> <div class="panel-title">测试test</div> </div> <div class="panel-body"> <div class="row"> <div class="col-md⑴2">${user.username},springmvc OKOK</div> <div ng-app=""<
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生