1. 程式人生 > >spring+springMVC+mybatis的框架專案基礎環境搭建

spring+springMVC+mybatis的框架專案基礎環境搭建


上一個專案在後臺用到spring+springMVC+mybatis的框架,先新專案初步需求也已經下來,不出意外的話,應該也是用這個框架組合。


雖然在之前activiti相關的學習中所用到的框架也是這個,但是當時重點在於實現activiti的功能,因此在環境搭建上也只是以能用為前提,與真實專案中所用的還是差了不少。


因此為了給接下來的專案做準備,今天便抽空練習了一下這個框架組合的搭建。雖然之前的框架都不是我來搭,接下來這個可能也不是讓我搭,但記錄下來說不定以後能用上,也或者對其他人有用。


那麼進入正題:
一、搭建目標:
實現標準的後臺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程式碼:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>frameTest</groupId>
  <artifactId>frameTest</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>frameTest Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <build>
		<plugins>
		    <!-- 以下配置可以保證每次強制更新時jre版本不會變化,那我的eclipse4.4.1,maven3.2.5為例,如果不設定這個,每次強制更新時jre就會變回1.5 -->
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
					<encoding>UTF-8</encoding>
					<compilerArguments>
                        <verbose />
                        <bootclasspath>${java.home}\lib\rt.jar</bootclasspath>
                    </compilerArguments>
				</configuration>
			</plugin>
		</plugins>
		<!-- 加上這個可以保證maven打包是把這些資原始檔都打到war包中 -->
		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.xml</include>
				</includes>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*.*</include>
				</includes>
			</resource>
		</resources>
		<!-- maven打包後的專案名 -->
		<finalName>frameTest</finalName>
	</build>
    <properties>
		<spring-version>4.0.3.RELEASE</spring-version>
	</properties>
	<!-- 專案基礎依賴包配置 -->
    <dependencies>
		<!-- spring以及springMVC相關依賴 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring-version}</version>
		</dependency>


		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.amqp</groupId>
			<artifactId>spring-amqp</artifactId>
			<version>1.2.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.7.1</version>
		</dependency>


		<!-- mybatis框架相關依賴包 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.2.7</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.2</version>
		</dependency>


		<!-- mysql資料庫-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.34</version>
		</dependency>
		<!-- junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
	  <!-- json資料相關依賴 -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.7</version>
		</dependency>
		
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.1.26</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-asl</artifactId>
			<version>1.9.7</version>
		</dependency>
		
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>3.0-alpha-1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.geronimo.specs</groupId>
			<artifactId>geronimo-servlet_3.0_spec</artifactId>
			<version>1.0</version>
			<scope>test</scope>
		</dependency>
		
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2</version>
		</dependency>
		<!-- 日誌相關依賴 -->
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>1.0.9</version>
		</dependency>
		
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		
		<dependency>
			<groupId>com.github.snakerflow</groupId>
			<artifactId>snaker-core</artifactId>
			<version>2.5.1</version>
		</dependency>


		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.3.1</version>
		</dependency>
	
	</dependencies>
</project>


五、web專案基礎配置檔案web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>appversion</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml</param-value>
  </context-param>
  
  <filter>
    <description>字符集過濾器</description>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <description>字符集編碼</description>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <listener>
    <description>spring監聽器</description>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <session-config>
    <session-timeout>15</session-timeout>
  </session-config>
</web-app>


六、spring基礎篇日誌檔案spring.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:task="http://www.springframework.org/schema/task"
	xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context" 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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">


	<!-- 引入屬性檔案 -->
	<context:property-placeholder location="classpath:config.properties" />
    
	<!--spring mybatis 資料庫連線配置 -->
	<import resource="spring-MybatisConfig.xml" />


	<!-- 自動掃描(自動注入) -->
	<context:component-scan base-package="merService.merServiceImp" />


	<!-- 採用註釋的方式配置bean -->
	<context:annotation-config />
	<!-- 該 BeanPostProcessor 將自動起作用,對標註 @Autowired 的 Bean 進行自動注入 -->
	<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
	
	<!-- 開啟事務註解驅動 -->
	<tx:annotation-driven />
	
</beans>


七、mybatis基礎配置檔案spring-MybatisConfig.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">


	<!-- 配置druid資料庫連線池-->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
		<property name="url" value="${jdbc.url}" />  
		<property name="username" value="${jdbc.username}" />  
		<property name="password" value="${jdbc.password}" />  
		<property name="maxActive" value="${druid.maxPoolSize}" />   
		<property name="initialSize" value="${druid.initialPoolSize}" />  
		<property name="maxWait" value="${druid.maxWait}" />  
		<property name="minIdle" value="${druid.minPoolSize}" />  
		<property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}" />  
		<property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}" />  
		<property name="validationQuery" value="${druid.validationQuery}" />  
		<property name="testWhileIdle" value="${druid.testWhileIdle}" />  
		<property name="testOnBorrow" value="${druid.testOnBorrow}" />  
		<property name="testOnReturn" value="${druid.testOnReturn}" />  
		<property name="poolPreparedStatements" value="${druid.poolPreparedStatements}" />  
		<!-- <property name="maxPoolPreparedStatementPerConnectionSize" value="${druid.maxPoolPreparedStatementPerConnectionSize}" /> -->  
	</bean>
	 
	<!-- 配置mybitasSqlSessionFactoryBean -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:MybatisConf.xml"></property>
		<property name="mapperLocations"
			value="classpath*:merDao/mapper/*Mapper.xml"></property>
	</bean>
	
	<!-- 配置SqlSessionTemplate -->
	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
	    <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
	</bean>
	
		<!-- 自動掃描,注入×Mapper實現類 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  		<property name="basePackage" value="merDao" />
	</bean>
</beans>


七、mybatis基礎配置檔案MybatisConf.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		<!-- 這個配置使全域性的對映器啟用或禁用快取 -->
		<setting name="cacheEnabled" value="true" />
		<!-- 允許 JDBC 支援生成的鍵。需要適合的驅動。如果設定為 true 則這個設定強制生成的鍵被使用,儘管一些驅動拒絕相容但仍然有效(比如 Derby) -->
		<setting name="useGeneratedKeys" value="true" />
		<!-- 配置預設的執行器。SIMPLE 執行器沒有什麼特別之處。REUSE 執行器重用預處理語句。BATCH 執行器重用語句和批量更新  -->
		<setting name="defaultExecutorType" value="REUSE" />
		<!-- 全域性啟用或禁用延遲載入。當禁用時,所有關聯物件都會即時載入。 -->
		<setting name="lazyLoadingEnabled" value="true"/>
		<!-- 設定超時時間,它決定驅動等待一個數據庫響應的時間。  -->
		<setting name="defaultStatementTimeout" value="55000"/> 
		 <setting name="logPrefix" value="dao."/>  
	</settings>
	
	<!-- 別名配置,查詢該包內的所有bean,bean例項名為類名 -->
	<typeAliases>
		<package name="merModel"/>
	</typeAliases>
	
</configuration>


八、springMVC基礎配置檔案spring-mvc.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 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.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-4.0.xsd 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
	
	<context:component-scan base-package="merController" />	
	<mvc:default-servlet-handler />
	<mvc:annotation-driven />
    
	<!-- 避免IE執行AJAX時,返回JSON出現下載檔案 -->
	<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>text/html;charset=UTF-8</value>
			</list>
		</property>
	</bean>
<bean id = "stringHttpMessageConverter" 
class = "org.springframework.http.converter.StringHttpMessageConverter"/>
	<!-- 啟動Spring MVC的註解功能,完成請求和註解POJO的對映 -->
	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" /><!-- json轉換器 -->
				<ref bean="stringHttpMessageConverter"/>
			</list>
		</property>
	</bean>
	
</beans>


九、日誌列印相關配置logback.xml:
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="30 seconds">
    <!--定義日誌檔案的儲存地址 勿在 LogBack 的配置中使用相對路徑-->  
    <property name="LOG_HOME" value="logs" />  
	<!-- appender -->
	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
		<layout class="ch.qos.logback.classic.PatternLayout">
			<pattern>%d{yyyy-MM-dd HH:mm:ss:SSS}[%p]: %m%n</pattern>
		</layout>
	</appender>
	
	<!-- 按照每天生成日誌檔案 -->   
    <appender name="FILE"  class="ch.qos.logback.core.rolling.RollingFileAppender">   
<!--     	<File>processcontrol.log</File> -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<!--日誌檔案輸出的檔名 -->
			<FileNamePattern>${LOG_HOME}//merchant.%d{yyyy-MM-dd}.log</FileNamePattern>
			<!--日誌檔案保留天數 -->
			<MaxHistory>30</MaxHistory>
		</rollingPolicy>
		
		<layout class="ch.qos.logback.classic.PatternLayout">
			<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} -%msg%n</Pattern>
		</layout>
    </appender> 
    
	<!-- log 通過 LoggerFactory.getLogger(name)取得 -->
	<logger name="myLog" additivity="true" level="info">
		<appender-ref ref="stdout" />
	</logger>
	 <!-- update:liaoshijun 2015-04-24 -->
	 <logger name="frameTest" level="INFO"/>
	  <logger name="org.apache.ibatis" level="INFO"/>
	  <logger name="org.apache.mybatis" level="INFO"/>
	  <logger name="com.ibatis" level="DEBUG" />  
<logger name="com.ibatis.common.jdbc.SimpleDataSource" level="DEBUG" />  
<logger name="com.ibatis.common.jdbc.ScriptRunner" level="DEBUG" />  
<logger name="dao" level="DEBUG">  
    <!--daoFILE為實際定義的appender-->  
    <appender-ref ref="daoFILE" />  
</logger> 
	<!-- root 預設日誌配置 -->
	<root level="info">
		<appender-ref ref="STDOUT" />
		<appender-ref ref="FILE" />
	</root>
</configuration>
十、屬性檔案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:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="merDao.UserDao">
	<!-- 資料庫對映配置 -->
	<resultMap type="UserModel" id="userResult">
		<id property="id" column="id" />
		<result property="account" column="account" />
		<result property="userName" column="userName" />
		<result property="password" column="password" />
		<result property="mobile" column="mobile" />
		<result property="email" column="email" />	
	</resultMap>


	<sql id="userColumns">id,account,userName,password,mobile,email
	</sql>
	
	<!-- 新增使用者 -->
	<insert id="save" parameterType="UserModel">
		insert into user(<include refid="userColumns" />)
	values(#{id},#{account},#{userName},#{password},#{mobile},#{email})
	</insert>
	
	 查詢使用者-->
	<select id="findAll"  resultMap="userResult">
		SELECT u.* FROM user u 
	</select>
	 
</mapper>


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檔案:
<!doctype html>
<html ng-app="merchantApp">
<head>
<meta charset="utf-8">
<title>交易業務商戶服務平臺</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="./css/addUser.css">
<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>
</head>
<body>
    <div id="headBack">
        <img id="rdiv" src="./images/555.jpg" style="width:25%;height:98%;"/>
        <ul id="navUl">
             <li ><a href="#">首頁</a></li>
             <li >|</li>
             <li ><a href="script:;">申告管理</a></li>
             <li >|</li>
             <li ><a href="#login">自助服務</a></li>
             <li >|</li>
             <li ><a href="#regist">意見管理</a></li>
             <li >|</li>
             <li ><a href="#regist">知識庫</a></li>
        </ul>
        <div id="headDiv">
            
        </div>
    </div>
    
	<div ui-view="view" style="height: 100%;"></div>
</body>
</html>


前臺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:
<center>
<div id="addUser">
   使用者名稱:<input type="text" ng-model="user.account"></input></br></br>
   姓     名:<input type="text" ng-model="user.userName"></input></br></br>
   密     碼:<input type="password" ng-model="user.password"></input></br></br>
   手     機:<input type="text" ng-model="user.mobile"></input></br></br>
   郵     箱:<input type="text" ng-model="user.email"></input></br></br>
   <input class="button1" type="button" ng-click="addUser(user);" value="注   冊"></input>  
   <input class="button1" type="button" ng-click="toLogin();" value="返  回">
</div>
</center>


增加使用者資訊的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;
}


瀏覽器訪問介面如下:


點選註冊以後,資料庫資訊如下:



至此,基礎搭建成功。

相關推薦

spring+springMVC+mybatis框架專案基礎環境搭建

上一個專案在後臺用到spring+springMVC+mybatis的框架,先新專案初步需求也已經下來,不出意外的話,應該也是用這個框架組合。雖然在之前activiti相關的學習中所用到的框架也是這個,但是當時重點在於實現activiti的功能,因此在環境搭建上也只是以能用為

利用Maven搭建Spring+SpringMVC+Mybatis框架專案(二)

上次寫到將Spring和Mybatis整合到了一起,這次便將SpringMVC整合進去,SpringMVC只負責controller和頁面之間的跳轉,也就是隻負責和使用者互動 3.2 整合SpringMVC框架 3.2.1 建立spring-mvc.xml

SSM(Spring+SpringMVC+Mybatis)框架超詳細搭建指南(利用Maven構建專案)

其實這是我實習生涯開始後的第一個任務,但是當時太忙了一直沒有時間記錄,就按照教程走了。剛好現在實習結束了有些時間,把整個搭建的過程還有一些坑記錄下來還是很有必要的。 DEMO https://github.com/mgsky1/aboutSpring/tree/ma

使用idea搭建Maven+SSM(Spring+SpringMVC+Mybatis)框架(一、使用Maven創建新工程)

post eight 9.png 圖片 tis 本地包 end pen nbsp 一、新建Maven項目 1、如圖創建簡單java web application。 2、如圖填寫組織唯一標識和項目唯一標識 3、如圖照做 4、點擊finish即可完成項目創建,如圖為創建

Dubbo+SpringBoot+Spring+SpringMVC+MyBatis框架搭建的Demo中遇到的錯誤

遇到的報錯問題: com.alibaba.dubbo.remoting.RemotingException: message can not send, because channel is closed . url:dubbo://192.168.43.177:20880/com.test.s

Spring-SpringMVC-Mybatis框架配置檔案內容(基礎版)

    最近開始學SSM框架了,在學習搭建執行環境和配置檔案時,花了好久,有很多次都出了異常,最後終於跑通了一個簡單的登入功能.現將各種XML檔案記錄下來以便日後檢視.一.Web.XML<?xml version="1.0" encoding="UTF-8"?>

簡單的SSM(Spring+SpringMVC+Mybatis專案搭建

SSM(Spring+SpringMVC+MyBatis)框架集由Spring、SpringMVC、MyBatis三個開源框架整合而成,常作為資料來源較簡單的web專案的框架。 spring是一個輕量級的控制反轉(IoC)和麵向切面(AOP)的容器框架。 SpringMV

Maven搭建Spring+SpringMVC+Mybatis+Shiro專案詳解

最近新換了一臺機子,這次主要框架使用spring+SpringMVC+Mybatis+Shiro。專案持久層使用Mybatis3.3.0,控制層使用SpringMVC4.3.6,使用Spring4.3.6管理控制器,使用Shiro1.2.4許可權管理器,資料庫連線池使

Spring+SpringMVC+MyBatis+easyUI整合基礎篇(一)專案簡述及技術選型介紹

萌芽階段 很久之前就開始打算整理一下自己的技術部落格了,由於各種原因(藉口總是可以找到的),實在抽不出時間所以計劃一直處於擱置狀態,一直只是心底的一顆小萌芽,日復一日的悠悠歲月如同手中緊抓的沙子,無聲無息的流失,不過這顆小生命也在我渴望與期待的澆灌下不斷的長大。

SSM:spring+springmvc+mybatis框架中的XML配置文件功能詳細解釋

con initial -m and 整理 .get 尺寸 internal 頁面 SSM:spring+springmvc+mybatis框架中的XML配置文件功能詳細解釋 2016-04-14 23:40 13030人閱讀 評論(2) 收藏 舉報

spring+springMvc+mybatis框架簡單實例

username span tty 添加 localhost name cee rop lns web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://

SSM:spring+springmvc+mybatis框架中的XML配置檔案功能詳細解釋

SSM:spring+springmvc+mybatis框架中的XML配置檔案功能詳細解釋 這幾天一直在整合SSM框架,雖然網上有很多已經整合好的,但是對於裡面的配置檔案並沒有進行過多的說明,很多人知其然不知其所以然,經過幾天的搜尋和整理,今天總算對其中的XML配置檔案有了一定的瞭解,所以拿

新手入門java中Spring+SpringMVC+MyBatis框架整合詳細步驟

Springmvc+spring+mybatis環境搭建 注意:這裡我是用Spring的famerwork的參考文件聯合搭建 搭建spring環境 Spring的基本包+SpringMVC基本+MyBatis基本+mybatis-spring整合,增加tx包,aop包,c

SSM(Spring + Springmvc + Mybatis)框架面試題

事務管理器 map 得到 反轉 存取 _id conf last markdown JAVA SSM框架基礎面試題https://blog.csdn.net/qq_39031310/article/details/83050192 SSM(

ssm(spring+springMVC+Mybatis)框架整合Mongodb

1、開發環境 JDK:1.6 ssm框架關聯jar包: aopalliance.jar aspectjrt.jar aspectjweaver.jar commons-beanutils-1.9.2.jar commons-codec-1.9.jar commons-col

Spring+SpringMVC+MyBatis整合配置檔案的搭建

SSM專案的環境搭建: 一、專案的目錄結構如下: 二、匯入的jar包:WEB-INF/lib下 三、resources下的幾個配置檔案+WEB-INF下的web.xml檔案需要自己配置: wei.xml: <?xml version="1.0" en

Spring+SpringMVC+MyBatis+easyUI整合基礎篇(五)講一下maven

github地址,點這裡。專案效展示,點這裡。賬號:admin 密碼:123456 下一篇文章開始,所有的專案原始碼都是與maven整合後的程式碼了,所以這一篇講一講maven。1、簡單介紹 我們看一下github上一些開源專案的目錄結構,下圖中有mybatis、nett

SSM(Spring+SpringMVC+Mybatis)框架整合Demo+詳細講解

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-ins

java web,從零開始,一步一步配置ssm(Spring+SpringMVC+MyBatis)框架

1、安裝JDK: 安裝之後要配置環境變數,在系統變數裡: 新建變數名JAVA_HOME,變數值C:\Program Files\Java\jdk1.8.0_77; 新建變數名CLASSPATH,變數值.;%JAVA_HOME%\lib\tools.jar Path後面新增%

Spring-SpringMVC-Mybatis框架下的 省市區 三級聯動

    初學者學習SSM框架,若有問題,請留言.    首先看一下專案結構.        配置檔案Web.xml,  spring-dao.xml,   springmvc-servlet.xml,  configuration.properties 等就是常規沒有特殊的,