详解手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)

详解手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版),第1张

概述SSM(Spring+SpringMVC+Mybatis),目前较为主流的企业级架构方案。标准的MVC设计模式,将整个系统划分为显示层、Controller层、Service层、Dao层四层,使用SpringMVC负责请求的转发和视图管理,Spring实现业务对象管

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" >     <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" >     <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 >     <property name="basePackage" value="com,yingjun.test.dao" />     <property name="sqlSessionfactorybeanname" value="sqlSessionFactory" />   </bean>    <bean ID="transactionManager" >     <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"     >     <property name="supportedMediaTypes">       <List>         <value>text/HTML;charset=UTF-8</value>       </List>     </property>   </bean>    <!-- 定义跳转的文件的前后缀 ,视图模式配置 -->   <bean     >     <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的URL地址 -->     <property name="prefix" value="/WEB-INF/Jsp/" />     <property name="suffix" value=".Jsp" />   </bean>    <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->   <bean ID="multipartResolver"     >     <!-- 默认编码 -->     <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三大框架的整合就完成了,有什么其他需求可以在此基础继续添

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的详解手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)全部内容,希望文章能够帮你解决详解手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1224172.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存