详解手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)
ssm(spring+springmvc+mybatis),目前较为主流的企业级架构方案。标准的mvc设计模式,将整个系统划分为显示层、controller层、service层、dao层四层,使用springmvc负责请求的转发和视图管理,spring实现业务对象管理, mybatis作为数据对象持久化引擎。
一. 框架详情
spring是一个轻量级的java开发框架,它是为了解决企业应用开发的复杂性而创建的。spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何java应用都可以从spring中受益。 简单来说,spring是一个轻量级的控制反转(ioc)和面向切面(aop)的容器框架
springmvc属于springframework的后续产品,分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制
mybatis是一个基于java的持久层框架。mybatis提供的持久层框架包括sql maps和data access objects(dao)它消除了几乎所有的jdbc代码和参数的手工设置以及结果集的检索。mybatis 使用简单的 xml或注解用于配置和原始映射,将接口和 java映射成数据库中的记录
二. 创建maven项目
1、eclipse中用maven创建项目
2、按默认next
3、找到maven-archetype-webapp后,点击next
4、填写相应的信息,groupid是项目组织唯一的标识符,实际对应java的包的结构。artifactid就是项目的唯一的标识符,实际对应项目的名称,就是项目根目录的名称。package填了默认给你建一个包,不写也可以。
5、刚建好的目录如下
6、maven规定必须添加以下source folder:
src/main/resources
src/main/java
src/test/resources
src/test/java
在这步之前最好先项目上右键选择properties,然后点击java build path,在librarys下,编辑jre system library,选择workspace default jre。
7、分别修改输出路径为,对应关系如下:
8、将项目转换成dynamic web project,在项目上右键properties,在左侧选择 project facets。
9、设置部署时的文件发布路径,删除test的两项,因为test是测试使用,并不需要部署。
设置将maven的jar包发布到lib下。add -> java build path entries -> maven dependencies -> finish
三. maven引入需要的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.yingjun.test</groupid> <artifactid>tradingstate</artifactid> <packaging>war</packaging> <version>2.0.1</version> <properties> <project.build.sourceencoding>utf-8</project.build.sourceencoding> <maven.build.timestamp.format>yyyymmddhhmmss</maven.build.timestamp.format> <spring.version>3.2.9.release</spring.version> <mybatis.version>3.1.1</mybatis.version> <mybatisspring.version>1.1.1</mybatisspring.version> </properties> <dependencies> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-core</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-test</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupid>org.mybatis</groupid> <artifactid>mybatis</artifactid> <version>${mybatis.version}</version> </dependency> <dependency> <groupid>org.mybatis</groupid> <artifactid>mybatis-spring</artifactid> <version>${mybatisspring.version}</version> </dependency> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <version>5.1.34</version> </dependency> <dependency> <groupid>junit</groupid> <artifactid>junit</artifactid> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupid>c3p0</groupid> <artifactid>c3p0</artifactid> <version>0.9.1.2</version> </dependency> <dependency> <groupid>org.aspectj</groupid> <artifactid>aspectjweaver</artifactid> <version>1.8.1</version> </dependency> <dependency> <groupid>javax.servlet</groupid> <artifactid>jstl</artifactid> <version>1.2</version> </dependency> <dependency> <groupid>javax.servlet</groupid> <artifactid>servlet-api</artifactid> <version>3.0</version> <scope>provided</scope> </dependency> <dependency> <groupid>javax.servlet.jsp</groupid> <artifactid>jsp-api</artifactid> <version>2.2</version> <scope>provided</scope> </dependency> <dependency> <groupid>commons-fileupload</groupid> <artifactid>commons-fileupload</artifactid> <version>1.3.1</version> </dependency> <dependency> <groupid>commons-lang</groupid> <artifactid>commons-lang</artifactid> <version>2.6</version> </dependency> <dependency> <groupid>commons-codec</groupid> <artifactid>commons-codec</artifactid> <version>1.9</version> </dependency> <dependency> <groupid>org.apache.httpcomponents</groupid> <artifactid>httpclient</artifactid> <version>4.5</version> </dependency> <dependency> <groupid>org.slf4j</groupid> <artifactid>slf4j-api</artifactid> <version>1.7.10</version> </dependency> <dependency> <groupid>org.slf4j</groupid> <artifactid>slf4j-log4j12</artifactid> <version>1.7.10</version> </dependency> <dependency> <groupid>log4j</groupid> <artifactid>log4j</artifactid> <version>1.2.17</version> </dependency> <dependency> <groupid>com.alibaba</groupid> <artifactid>fastjson</artifactid> <version>1.1.41</version> </dependency> <dependency> <groupid>org.codehaus.jackson</groupid> <artifactid>jackson-mapper-asl</artifactid> <version>1.9.13</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactid>maven-compiler-plugin</artifactid> <version>2.3.2</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <artifactid>maven-war-plugin</artifactid> <version>2.2</version> <configuration> <version>3.0</version> <failonmissingwebxml>false</failonmissingwebxml> </configuration> </plugin> </plugins> <finalname>${project.artifactid}_${project.version}_${maven.build.timestamp}</finalname> </build> </project>
四. 相关配置文件配置,整合ssm框架
web.xml
<?xml version="1.0" encoding="utf-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <!-- 配置 spring --> <context-param> <param-name>contextconfiglocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.contextloaderlistener</listener-class> </listener> <!-- 防止spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.introspectorcleanuplistener</listener-class> </listener> <!-- 配置springmvc --> <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> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 字符集过滤器 --> <filter> <filter-name>encodingfilter</filter-name> <filter-class>org.springframework.web.filter.characterencodingfilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> <init-param> <param-name>forceencoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
spring.xml
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "> <!-- 扫描service、dao组件 --> <context:component-scan base-package="com.yingjun.test" /> <!-- 分解配置 jdbc.properites --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 数据源c3p0 --> <bean id="datasource" class="com.mchange.v2.c3p0.combopooleddatasource"> <property name="driverclass" value="${jdbc.driverclassname}" /> <property name="jdbcurl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxpoolsize" value="${c3p0.pool.size.max}" /> <property name="minpoolsize" value="${c3p0.pool.size.min}" /> <property name="initialpoolsize" value="${c3p0.pool.size.ini}" /> <property name="acquireincrement" value="${c3p0.pool.size.increment}" /> </bean> <!-- sessionfactory 将spring和mybatis整合 --> <bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean"> <property name="datasource" ref="datasource" /> <property name="configlocation" value="classpath:spring-mybatis.xml" /> <property name="mapperlocations" value="classpath*:com/yingjun/test/mapping/**/*.xml" /> </bean> <bean class="org.mybatis.spring.mapper.mapperscannerconfigurer"> <property name="basepackage" value="com,yingjun.test.dao" /> <property name="sqlsessionfactorybeanname" value="sqlsessionfactory" /> </bean> <bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager"> <property name="datasource" ref="datasource" /> </bean> <tx:advice id="transactionadvice" transaction-manager="transactionmanager"> <tx:attributes> <tx:method name="add*" propagation="required" /> <tx:method name="append*" propagation="required" /> <tx:method name="insert*" propagation="required" /> <tx:method name="save*" propagation="required" /> <tx:method name="update*" propagation="required" /> <tx:method name="modify*" propagation="required" /> <tx:method name="edit*" propagation="required" /> <tx:method name="delete*" propagation="required" /> <tx:method name="remove*" propagation="required" /> <tx:method name="repair" propagation="required" /> <tx:method name="delandrepair" propagation="required" /> <tx:method name="get*" propagation="supports" /> <tx:method name="find*" propagation="supports" /> <tx:method name="load*" propagation="supports" /> <tx:method name="search*" propagation="supports" /> <tx:method name="datagrid*" propagation="supports" /> <tx:method name="*" propagation="supports" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="transactionpointcut" expression="execution(* com.yingjun.test.service..*impl.*(..))" /> <aop:advisor pointcut-ref="transactionpointcut" advice-ref="transactionadvice" /> </aop:config> </beans>
为了代替手工使用 sqlsessiondaosupport 或 sqlsessiontemplate 编写数据访问对象 (dao)的代码,mybatis-spring 提供了一个动态代理的实现:mapperfactorybean。这个类 可以让你直接注入数据映射器接口到你的 service 层 bean 中。当使用映射器时,你仅仅如调 用你的 dao 一样调用它们就可以了,但是你不需要编写任何 dao 实现的代码,因为 mybatis-spring 将会为你创建代理。
spring-mybatis.xml
<?xml version="1.0" encoding="utf-8" ?> <!doctype configuration public "-//mybatis.org//dtd config 3.0//en" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 暂时不需要其他配置--> </configuration>
spring-mvc.xml
<?xml version="1.0" encoding="utf-8"?> <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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 默认的注解映射的支持 --> <mvc:annotation-driven /> <!-- 自动扫描该包,使springmvc认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="com.yingjun.test.controller" /> <!--避免ie执行ajax时,返回json出现下载文件 --> <bean id="mappingjacksonhttpmessageconverter" class="org.springframework.http.converter.json.mappingjacksonhttpmessageconverter"> <property name="supportedmediatypes"> <list> <value>text/html;charset=utf-8</value> </list> </property> </bean> <!-- 定义跳转的文件的前后缀 ,视图模式配置 --> <bean class="org.springframework.web.servlet.view.internalresourceviewresolver"> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的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-8" /> <!-- 文件大小最大值 --> <property name="maxuploadsize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxinmemorysize" value="40960" /> </bean> </beans>
log4j.properties
jdbc.driverclassname=com.mysql.jdbc.driver jdbc.url=jdbc:mysql://192.168.1.194:3306/test?useunicode=true&characterencoding=utf-8 jdbc.username=root jdbc.password=root c3p0.pool.size.max=20 c3p0.pool.size.min=5 c3p0.pool.size.ini=3 c3p0.pool.size.increment=2
jdbc.properties
log4j.rootlogger=info, console, debug, app, error ###console ### 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 = %d %p[%c:%l]- %m%n ### debug ### log4j.appender.debug = org.apache.log4j.dailyrollingfileappender log4j.appender.debug.file = log/debug.log log4j.appender.debug.append = true log4j.appender.debug.threshold = debug log4j.appender.debug.datepattern='.'yyyy-mm-dd log4j.appender.debug.layout = org.apache.log4j.patternlayout log4j.appender.debug.layout.conversionpattern = %d %p[%c:%l] - %m%n ### app ### log4j.appender.app = org.apache.log4j.dailyrollingfileappender log4j.appender.app.file = log/app.log log4j.appender.app.append = true log4j.appender.app.threshold = info log4j.appender.app.datepattern='.'yyyy-mm-dd log4j.appender.app.layout = org.apache.log4j.patternlayout log4j.appender.app.layout.conversionpattern = %d %p[%c:%l] - %m%n ### error ### log4j.appender.error = org.apache.log4j.dailyrollingfileappender log4j.appender.error.file = log/error.log log4j.appender.error.append = true log4j.appender.error.threshold = error log4j.appender.error.datepattern='.'yyyy-mm-dd log4j.appender.error.layout = org.apache.log4j.patternlayout log4j.appender.error.layout.conversionpattern =%d %p[%c:%l] - %m%n
五. 利用mybatis generator自动创建实体类、映射文件以及dao接口
mybatis属于一种半自动的orm框架,所以主要的工作就是配置mapping映射文件,但是由于手写映射文件很容易出错,所以可利用mybatis生成器自动生成实体类、dao接口和mapping映射文件。这样可以省去很多的功夫,将生成的代码copy到项目工程中即可。
生成代码需要的文件和jar并建立如下目录结构:
在generatorl.xml中配置相关的数据库连接,已经数据库表:
<?xml version="1.0" encoding="utf-8"?> <!doctype generatorconfiguration public "-//mybatis.org//dtd mybatis generator configuration 1.0//en" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorconfiguration> <!-- 数据库驱动 --> <classpathentry location="mysql-connector-java-5.1.34.jar" /> <context id="db2tables" targetruntime="mybatis3"> <commentgenerator> <property name="suppressdate" value="true" /> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressallcomments" value="true" /> </commentgenerator> <!--数据库链接url,用户名、密码 --> <jdbcconnection driverclass="com.mysql.jdbc.driver" connectionurl="jdbc:mysql://192.168.1.194:3306/noc" userid="root" password="root"> </jdbcconnection> <javatyperesolver> <property name="forcebigdecimals" value="false" /> </javatyperesolver> <!-- 生成模型的包名和位置 --> <javamodelgenerator targetpackage="com.yingjun.test.model" targetproject="src"> <property name="enablesubpackages" value="true" /> <property name="trimstrings" value="true" /> </javamodelgenerator> <!-- 生成映射文件的包名和位置 --> <sqlmapgenerator targetpackage="com.yingjun.test.mapping" targetproject="src"> <property name="enablesubpackages" value="true" /> </sqlmapgenerator> <!-- 生成dao的包名和位置 --> <javaclientgenerator type="xmlmapper" targetpackage="com.yingjun.test.dao" targetproject="src"> <property name="enablesubpackages" value="true" /> </javaclientgenerator> <!-- 要生成的表 tablename是数据库中的表名或视图名 domainobjectname是实体类名 --> <table tablename="other_list" domainobjectname="otherlist" enablecountbyexample="fasle" enableupdatebyexample="false" enabledeletebyexample="false" enableselectbyexample="false" selectbyexamplequeryid="false" > </table> </context> </generatorconfiguration>
打开cmd窗口 进入该目录结构,输入命令行:
java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite
运行完成后会生成相应的dao mapper 和model,是不是很爽。
六. 建立service层以及conrorller层
package com.yingjun.test.service; public interface otherservicei { public string getoterlist(); }
package com.yingjun.test.service; import java.util.arraylist; import java.util.arrays; import java.util.hashset; import java.util.list; import java.util.map; import java.util.set; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.service; import com.alibaba.fastjson.json; import com.alibaba.fastjson.serializer.serializerfeature; import com.yingjun.test.dao.otherlistmapper; import com.yingjun.test.model.otherlist; import com.yingjun.test.model.otherlistdomain; @service public class otherserviceimpl implements otherservicei { @autowired private otherlistmapper otherlistmapper; @override public string getoterlist() { set<string> set=new hashset<string>(); list<otherlist> list=otherlistmapper.selectall(); list<otherlistdomain> jsonlist=new arraylist<otherlistdomain>(); for(otherlist other:list){ string title=other.gettitle(); if(set.contains(title)){ continue; }else{ list<otherlist> t_list=new arraylist<otherlist>(); for(otherlist data:list){ if(title.equals(data.gettitle())){ t_list.add(data); } } otherlistdomain domain=new otherlistdomain(); domain.settitle(title); domain.setitems(t_list); jsonlist.add(domain); set.add(other.gettitle()); } } return json.tojsonstring(jsonlist, serializerfeature.writemapnullvalue); } }
package com.yingjun.test.controller; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.controller; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.responsebody; import com.alibaba.fastjson.json; import com.yingjun.test.service.otherservicei; import com.yingjun.test.service.stockstatusservicei; @controller @requestmapping(value = "/") public class tsscontroller { @autowired private otherservicei otherservice; @requestmapping(value="/getotherlist",produces="text/html;charset=utf-8" ) @responsebody private string getotherlist(){ string json=otherservice.getoterlist(); return json; } }
七. 建立测试类
import java.util.list; import org.apache.log4j.logmanager; import org.apache.log4j.logger; import org.junit.test; import org.junit.runner.runwith; import org.springframework.beans.factory.annotation.autowired; import org.springframework.test.context.contextconfiguration; import org.springframework.test.context.junit4.springjunit4classrunner; @runwith(springjunit4classrunner.class) @contextconfiguration(locations = {"classpath:spring.xml"}) public class testmybatis { @autowired private otherservicei service; @test public void test() { string list=service.getoterlist(); logger.info(list); } }
八. 通过浏览器进行验证
http://localhost:8080/tzyjstateservice/getotherlist
至此,测试成功,ssm三大框架的整合就完成了,有什么其他需求可以在此基础继续添
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: java集合map取key使用示例 java遍历map
下一篇: JAVA算法起步之堆排序实例