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;
}


浏览器访问界面如下:



点击注册以后,数据库信息如下:



至此,基础搭建成功。
涂宗勋 CSDN认证博客专家 web安全 系统安全 安全架构
【若想不迷路,记得点关注,动动小手指,点点全是福】

6年java工作经验,现居湖北武汉,有过支付、OA、CA、OAUTH2等工作经验,现从事车联网行业。
爱好分享,个人博客blog.tzxcode.cn,微信tuzongxun,qq1160569243,欢迎来撩。
©️2020 CSDN 皮肤主题: 成长之路 设计师: Amelia_0503 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值