手把手Maven搭建SpringMVC+Spring+MyBatis框架(超級詳細版)

手把手Maven搭建SpringMVC+Spring+MyBatis框架(超級詳細版)html

SSM(Spring+SpringMVC+Mybatis),目前較爲主流的企業級架構方案。標準的MVC設計模式,將整個系統劃分爲顯示層、Controller層、Service層、Dao層四層,使用SpringMVC負責請求的轉發和視圖管理,Spring實現業務對象管理, MyBatis做爲數據對象持久化引擎。java

一. 框架詳情mysql

Spring是一個輕量級的Java開發框架,它是爲了解決企業應用開發的複雜性而建立的。Spring的用途不只限於服務器端的開發。從簡單性、可測試性和鬆耦合的角度而言,任何Java應用均可以從Spring中受益。 簡單來講,Spring是一個輕量級的控制反轉(IoC)和麪向切面(AOP)的容器框架。web

SpringMVC屬於SpringFrameWork的後續產品,分離了控制器、模型對象、分派器以及處理程序對象的角色,這種分離讓它們更容易進行定製。spring

MyBatis是一個基於Java的持久層框架。MyBatis提供的持久層框架包括SQL Maps和Data Access Objects(DAO)它消除了幾乎全部的JDBC代碼和參數的手工設置以及結果集的檢索。MyBatis 使用簡單的 XML或註解用於配置和原始映射,將接口和 Java映射成數據庫中的記錄。sql

二. 建立Maven項目數據庫

Eclipse中用Maven建立項目apache


按默認Nextjson


找到maven-archetype-webapp後,點擊next設計模式


填寫相應的信息,GroupID是項目組織惟一的標識符,實際對應JAVA的包的結構。ArtifactID就是項目的惟一的標識符,實際對應項目的名稱,就是項目根目錄的名稱。Package填了默認給你建一個包,不寫也能夠。


剛建好的目錄以下


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。


分別修改輸出路徑爲,對應關係以下:


將項目轉換成Dynamic Web Project,在項目上右鍵Properties,在左側選擇 Project Facets。


設置部署時的文件發佈路徑,刪除test的兩項,由於test是測試使用,並不須要部署。

設置將Maven的jar包發佈到lib下。Add -> Java Build Path Entries -> Maven Dependencies -> Finish


三. Maven引入須要的JAR包

Xml代碼

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

4.0.0

com.yingjun.test

TradingState

war

2.0.1

UTF-8

yyyyMMddHHmmss

3.2.9.RELEASE

3.1.1

1.1.1

org.springframework

spring-core

${spring.version}

org.springframework

spring-webmvc

${spring.version}

org.springframework

spring-test

${spring.version}

org.mybatis

mybatis

${mybatis.version}

org.mybatis

mybatis-spring

${mybatisspring.version}

mysql

mysql-connector-java

5.1.34

junit

junit

4.11

test

c3p0

c3p0

0.9.1.2

org.aspectj

aspectjweaver

1.8.1

javax.servlet

jstl

1.2

javax.servlet

servlet-api

3.0

provided

javax.servlet.jsp

jsp-api

2.2

provided

commons-fileupload

commons-fileupload

1.3.1

commons-lang

commons-lang

2.6

commons-codec

commons-codec

1.9

org.apache.httpcomponents

httpclient

4.5

org.slf4j

slf4j-api

1.7.10

org.slf4j

slf4j-log4j12

1.7.10

log4j

log4j

1.2.17

com.alibaba

fastjson

1.1.41

org.codehaus.jackson

jackson-mapper-asl

1.9.13

maven-compiler-plugin

2.3.2

1.7

1.7

maven-war-plugin

2.2

3.0

false

${project.artifactId}_${project.version}_${maven.build.timestamp}

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

web.xml

Java代碼

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">

contextConfigLocation

classpath:spring.xml

org.springframework.web.context.ContextLoaderListener

org.springframework.web.util.IntrospectorCleanupListener

springMVC

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath:spring-mvc.xml

1

springMVC

/

encodingFilter

org.springframework.web.filter.CharacterEncodingFilter

encoding

UTF-8

forceEncoding

true

encodingFilter

/*

spring.xml

Java代碼

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 ">

爲了代替手工使用 SqlSessionDaoSupport 或 SqlSessionTemplate 編寫數據訪問對象 (DAO)的代碼,MyBatis-Spring 提供了一個動態代理的實現:MapperFactoryBean。這個類 可讓你直接注入數據映射器接口到你的 service 層 bean 中。當使用映射器時,你僅僅如調 用你的 DAO 同樣調用它們就能夠了,可是你不須要編寫任何 DAO 實現的代碼,由於 MyBatis-Spring 將會爲你建立代理。

spring-mybatis.xml

Java代碼

spring-mvc.xml

Java代碼

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">

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

text/html;charset=UTF-8

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

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

log4j.properties

Sql代碼

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

Java代碼

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代碼

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

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

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

userId="root"password="root">

targetProject="src">

targetProject="src">

targetProject="src">

enableCountByExample="fasle"enableUpdateByExample="false"

enableDeleteByExample="false"enableSelectByExample="false"

selectByExampleQueryId="false">

打開CMD窗口 進入該目錄結構,輸入命令行:

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

運行完成後會生成相應的dao mapper 和model,是否是很爽。

六. 創建Service層以及conrorller層

Java代碼

packagecom.yingjun.test.service;

publicinterfaceOtherServiceI {

publicString getOterList();

}

Java代碼

packagecom.yingjun.test.service;

importjava.util.ArrayList;

importjava.util.Arrays;

importjava.util.HashSet;

importjava.util.List;

importjava.util.Map;

importjava.util.Set;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.stereotype.Service;

importcom.alibaba.fastjson.JSON;

importcom.alibaba.fastjson.serializer.SerializerFeature;

importcom.yingjun.test.dao.OtherListMapper;

importcom.yingjun.test.model.OtherList;

importcom.yingjun.test.model.OtherListDomain;

@Service

publicclassOtherServiceImplimplementsOtherServiceI {

@Autowired

privateOtherListMapper otherListMapper;

@Override

publicString getOterList() {

Set set=newHashSet();

List list=otherListMapper.selectAll();

List jsonList=newArrayList();

for(OtherList other:list){

String title=other.getTitle();

if(set.contains(title)){

continue;

}else{

List t_list=newArrayList();

for(OtherList data:list){

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

t_list.add(data);

}

}

OtherListDomain domain=newOtherListDomain();

domain.setTitle(title);

domain.setItems(t_list);

jsonList.add(domain);

set.add(other.getTitle());

}

}

returnJSON.toJSONString(jsonList, SerializerFeature.WriteMapNullValue);

}

}

Java代碼

packagecom.yingjun.test.controller;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.stereotype.Controller;

importorg.springframework.web.bind.annotation.RequestMapping;

importorg.springframework.web.bind.annotation.ResponseBody;

importcom.alibaba.fastjson.JSON;

importcom.yingjun.test.service.OtherServiceI;

importcom.yingjun.test.service.StockStatusServiceI;

@Controller

@RequestMapping(value ="/")

publicclassTSSController {

@Autowired

privateOtherServiceI otherService;

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

@ResponseBody

privateString getOtherList(){

String json=otherService.getOterList();

returnjson;

}

}

七. 創建測試類

Java代碼

importjava.util.List;

importorg.apache.log4j.LogManager;

importorg.apache.log4j.Logger;

importorg.junit.Test;

importorg.junit.runner.RunWith;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.test.context.ContextConfiguration;

importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)

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

publicclassTestMybatis {

@Autowired

privateOtherServiceI service;

@Test

publicvoidtest() {

String list=service.getOterList();

logger.info(list);

}

}

願意瞭解框架技術或者源碼的朋友直接求求:2042849237

相關文章
相關標籤/搜索