Maven搭建SpringMVC+Mybatis專案詳解【轉】
最近比較閒,複習搭建一下專案,這次主要使用Spring+SpringMVC+Mybatis。專案持久層使用Mybatis3,控制層使用SpringMVC4.1,使用Spring4.1管理控制器,資料庫連線池使用druid資料來源,該項資料庫暫使用MySQL。
1、 資料庫表結構以及maven專案結構
資料表非常的簡單(不是重點),如下:
建立maven專案建立Maven Project時,將Filter選擇為org.apache.maven.archetypes。填寫完相關專案座標資訊後專案結構如下:
注:若無src/main/java,src/test/java,src/test/resources時,建立這個幾個Source Folder。
2、修改pom.xml新增對應的包依賴
這兒將全部使用的Maven依賴貼出了,對應什麼作用上面都有解釋,如下:
pom.xml
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
org.andy.sm
springmvc_mybatis_demo
war
0.0.1-SNAPSHOT
springmvc_mybatis_demo Maven Webapp
http://maven.apache.org
UTF-8
4.1.4.RELEASE
2.5.0
junit
junit
4.12
test
org.springframework
spring-core
${spring.version}
org.springframework
spring-beans
${spring.version}
org.springframework
spring-context
${spring.version}
org.springframework
spring-tx
${spring.version}
org.springframework
spring-web
${spring.version}
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework
spring-test
${spring.version}
test
org.mybatis
mybatis
3.2.8
org.mybatis
mybatis-spring
1.2.2
mysql
mysql-connector-java
5.1.34
com.alibaba
druid
1.0.12
org.aspectj
aspectjweaver
1.8.4
log4j
log4j
1.2.17
javax.servlet
servlet-api
3.0-alpha-1
javax.servlet
jstl
1.2
org.codehaus.jackson
jackson-mapper-asl
1.9.13
com.alibaba
fastjson
1.2.3
com.fasterxml.jackson.core
jackson-annotations
${jackson.version}
com.fasterxml.jackson.core
jackson-core
${jackson.version}
com.fasterxml.jackson.core
jackson-databind
${jackson.version}
commons-io
commons-io
2.4
commons-fileupload
commons-fileupload
1.2.2
springmvc_mybatis_demo
org.apache.maven.plugins
maven-surefire-plugin
2.4.2
true
org.apache.maven.plugins
maven-war-plugin
2.3
src/main/webapp/WEB-INF/web.xml
org.apache.maven.plugins
maven-javadoc-plugin
2.9.1
target/javadoc
target/javadoc
UTF-8
UTF-8
UTF-8
private
org.codehaus.cargo
cargo-maven2-plugin
1.0
tomcat6x
D:\WebServer\apache-tomcat-6.0.39
existing
D:\WebServer\apache-tomcat-6.0.39
3、使用Generator自動生成Mybatis相關表資訊
自動生成表的Model,Mapping,Dao檔案
並將其匯入到專案的src/main/java包中。
其中生成的Model中UserInfo如下:
UserInfo.java(其中List courseInfos手動新增的)
package org.andy.shop.model;
import java.util.List;
public class UserInfo {
private Integer id;
private String uname;
private Integer unumber;
private List courseInfos;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname == null ? null : uname.trim();
}
public Integer getUnumber() {
return unumber;
}
public void setUnumber(Integer unumber) {
this.unumber = unumber;
}
public List getCourseInfos() {
return courseInfos;
}
}
Dao包中的UserInfoMapper.java
package org.andy.shop.dao;
import java.util.List;
import org.andy.shop.model.UserInfo;
public interface UserInfoMapper {
int deleteByPrimaryKey(Integer id);
int insert(UserInfo record);
int insertSelective(UserInfo record);
UserInfo selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(UserInfo record);
int updateByPrimaryKey(UserInfo record);
List selectAll();
}
mapping 中的配置檔案UserInfoMapper.xml
id, uname, unumber
parameterType="java.lang.Integer">
select
from user_info
where id = #{id,jdbcType=INTEGER}
delete from
user_info
where id = #{id,jdbcType=INTEGER}
insert into user_info (id,
uname, unumber
)
values (#{id,jdbcType=INTEGER},
#{uname,jdbcType=VARCHAR},
#{unumber,jdbcType=INTEGER}
)
insert into user_info
id,
uname,
unumber,
#{id,jdbcType=INTEGER},
#{uname,jdbcType=VARCHAR},
#{unumber,jdbcType=INTEGER},
update user_info
uname = #{uname,jdbcType=VARCHAR},
unumber = #{unumber,jdbcType=INTEGER},
where id = #{id,jdbcType=INTEGER}
update user_info
set uname = #{uname,jdbcType=VARCHAR},
unumber =
#{unumber,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
extends="BaseResultMap">
ofType="org.andy.shop.model.CourseInfo">
select u.id, u.uname,
u.unumber, c.id course_id, c.cname, c.caddress from user_info u left
join course_user_info cu on u.id = cu.uid
left join course_info c on
cu.cid = c.id
4、引入Spring並配置相關屬性
在src/main/resources建立spring的配置檔案,這裡建立了spring.xml,資訊如下:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
5、引入Mybatis並配置資料連線池等資訊
5.1、資料連線池druid配置資訊
配置連線池配置資訊在config.properties中,如下:
#mysql version database druid setting
validationQuery=SELECT 1
jdbc.url=jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=12345
5.2、配置Mybatis相關資訊
以下是mybatis的配置資訊:spring-mybatis.xml(ps:名字可隨便起)
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
">
init-method="init" destroy-method="close">
value="33" />
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
expression="execution(* org.andy.shop.service..*Impl.*(..))" />
advice-ref="transactionAdvice" />
主要配置資料連線池,事務管理, mybatis關聯對映等,事務採用aop的宣告式事務。
6、引入日誌
在src/main/resources中新增log4j日誌配置資訊:
log4j.properties
### set log levels ###
log4j.rootLogger = INFO , C , D , E
### console ###
log4j.appender.C = org.apache.log4j.ConsoleAppender
log4j.appender.C.Target = System.out
log4j.appender.C.layout = org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern = [springmvc_mybatis_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
### log file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ../logs/springmvc-mybatis-demo.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = [springmvc_mybatis_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
### exception ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = ../logs/springmvc-mybatis-demo_error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = [sspringmvc_mybatis_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
7、建立Service
在src/main/java中建立相關的org.andy.shop.service包和org.andy.shop.service.Impl包。
UserService介面:
package org.andy.shop.service;
import java.util.List;
import org.andy.shop.model.UserInfo;
/**
* 建立時間:2015-1-27 下午5:15:03
* @author andy
* @version 2.2
*/
public interface UserService {
UserInfo getUserById(int id);
List getUsers();
int insert(UserInfo userInfo);
}
UserServiceImpl實現Service:
package org.andy.shop.service.impl;
import java.util.List;
import org.andy.shop.dao.UserInfoMapper;
import org.andy.shop.model.UserInfo;
import org.andy.shop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 建立時間:2015-1-27 下午5:22:59
*
* @author andy
* @version 2.2
*/
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserInfoMapper userInfoMapper;
@Override
public UserInfo getUserById(int id) {
return userInfoMapper.selectByPrimaryKey(id);
}
@Override
public List getUsers() {
return userInfoMapper.selectAll();
}
@Override
public int insert(UserInfo userInfo) {
int result = userInfoMapper.insert(userInfo);
System.out.println(result);
return result;
}
}
8、測試Spring和Mybatis配置
在src/test/java中寫測試類,檢測是否能夠讀出資料,若能讀出則證明Spring+Mybatis整合成功。
TestUserService測試類:
package org.andy.shop.service;
import java.util.List;
import org.andy.shop.model.UserInfo;
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;
import com.alibaba.fastjson.JSON;
/**
* 建立時間:2015-1-27 下午10:45:38
*
* @author andy
* @version 2.2
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring.xml",
"classpath:spring-mybatis.xml" })
public class TestUserService {
private static final Logger LOGGER = Logger
.getLogger(TestUserService.class);
@Autowired
private UserService userService;
@Test
public void testQueryById1() {
UserInfo userInfo = userService.getUserById(1);
LOGGER.info(JSON.toJSON(userInfo));
}
@Test
public void testQueryAll() {
List userInfos = userService.getUsers();
LOGGER.info(JSON.toJSON(userInfos));
}
@Test
public void testInsert() {
UserInfo userInfo = new UserInfo();
userInfo.setUname("xiaoming");
userInfo.setUnumber(4);
int result = userService.insert(userInfo);
System.out.println(result);
}
}
若是測試成功,那證明已經成功了一半了。
9、引入SpringMVC
9.1 配置SpringMVC配置資訊
SpringMVC的配置資訊主要包括控制層Controller的bean管理,檢視層和控制層配置等等,下面是spring-mvc.xml資訊:
xmlns:mvc="http://www.springframework.org/schema/mvc" 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
text/html;charset=UTF-8
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
value="org.springframework.web.servlet.view.JstlView" />
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
UTF-8
32505856
4096
自動掃描org.andy.shop.controller報下還有@Controller的控制層,注入為bean。
9.2、Web容器web.xml配置
web容器配置啟動載入的配置檔案,設定SpringMVC攔截的請求(此處攔截.htmls結尾的url請求)
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
springmvc_mybatis_demo
contextConfigLocation
classpath:spring.xml,classpath:spring-mybatis.xml
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
utf-8
forceEncoding
true
encodingFilter
/*
org.springframework.web.context.ContextLoaderListener
org.springframework.web.util.IntrospectorCleanupListener
spring mvc servlet
rest
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
1
rest
*.htmls
30
index.jsp
9.3、Controller控制層
在org.andy.shop.controller建立控制層,如UserController.java
package org.andy.shop.controller;
import java.util.List;
import org.andy.shop.model.UserInfo;
import org.andy.shop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 建立時間:2015-1-28 下午1:17:27
* @author andy
* @version 2.2
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/showInfo/{userId}")
public String showUserInfo(ModelMap modelMap, @PathVariable int userId){
UserInfo userInfo = userService.getUserById(userId);
modelMap.addAttribute("userInfo", userInfo);
return "/user/showInfo";
}
@RequestMapping("/showInfos")
public @ResponseBody Object showUserInfos(){
List userInfos = userService.getUsers();
return userInfos;
}
}
9.4、檢視層
在WEB-INF建立檢視總目錄views(為了安全起見一般都在WEB-INF下建立),建立/user/showInfo.jsp檢視檔案。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
userInfo
姓名: ${userInfo.uname}
9.5、專案總目錄結構
到此為demo以及基本建立完成總目錄如下:
10、專案測試
將專案編譯,Maven build...輸入clean compile package,部署到Tomcat伺服器,啟動專案。
測試1:測試第一個url, http://localhost:8080/springmvc_mybatis_demo/user/showInfo/1.htmls
測試2:測試第二個json資料返回的url, http://localhost:8080/springmvc_mybatis_demo/user/showInfos.htmls
核心技術:Maven,Springmvc mybatis shiro, Druid, Restful, Dubbo, ZooKeeper,Redis,FastDFS,ActiveMQ,Nginx
1. 專案核心程式碼結構截圖
專案模組依賴
特別提醒:開發人員在開發的時候可以將自己的業務REST服務化或者Dubbo服務化
2. 專案依賴介紹
2.1 後臺管理系統、Rest服務系統、Scheculer定時排程系統依賴如下圖:
2.2 Dubbo獨立服務專案依賴如下圖:
3. 專案功能部分截圖:
zookeeper、dubbo服務啟動
dubbo管控臺
REST服務平臺
相關文章
- SpringMVC 乾貨系列:從零搭建 SpringMVC+mybatis(一):maven WEB 專案的搭建 | 掘金技術徵文SpringMVCMyBatisMavenWeb
- SpringMVC 乾貨系列:從零搭建 SpringMVC+mybatis(一):maven WEB 專案的搭建 | 掘金技術徵文...SpringMVCMyBatisMavenWeb
- IDEA執行maven專案詳解IdeaMaven
- eclipse 搭建maven專案EclipseMaven
- Maven--搭建Web專案MavenWeb
- IDEA搭建和部署Maven專案IdeaMaven
- Spring Boot + Maven 多模組專案開發詳解Spring BootMaven
- Maven-Eclipse搭建一個maven專案(方法二)MavenEclipse
- idea ssm maven專案搭建筆記IdeaSSMMaven筆記
- maven 專案轉化成 gradle 專案實踐MavenGradle
- 把普通java專案轉換成maven專案JavaMaven
- Maven中optional標籤詳解(轉)Maven
- SpringBoot + maven 父子模組專案搭建Spring BootMaven
- Spirng+SpringMVC+Maven+Mybatis+MySQL專案搭建SpringMVCMavenMyBatisMySql
- Maven專案中POM.xml檔案內的標籤大全詳解MavenXML
- maven詳解Maven
- Maven 學習筆記——將普通的Java專案轉換成Maven專案(3)Maven筆記Java
- 【小白第一篇】maven搭建ssm專案MavenSSM
- Maven的pom.xml檔案詳解MavenXML
- Maven pom.xml檔案配置詳解MavenXML
- IDEA使用maven搭建SSM框架整合專案(超級詳細,值得一看)IdeaMavenSSM框架
- maven專案缺jar問題解決MavenJAR
- Eclipse-用Eclipse搭建一個maven專案EclipseMaven
- Maven 搭建spring boot多模組專案(附原始碼)MavenSpring Boot原始碼
- IDEA新建Maven Java Web專案-詳細教程IdeaMavenJavaWeb
- Maven 專案模板Maven
- Maven 專案文件Maven
- Maven快速入門(四)Maven中的pom.xml檔案詳解MavenXML
- Eclipse-用Eclipse搭建一個maven專案-續EclipseMaven
- 解決maven專案控制檯資訊亂碼Maven
- Maven安裝詳解Maven
- Maven入門詳解Maven
- 建立Maven模板專案Maven
- maven 建立web專案MavenWeb
- Maven建立Java專案MavenJava
- JN專案配置-公司是maven專案Maven
- Maven教程(Eclipse配置及maven專案)MavenEclipse
- MyEclipse2017破解設定與maven專案搭建EclipseMaven