千家信息网

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

发表于:2024-11-25 作者:千家信息网编辑
千家信息网最后更新 2024年11月25日,一. 框架详情Spring 是一个轻量级的Java开发框架,它是为了解决企业应用开发的复杂性而创建的。Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都
千家信息网最后更新 2024年11月25日手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)【转】
一. 框架详情
  1. Spring 是一个轻量级的Java开发框架,它是为了解决企业应用开发的复杂性而创建的。Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。 简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。

  2. SpringMVC 属于SpringFrameWork的后续产品,分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。

  3. 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包

    Xml代码

    四. 相关配置文件配置,整合SSM框架

    web.xml

    Java代码

    spring.xml

    Java代码


    为了代替手工使用 SqlSessionDaoSupport 或 SqlSessionTemplate 编写数据访问对象 (DAO)的代码,MyBatis-Spring 提供了一个动态代理的实现:MapperFactoryBean。这个类 可以让你直接注入数据映射器接口到你的 service 层 bean 中。当使用映射器时,你仅仅如调 用你的 DAO 一样调用它们就可以了,但是你不需要编写任何 DAO 实现的代码,因为 MyBatis-Spring 将会为你创建代理。

    spring-mybatis.xml

    Java代码

    spring-mvc.xml

    Java代码

    log4j.properties

    Sql代码


    jdbc.properties

    Java代码


    五. 利用MyBatis Generator自动创建实体类、映射文件以及DAO接口

    MyBatis属于一种半自动的ORM框架,所以主要的工作就是配置Mapping映射文件,但是由于手写映射文件很容易出错,所以可利用MyBatis生成器自动生成实体类、DAO接口和Mapping映射文件。这样可以省去很多的功夫,将生成的代码copy到项目工程中即可。
    生成代码需要的文件和jar并建立如下目录结构:



    在generatorl.xml中配置相关的数据库连接,已经数据库表:

    Xml代码

    打开CMD窗口 进入该目录结构,输入命令行:

    java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite


    运行完成后会生成相应的dao mapper 和model,是不是很爽。

    六. 建立Service层以及conrorller层

    Java代码

    Java代码

    Java代码



    七. 建立测试类

    Java代码

    1. import java.util.List;

    2. import org.apache.log4j.LogManager;

    3. import org.apache.log4j.Logger;

    4. import org.junit.Test;

    5. import org.junit.runner.RunWith;

    6. import org.springframework.beans.factory.annotation.Autowired;

    7. import org.springframework.test.context.ContextConfiguration;

    8. import org.springframework.test.context.junit4.SpringJUnit4Cla***unner;

    9. @RunWith(SpringJUnit4Cla***unner.class)

    10. @ContextConfiguration(locations = {"classpath:spring.xml"})

    11. public class TestMybatis {

    12. @Autowired

    13. private OtherServiceI service;

    14. @Test

    15. public void test() {

    16. String list=service.getOterList();

    17. logger.info(list);

    18. }

    19. }

    20. package com.yingjun.test.controller;

    21. import org.springframework.beans.factory.annotation.Autowired;

    22. import org.springframework.stereotype.Controller;

    23. import org.springframework.web.bind.annotation.RequestMapping;

    24. import org.springframework.web.bind.annotation.ResponseBody;

    25. import com.alibaba.fastjson.JSON;

    26. import com.yingjun.test.service.OtherServiceI;

    27. import com.yingjun.test.service.StockStatusServiceI;

    28. @Controller

    29. @RequestMapping(value = "/")

    30. public class TSSController {

    31. @Autowired

    32. private OtherServiceI otherService;

    33. @RequestMapping(value="/getOtherList",produces="text/html;charset=UTF-8" )

    34. @ResponseBody

    35. private String getOtherList(){

    36. String json=otherService.getOterList();

    37. return json;

    38. }

    39. }

    40. package com.yingjun.test.service;

    41. import java.util.ArrayList;

    42. import java.util.Arrays;

    43. import java.util.HashSet;

    44. import java.util.List;

    45. import java.util.Map;

    46. import java.util.Set;

    47. import org.springframework.beans.factory.annotation.Autowired;

    48. import org.springframework.stereotype.Service;

    49. import com.alibaba.fastjson.JSON;

    50. import com.alibaba.fastjson.serializer.SerializerFeature;

    51. import com.yingjun.test.dao.OtherListMapper;

    52. import com.yingjun.test.model.OtherList;

    53. import com.yingjun.test.model.OtherListDomain;

    54. @Service

    55. public class OtherServiceImpl implements OtherServiceI {

    56. @Autowired

    57. private OtherListMapper otherListMapper;

    58. @Override

    59. public String getOterList() {

    60. Set set=new HashSet();

    61. List list=otherListMapper.selectAll();

    62. List jsonList=new ArrayList();

    63. for(OtherList other:list){

    64. String title=other.getTitle();

    65. if(set.contains(title)){

    66. continue;

    67. }else{

    68. List t_list=new ArrayList();

    69. for(OtherList data:list){

    70. if(title.equals(data.getTitle())){

    71. t_list.add(data);

    72. }

    73. }

    74. OtherListDomain domain=new OtherListDomain();

    75. domain.setTitle(title);

    76. domain.setItems(t_list);

    77. jsonList.add(domain);

    78. set.add(other.getTitle());

    79. }

    80. }

    81. return JSON.toJSONString(jsonList, SerializerFeature.WriteMapNullValue);

    82. }

    83. }

    1. package com.yingjun.test.service;

    2. public interface OtherServiceI {

    3. public String getOterList();

    4. }

    5. xml version="1.0" encoding="UTF-8"?>

    6. PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"

    7. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

    8. <generatorConfiguration>

    9. <classPathEntry location="mysql-connector-java-5.1.34.jar" />

    10. <context id="DB2Tables" targetRuntime="MyBatis3">

    11. <commentGenerator>

    12. <property name="suppressDate" value="true" />

    13. <property name="suppressAllComments" value="true" />

    14. commentGenerator>

    15. <jdbcConnection driverClass="com.mysql.jdbc.Driver"

    16. connectionURL="jdbc:mysql://192.168.1.194:3306/noc"

    17. userId="root" password="root">

    18. jdbcConnection>

    19. <javaTypeResolver>

    20. <property name="forceBigDecimals" value="false" />

    21. javaTypeResolver>

    22. <javaModelGenerator targetPackage="com.yingjun.test.model"

    23. targetProject="src">

    24. <property name="enableSubPackages" value="true" />

    25. <property name="trimStrings" value="true" />

    26. javaModelGenerator>

    27. <sqlMapGenerator targetPackage="com.yingjun.test.mapping"

    28. targetProject="src">

    29. <property name="enableSubPackages" value="true" />

    30. sqlMapGenerator>

    31. <javaClientGenerator type="XMLMAPPER" targetPackage="com.yingjun.test.dao"

    32. targetProject="src">

    33. <property name="enableSubPackages" value="true" />

    34. javaClientGenerator>

    35. <table tableName="other_list" domainObjectName="OtherList"

    36. enableCountByExample="fasle" enableUpdateByExample="false"

    37. enableDeleteByExample="false" enableSelectByExample="false"

    38. selectByExampleQueryId="false" >

    39. table>

    40. context>

    41. generatorConfiguration>

    1. log4j.rootLogger=info, console, debug, app, error

    2. ###Console ###

    3. log4j.appender.console = org.apache.log4j.ConsoleAppender

    4. log4j.appender.console.Target = System.out

    5. log4j.appender.console.layout = org.apache.log4j.PatternLayout

    6. log4j.appender.console.layout.ConversionPattern = %d %p[%C:%L]- %m%n

    7. ### debug ###

    8. log4j.appender.debug = org.apache.log4j.DailyRollingFileAppender

    9. log4j.appender.debug.File = log/debug.log

    10. log4j.appender.debug.Append = true

    11. log4j.appender.debug.Threshold = DEBUG

    12. log4j.appender.debug.DatePattern='.'yyyy-MM-dd

    13. log4j.appender.debug.layout = org.apache.log4j.PatternLayout

    14. log4j.appender.debug.layout.ConversionPattern = %d %p[%c:%L] - %m%n

    15. ### app ###

    16. log4j.appender.app = org.apache.log4j.DailyRollingFileAppender

    17. log4j.appender.app.File = log/app.log

    18. log4j.appender.app.Append = true

    19. log4j.appender.app.Threshold = INFO

    20. log4j.appender.app.DatePattern='.'yyyy-MM-dd

    21. log4j.appender.app.layout = org.apache.log4j.PatternLayout

    22. log4j.appender.app.layout.ConversionPattern = %d %p[%c:%L] - %m%n

    23. ### Error ###

    24. log4j.appender.error = org.apache.log4j.DailyRollingFileAppender

    25. log4j.appender.error.File = log/error.log

    26. log4j.appender.error.Append = true

    27. log4j.appender.error.Threshold = ERROR

    28. log4j.appender.error.DatePattern='.'yyyy-MM-dd

    29. log4j.appender.error.layout = org.apache.log4j.PatternLayout

    30. log4j.appender.error.layout.ConversionPattern =%d %p[%c:%L] - %m%n

    31. jdbc.driverClassName=com.mysql.jdbc.Driver

    32. jdbc.url=jdbc:mysql://192.168.1.194:3306/test?useUnicode=true&characterEncoding=UTF-8

    33. jdbc.username=root

    34. jdbc.password=root

    35. c3p0.pool.size.max=20

    36. c3p0.pool.size.min=5

    37. c3p0.pool.size.ini=3

    38. c3p0.pool.size.increment=2

    1. "1.0" encoding="UTF-8"?>

    2. "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="

    7. http://www.springframework.org/schema/beans

    8. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

    9. http://www.springframework.org/schema/context

    10. http://www.springframework.org/schema/context/spring-context-3.0.xsd

    11. http://www.springframework.org/schema/mvc

    12. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    13. package="com.yingjun.test.controller" />

    14. "mappingJacksonHttpMessageConverter"

    15. class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">

    16. "supportedMediaTypes">

    17. text/html;charset=UTF-8

    18. class="org.springframework.web.servlet.view.InternalResourceViewResolver">

    19. "prefix" value="/WEB-INF/jsp/" />

    20. "suffix" value=".jsp" />

    21. "multipartResolver"

    22. class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    23. "defaultEncoding" value="utf-8" />

    24. "maxUploadSize" value="10485760000" />

    25. "maxInMemorySize" value="40960" />

    26. "1.0" encoding="UTF-8" ?>

    27. "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">

    1. "1.0" encoding="UTF-8"?>

    2. "http://www.springframework.org/schema/beans"

    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"

    4. xmlns:context="http://www.springframework.org/schema/context"

    5. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"

    6. xsi:schemaLocation="http://www.springframework.org/schema/beans

    7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

    8. http://www.springframework.org/schema/mvc

    9. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd

    10. http://www.springframework.org/schema/context

    11. http://www.springframework.org/schema/context/spring-context-3.0.xsd

    12. http://www.springframework.org/schema/aop

    13. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

    14. http://www.springframework.org/schema/tx

    15. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">

    16. package="com.yingjun.test" />

    17. "classpath:jdbc.properties" />

    18. "dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">

    19. "driverClass" value="${jdbc.driverClassName}" />

    20. "jdbcUrl" value="${jdbc.url}" />

    21. "user" value="${jdbc.username}" />

    22. "password" value="${jdbc.password}" />

    23. "maxPoolSize" value="${c3p0.pool.size.max}" />

    24. "minPoolSize" value="${c3p0.pool.size.min}" />

    25. "initialPoolSize" value="${c3p0.pool.size.ini}" />

    26. "acquireIncrement" value="${c3p0.pool.size.increment}" />

    27. "sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

    28. "dataSource" ref="dataSource" />

    29. "configLocation" value="classpath:spring-mybatis.xml" />

    30. "mapperLocations" value="classpath*:com/yingjun/test/mapping/**/*.xml" />

    31. class="org.mybatis.spring.mapper.MapperScannerConfigurer">

    32. "basePackage" value="com,yingjun.test.dao" />

    33. "sqlSessionFactoryBeanName" value="sqlSessionFactory" />

    34. "transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

    35. "dataSource" ref="dataSource" />

    36. "transactionAdvice" transaction-manager="transactionManager">

    37. "add*" propagation="REQUIRED" />

    38. "append*" propagation="REQUIRED" />

    39. "insert*" propagation="REQUIRED" />

    40. "save*" propagation="REQUIRED" />

    41. "update*" propagation="REQUIRED" />

    42. "modify*" propagation="REQUIRED" />

    43. "edit*" propagation="REQUIRED" />

    44. "delete*" propagation="REQUIRED" />

    45. "remove*" propagation="REQUIRED" />

    46. "repair" propagation="REQUIRED" />

    47. "delAndRepair" propagation="REQUIRED" />

    48. "get*" propagation="SUPPORTS" />

    49. "find*" propagation="SUPPORTS" />

    50. "load*" propagation="SUPPORTS" />

    51. "search*" propagation="SUPPORTS" />

    52. "datagrid*" propagation="SUPPORTS" />

    53. "*" propagation="SUPPORTS" />

    54. "transactionPointcut" expression="execution(* com.yingjun.test.service..*Impl.*(..))" />

    55. "transactionPointcut" advice-ref="transactionAdvice" />

    56. "1.0" encoding="UTF-8"?>

    57. "http://www.w3.org/2001/XMLSchema-instance"

    58. xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"

    59. xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"

    60. version="2.4">

    61. contextConfigLocation

    62. classpath:spring.xml

    63. class>org.springframework.web.context.ContextLoaderListenerclass>

    64. class>org.springframework.web.util.IntrospectorCleanupListenerclass>

    65. springMVC

    66. class>org.springframework.web.servlet.DispatcherServletclass>

    67. contextConfigLocation

    68. classpath:spring-mvc.xml

    69. 1

    70. springMVC

    71. /

    72. encodingFilter

    73. class>org.springframework.web.filter.CharacterEncodingFilterclass>

    74. encoding

    75. UTF-8

    76. forceEncoding

    77. true

    78. encodingFilter

    79. /*

    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.0modelVersion>

    4. <groupId>com.yingjun.testgroupId>

    5. <artifactId>TradingStateartifactId>

    6. <packaging>warpackaging>

    7. <version>2.0.1version>

    8. <properties>

    9. <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>

    10. <maven.build.timestamp.format>yyyyMMddHHmmssmaven.build.timestamp.format>

    11. <spring.version>3.2.9.RELEASEspring.version>

    12. <mybatis.version>3.1.1mybatis.version>

    13. <mybatisspring.version>1.1.1mybatisspring.version>

    14. properties>

    15. <dependencies>

    16. <dependency>

    17. <groupId>org.springframeworkgroupId>

    18. <artifactId>spring-coreartifactId>

    19. <version>${spring.version}version>

    20. dependency>

    21. <dependency>

    22. <groupId>org.springframeworkgroupId>

    23. <artifactId>spring-webmvcartifactId>

    24. <version>${spring.version}version>

    25. dependency>

    26. <dependency>

    27. <groupId>org.springframeworkgroupId>

    28. <artifactId>spring-testartifactId>

    29. <version>${spring.version}version>

    30. dependency>

    31. <dependency>

    32. <groupId>org.mybatisgroupId>

    33. <artifactId>mybatisartifactId>

    34. <version>${mybatis.version}version>

    35. dependency>

    36. <dependency>

    37. <groupId>org.mybatisgroupId>

    38. <artifactId>mybatis-springartifactId>

    39. <version>${mybatisspring.version}version>

    40. dependency>

    41. <dependency>

    42. <groupId>mysqlgroupId>

    43. <artifactId>mysql-connector-javaartifactId>

    44. <version>5.1.34version>

    45. dependency>

    46. <dependency>

    47. <groupId>junitgroupId>

    48. <artifactId>junitartifactId>

    49. <version>4.11version>

    50. <scope>testscope>

    51. dependency>

    52. <dependency>

    53. <groupId>c3p0groupId>

    54. <artifactId>c3p0artifactId>

    55. <version>0.9.1.2version>

    56. dependency>

    57. <dependency>

    58. <groupId>org.aspectjgroupId>

    59. <artifactId>aspectjweaverartifactId>

    60. <version>1.8.1version>

    61. dependency>

    62. <dependency>

    63. <groupId>javax.servletgroupId>

    64. <artifactId>jstlartifactId>

    65. <version>1.2version>

    66. dependency>

    67. <dependency>

    68. <groupId>javax.servletgroupId>

    69. <artifactId>servlet-apiartifactId>

    70. <version>3.0version>

    71. <scope>providedscope>

    72. dependency>

    73. <dependency>

    74. <groupId>javax.servlet.jspgroupId>

    75. <artifactId>jsp-apiartifactId>

    76. <version>2.2version>

    77. <scope>providedscope>

    78. dependency>

    79. <dependency>

    80. <groupId>commons-fileuploadgroupId>

    81. <artifactId>commons-fileuploadartifactId>

    82. <version>1.3.1version>

    83. dependency>

    84. <dependency>

    85. <groupId>commons-langgroupId>

    86. <artifactId>commons-langartifactId>

    87. <version>2.6version>

    88. dependency>

    89. <dependency>

    90. <groupId>commons-codecgroupId>

    91. <artifactId>commons-codecartifactId>

    92. <version>1.9version>

    93. dependency>

    94. <dependency>

    95. <groupId>org.apache.httpcomponentsgroupId>

    96. <artifactId>httpclientartifactId>

    97. <version>4.5version>

    98. dependency>

    99. <dependency>

    100. <groupId>org.slf4jgroupId>

    101. <artifactId>slf4j-apiartifactId>

    102. <version>1.7.10version>

    103. dependency>

    104. <dependency>

    105. <groupId>org.slf4jgroupId>

    106. <artifactId>slf4j-log4j12artifactId>

    107. <version>1.7.10version>

    108. dependency>

    109. <dependency>

    110. <groupId>log4jgroupId>

    111. <artifactId>log4jartifactId>

    112. <version>1.2.17version>

    113. dependency>

    114. <dependency>

    115. <groupId>com.alibabagroupId>

    116. <artifactId>fastjsonartifactId>

    117. <version>1.1.41version>

    118. dependency>

    119. <dependency>

    120. <groupId>org.codehaus.jacksongroupId>

    121. <artifactId>jackson-mapper-aslartifactId>

    122. <version>1.9.13version>

    123. dependency>

    124. dependencies>

    125. <build>

    126. <plugins>

    127. <plugin>

    128. <artifactId>maven-compiler-pluginartifactId>

    129. <version>2.3.2version>

    130. <configuration>

    131. <source>1.7source>

    132. <target>1.7target>

    133. configuration>

    134. plugin>

    135. <plugin>

    136. <artifactId>maven-war-pluginartifactId>

    137. <version>2.2version>

    138. <configuration>

    139. <version>3.0version>

    140. <failOnMissingWebXml>falsefailOnMissingWebXml>

    141. configuration>

    142. plugin>

    143. plugins>

    144. <finalName>${project.artifactId}_${project.version}_${maven.build.timestamp}finalName>

    145. build>

    146. project>

框架/平台构成:

Maven+Springmvc + Mybatis + Shiro(权限)+ Tiles(模板) +ActiveMQ(消息队列) + Rest(服务) + WebService(服务)+ EHcache(缓存) + Quartz(定时调度)+ Html5(支持PC、IOS、Android)

用户权限系统:
组织结构:角色、用户、用户组、组织机构;权限点:页面、方法、按钮、数据权限、分级授权

项目管理新体验
快速出原型系统、组件树、版本控制、模块移植、协同开发、实时监控、发布管理

可持续集成:
所有组件可移植、可定制、可扩充,开发成果不断积累,形成可持续发展的良性循环

支持平台平台:
Windows XP、Windows 7 、Windows 10 、 Linux 、 Unix

服务器容器:
Tomcat 5/6/7 、Jetty、JBoss、WebSphere 8.5


0