程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> spring+springMVC+mybatis的框架項目基礎環境搭建

spring+springMVC+mybatis的框架項目基礎環境搭建

編輯:JAVA綜合教程

spring+springMVC+mybatis的框架項目基礎環境搭建


一、 搭建目標:
實現標准的後台controller、service、dao三層結構;
使用mapper.xml配置文件實現dao層和數據庫的交互;
數據庫連接信息、基礎配置文件存在config.properties文件中;
配置日志打印相關的信息;
配置數據庫連接池;
使用注解;
配置json數據前後台交互;
使用junit測試;
二、環境基礎:
eclipe4.4.1;
maven3.2.5;
spring4.0.3;
mysql5.6;
jdk1.7;
tomcat7;
Angularjs1.4.0;
注:為了確定後台環境是真的沒有問題,自然也需要簡單搭一下前台的環境,起碼要能保證前後台交互沒有問題。因此我前台也簡單的弄了一下angularjs,實際上我們項目中前端環境已經不這麼搭裡 ,只是新的搭法我還不會
三、項目整體結構如下:
1、 後端:
\
2、 前端:\
四、maven導包及基礎配置pom.xml代碼:
  4.0.0
  frameTest
  frameTest
  war
  0.0.1-SNAPSHOT
  frameTest Maven Webapp
  http://maven.apache.org  
 
maven-compiler-plugin
2.3.2

1.7
1.7
UTF-8

                       
                        ${java.home}\lib\rt.jar
                   





src/main/java

**/*.xml



src/main/resources

**/*.*



frameTest


   
4.0.3.RELEASE
 



 
org.springframework
spring-test
${spring-version}



org.springframework
spring-webmvc
${spring-version}



org.springframework
spring-core
${spring-version}



org.springframework
spring-context
${spring-version}



org.springframework
spring-context-support
${spring-version}



org.springframework
spring-beans
${spring-version}



org.springframework
spring-orm
${spring-version}



org.springframework.amqp
spring-amqp
1.2.0.RELEASE



org.aspectj
aspectjweaver
1.7.1




org.mybatis
mybatis
3.2.7



org.mybatis
mybatis-spring
1.2.2



com.alibaba
druid
1.0.2




mysql
mysql-connector-java
5.1.34




junit
junit
4.11
test


 

org.codehaus.jackson
jackson-mapper-asl
1.9.7




com.alibaba
fastjson
1.1.26



org.codehaus.jackson
jackson-core-asl
1.9.7



javax.servlet
servlet-api
3.0-alpha-1
provided



org.apache.geronimo.specs
geronimo-servlet_3.0_spec
1.0
test



cglib
cglib
2.2




ch.qos.logback
logback-classic
1.0.9



commons-io
commons-io
2.4




com.github.snakerflow
snaker-core
2.5.1





org.apache.commons
commons-lang3
3.3.1
  

 


五、web項目基礎配置文件web.xml:

  appversion
  
    contextConfigLocation
    classpath:spring.xml
  
  
  
    字符集過濾器
    encodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    
      字符集編碼
      encoding
      UTF-8
    
  
  
    encodingFilter
    /*
  
  
    spring監聽器
    org.springframework.web.context.ContextLoaderListener
  
  
    org.springframework.web.util.IntrospectorCleanupListener
  
  
    dispatcher
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      classpath:spring-mvc.xml
    
    1
  
  
    dispatcher
    /
  
  
    15
  


六、spring基礎篇日志文件spring.xml:


	
	
    
	
	


	
	


	
	
	
	
	
	
	
	


七、mybatis基礎配置文件spring-MybatisConfig.xml:




	
	
		  
		  
		  
		   
		  
		  
		  
		  
		  
		  
		  
		  
		  
		  
		  
	
	 
	
	
		
		
		
	
	
	
	
	    
	
	
		
	
  		
	


七、mybatis基礎配置文件MybatisConf.xml:


	
		
		
		
		
		
		
		
		
		
		 
		   
	
	
	
	
		
	
	



八、springMVC基礎配置文件spring-mvc.xml:

	
		
	
	
    
	
	
		
			
				text/html;charset=UTF-8
			
		
	

	
	
		
			
				
				
			
		
	
	


九、日志打印相關配置logback.xml:

      
      
	
	
		
			%d{yyyy-MM-dd HH:mm:ss:SSS}[%p]: %m%n
		
	
	
	   
       

        
			
			${LOG_HOME}//merchant.%d{yyyy-MM-dd}.log
			
			30
		
		
		
			%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} -%msg%n
		
     
    
	
	
		
	
	 
	 
	  
	  
	    
  
  
  
      
      
 
	
	
		
		
	

 

 

十、屬性文件config.properties:
#mysql
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/merchant?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

#c3p0
c3p0.minPoolSize=5
c3p0.initialPoolSize=10
c3p0.maxIdleTime=60
c3p0.acquireIncrement=5
c3p0.idleConnectionTestPeriod=60
c3p0.acquireRetryAttempts=30
c3p0.acquireRetryDelay=1000
c3p0.numHelperThreads=3
c3p0.breakAfterAcquireFailure=true
c3p0.testConnectionOnCheckout=false
c3p0.maxStatements=0
c3p0.maxStatementsPerConnection=0

#druid 阿裡巴巴提供的JDBC連接池、監控組件
druid.minPoolSize=5
druid.maxPoolSize=30
druid.initialPoolSize=10
druid.maxIdleTime=60
druid.acquireIncrement=5
druid.idleConnectionTestPeriod=60
druid.acquireRetryAttempts=30
druid.acquireRetryDelay=1000
druid.numHelperThreads=3
druid.breakAfterAcquireFailure=true
druid.testConnectionOnCheckout=false
druid.maxStatements=0
druid.maxStatementsPerConnection=0
druid.maxWait=60000
druid.timeBetweenEvictionRunsMillis=3000
druid.minEvictableIdleTimeMillis=300000
druid.maxPoolPreparedStatementPerConnectionSize=20
druid.validationQuery=SELECT 'x'
druid.testWhileIdle=true
druid.testOnBorrow=false
druid.testOnReturn=false
druid.poolPreparedStatements=false
十一、為了驗證這些配置是否可行,我寫了一個簡單的增加用戶信息的操作,代碼分別如下:
後台實體類userModel:
package merModel;
import java.io.Serializable;
public class UserModel implements Serializable {
	private static final long serialVersionUID = -3291196087479862240L;

	private int id;
	/**
	 * 用戶賬號
	 */
	private String account;

	/**
	 * 用戶姓名
	 */
	private String userName;

	/**
	 * 用戶密碼
	 */
	private String password;

	/**
	 * 手機
	 */
	private String mobile;

	/**
	 * 郵箱
	 */
	private String email;

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getMobile() {
		return mobile;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	@Override
	public String toString() {
		return "UserModel [id=" + id + ", account=" + account + ", userName="
				+ userName + ", password=" + password + ", modile=" + mobile
				+ ", email=" + email + "]";
	}

}


對應的前台UserCommand類:
package merCommand;
public class UserCommand {
	private int id;
	/**
	 * 用戶賬號
	 */
	private String account;


	/**
	 * 用戶姓名
	 */
	private String userName;


	/**
	 * 用戶密碼
	 */
	private String password;


	/**
	 * 手機
	 */
	private String mobile;


	/**
	 * 郵箱
	 */
	private String email;


	public String getAccount() {
		return account;
	}


	public void setAccount(String account) {
		this.account = account;
	}


	public String getUserName() {
		return userName;
	}


	public void setUserName(String userName) {
		this.userName = userName;
	}


	public String getPassword() {
		return password;
	}


	public void setPassword(String password) {
		this.password = password;
	}


	public String getMobile() {
		return mobile;
	}


	public void setMobile(String mobile) {
		this.mobile = mobile;
	}


	public String getEmail() {
		return email;
	}


	public void setEmail(String email) {
		this.email = email;
	}


	public int getId() {
		return id;
	}


	public void setId(int id) {
		this.id = id;
	}


	@Override
	public String toString() {
		return "UserCommand [id=" + id + ", account=" + account + ", userName="
				+ userName + ", password=" + password + ", modile=" + mobile
				+ ", email=" + email + "]";
	}


}

Dao接口UserDao:
package merDao;
import merModel.UserModel;
public interface UserDao {
	public void save(UserModel usermodel);
}

Dao實現userDaoMapper.xml:


	
	
		
		
		
		
		
			
	


	id,account,userName,password,mobile,email
	
	
	
	
		insert into user()
	values(#{id},#{account},#{userName},#{password},#{mobile},#{email})
	
	
	 查詢用戶-->
	
	 

UserService接口:
package merService;
import merModel.UserModel;
public interface UserService {
	public void add(UserModel usermodel);
}


userService實現:
package merService.merServiceImp;
import javax.annotation.Resource;
import merDao.UserDao;
import merModel.UserModel;
import merService.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service("UserService")
public class UserServiceImp implements UserService {
	privatefinal Logger logger = LoggerFactory.getLogger(UserServiceImp.class);

	private UserDao userDao;

	@Resource(name = "userDao")
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public void add(UserModel usermodel) {
		userDao.save(usermodel);
	}
}

Controller前後台交互:
package merController;
import merCommand.UserCommand;
import merModel.UserModel;
import merService.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
	@Autowired
	private UserService userService;


	/**
	 * 新增用戶
	 * 
	 * @author:tuzongxun
	 * @Title: addUser
	 * @param @param userCommand
	 * @return void
	 * @date Apr 14, 2016 11:28:47 AM
	 * @throws
	 */
	@RequestMapping(value = "addUser", method = RequestMethod.POST)
	public void addUser(@RequestBody UserCommand userCommand) {
		UserModel userModel = new UserModel();
		BeanUtils.copyProperties(userCommand, userModel);
		userService.add(userModel);
	}
}

前台index.html文件:




<script src="./angular-1.4.0-rc.2/angular.js"></script><script src='./angular-1.4.0-rc.2/angular-ui-router.js'></script><script src='./js/app.js'></script><script src='./js/addUserCtr.js'></script>

 

 
前台app.js文件代碼:
var app=angular.module('merchantApp',['ui.router']);  
app.config(function($stateProvider,$urlRouterProvider){  
    $urlRouterProvider.otherwise('/addUser');  
    $stateProvider  
    .state('addUser', {  
    url: "/addUser",  
    views: {  
       'view': {  
        templateUrl: 'views/addUser.html',  
        controller: 'addUserCtr'  
       }  
    }  
   });  
});  
增加用戶信息的界面addUser.html:

用戶名:

姓 名:

密 碼:

手 機:

郵 箱:

  


增加用戶信息的angularjs控制層:
angular.module('merchantApp')  
.controller('addUserCtr', ['$scope','$http', function($scope,$http){  
    $scope.addUser=function(user){
     //向後台提交數據
$http.post("./addUser",user,{headers:'Content-Type:application/json'}).success(function(){ 
	  
      });
    }   
}])  
相關的css:
body{
	margin:0;
}

.button1{
	font-size:28px;
}
#addUser input{
	font-size:24px;
}
#addUser{
	border:2px solid;
    border-radius:0.5em;
    width:35%;
    height:330px;
    float:left;
    margin-left:400px;
    margin-top:100px;
    padding:30px;
    background-image:url("../images/111.jpg");
    background-size:cover;
    font-size:26px;
}
#addUser img{
	width:100%;
	height:100%;
}
#headBack{
	width:100%;
	height:80px;
	background-color:#E0EEF0;
	position:relative;
}
#headDiv{
	width:75%;
	height:5px;
	background:#CBE1E4;
	float:right;
	position:absolute;
	right:0;
	bottom:0;
}

#navUl{
	/*position:relative;*/
	position:absolute;
	float:right;
	top:0;
	right:0;
	margin:0;
    box-sizing:border-box;
    /*background-color:red;*/
    width:75%;
    height:75px;
}

#navUl li{	
	list-style-type: none; 
	/*position:absolute;*/
	font-size:36px;
    display: inline;  
    /**top:20;*/
    margin-top:20px;
    left:0;
    height:auto;
    text-color:#2F2E2E;
    /*background-color:#EAE3EA;*/
    text-align:center;
     /**padding:5px;
   margin-top:3px;*/
}

a:link{
	text-decoration:none;
	color:black;
}

a:visited{
	color:blue;
}

a:hover{
	color:red;
}

a:active{
	color:orange;
}
浏覽器訪問界面如下:
\

點擊注冊以後,數據庫信息如下:

\

至此,基礎搭建成功。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved