最近比較閑还棱,復(fù)習(xí)搭建一下項目饮亏,這次主要使用Spring+SpringMVC+Mybatis慨绳。項目持久層使用Mybatis3,控制層使用SpringMVC4.1被环,使用Spring4.1管理控制器,數(shù)據(jù)庫連接池使用druid數(shù)據(jù)源,該項數(shù)據(jù)庫暫使用MySQL简肴。
1战秋、 數(shù)據(jù)庫表結(jié)構(gòu)以及maven項目結(jié)構(gòu)
數(shù)據(jù)表非常的簡單(不是重點),如下:
創(chuàng)建maven項目創(chuàng)建Maven Project時悴能,將Filter選擇為org.apache.maven.archetypes揣钦。填寫完相關(guān)項目坐標信息后項目結(jié)構(gòu)如下:
注:若無src/main/java,src/test/java漠酿,src/test/resources時冯凹,創(chuàng)建這個幾個Source Folder。
2、修改pom.xml添加對應(yīng)的包依賴
這兒將全部使用的Maven依賴貼出了宇姚,對應(yīng)什么作用上面都有解釋匈庭,如下:
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相關(guān)表信息
自動生成表的Model浑劳,Mapping阱持,Dao文件
并將其導(dǎo)入到項目的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并配置相關(guān)屬性
在src/main/resources創(chuàng)建spring的配置文件衷咽,這里創(chuàng)建了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并配置數(shù)據(jù)連接池等信息
5.1镶骗、數(shù)據(jù)連接池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相關(guān)信息
以下是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" />
主要配置數(shù)據(jù)連接池鼎姊,事務(wù)管理, mybatis關(guān)聯(lián)映射等相赁,事務(wù)采用aop的聲明式事務(wù)相寇。
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钮科、創(chuàng)建Service
在src/main/java中創(chuàng)建相關(guān)的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;
/**
* 創(chuàng)建時間: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實現(xiàn)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;
/**
* 創(chuàng)建時間: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中寫測試類跺嗽,檢測是否能夠讀出數(shù)據(jù)战授,若能讀出則證明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;
/**
* 創(chuàng)建時間: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);
}
}
若是測試成功桨嫁,那證明已經(jīng)成功了一半了植兰。
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容器配置啟動加載的配置文件,設(shè)置SpringMVC攔截的請求(此處攔截.htmls結(jié)尾的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創(chuàng)建控制層毡咏,如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;
/**
* 創(chuàng)建時間: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創(chuàng)建視圖總目錄views(為了安全起見一般都在WEB-INF下創(chuàng)建)逮刨,創(chuàng)建/user/showInfo.jsp視圖文件呕缭。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
userInfo
姓名: ${userInfo.uname}
9.5、項目總目錄結(jié)構(gòu)
到此為demo以及基本創(chuàng)建完成總目錄如下:
10、項目測試
將項目編譯恢总,Maven build...輸入clean compile package迎罗,部署到Tomcat服務(wù)器,啟動項目片仿。
測試1:測試第一個url纹安,? http://localhost:8080/springmvc_mybatis_demo/user/showInfo/1.htmls
測試2:測試第二個json數(shù)據(jù)返回的url,? http://localhost:8080/springmvc_mybatis_demo/user/showInfos.htmls
核心技術(shù):Maven,Springmvc mybatis shiro, Druid, Restful, Dubbo, ZooKeeper,Redis,FastDFS,ActiveMQ,Nginx
1.?????項目核心代碼結(jié)構(gòu)截圖
項目模塊依賴
特別提醒:開發(fā)人員在開發(fā)的時候可以將自己的業(yè)務(wù)REST服務(wù)化或者Dubbo服務(wù)化
2.????項目依賴介紹
2.1?后臺管理系統(tǒng)砂豌、Rest服務(wù)系統(tǒng)厢岂、Scheculer定時調(diào)度系統(tǒng)依賴如下圖:
2.2?Dubbo獨立服務(wù)項目依賴如下圖:
3.??項目功能部分截圖:
zookeeper、dubbo服務(wù)啟動
dubbo管控臺
REST服務(wù)平臺