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

网友投稿 267 2023-03-06


详解手把手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包

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}

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

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

/*

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

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

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

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

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

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

http://springframework.org/schema/mvc

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

http://springframework.org/schema/context

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

http://springframework.org/schema/aop

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

http://springframework.org/schema/tx

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

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

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

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

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

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

http://springframework.org/schema/mvc

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

http://springframework.org/schema/context

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

http://springframework.org/schema/aop

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

http://springframework.org/schema/tx

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

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

spring-mybatis.xml

spring-mvc.xml

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

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

xmlns:mvc="http://springframework.org/schema/mvc"

xsi:schemaLocation="

http://springframework.org/schema/beans

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

http://springframework.org/schema/context

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

http://springframework.org/schema/mvc

http://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">

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

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

xmlns:mvc="http://springframework.org/schema/mvc"

xsi:schemaLocation="

http://springframework.org/schema/beans

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

http://springframework.org/schema/context

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

http://springframework.org/schema/mvc

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

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

text/html;charset=UTF-8

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

text/html;charset=UTF-8

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

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

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

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

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.Chttp://onversionPattern =%d %p[%c:%L] - %m%n

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

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

生成代码需要的文件和jar并建立如下目录结构:

在generatorl.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">

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

userId="root" password="root">

targetProject="src">

targetProject="src">

targetProject="src">

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层

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 set=new HashSet();

List list=otherListMapper.selectAll();

List jsonList=new ArrayList();

for(OtherList other:list){

String title=other.getTitle();

if(set.contains(thttp://itle)){

continue;

}else{

List t_list=new ArrayList();

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三大框架的整合就完成了,有什么其他需求可以在此基础继续添


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:移动API网关(移动网关 dmz)
下一篇:Java实现特定范围的完数输出算法示例
相关文章

 发表评论

暂时没有评论,来抢沙发吧~