作者QQ:1095737364    QQ群:123300273     欢迎加入!

 建立好maven多模块项目后,开始使用ssm传统的框架:http://www.cnblogs.com/yysbolg/p/6898453.html

1.打开总工程下的pom.xml文件:添加如下代码:

<!--全局的所有版本号定义-->
<properties>
<!-- 日志管理 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<logback.version>1.1.7</logback.version>
<slf4j.version>1.7.21</slf4j.version>
<janino.version>2.7.8</janino.version>
<!-- 数据库 -->
<db.mysql>5.1.30</db.mysql>
<db.pool.druid>1.0.9</db.pool.druid>
<!-- 主要依赖库的版本定义 -->
<spring.version>4.1.3.RELEASE</spring.version>
<aspectj.version>1.8.4</aspectj.version>
<mybatis.version>3.2.7</mybatis.version>
<mybatis-spring.version>1.2.2</mybatis-spring.version>
<commons-lang3.version>3.3.2</commons-lang3.version>
<commons-io.version>2.4</commons-io.version>
</properties>
<dependencies>
<!-- 日志文件管理包 -->
<!-- logback+slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-access</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<!-- 日志文件管理包-提高性能log输出性能 -->
<!-- janino -->
<dependency>
<groupId>org.codehaus.janino</groupId>
<artifactId>commons-compiler</artifactId>
<version>${janino.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.janino</groupId>
<artifactId>janino</artifactId>
<version>${janino.version}</version>
</dependency>
<!-- spring核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</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-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<!--常用工具包-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!--json解析:spring-mvc.xml中配置避免IE执行AJAX时,返回JSON出现下载文件-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.4</version>
</dependency>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<!-- 导入Mysql数据库链接jar包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${db.mysql}</version>
</dependency>
<!--阿里巴巴druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${db.pool.druid}</version>
</dependency>
</dependencies>

2.在http的resources文件夹下新建application.properties:

#********Mybatis  分库(这里做测试模拟)**************
jdbc.driver = com.mysql.jdbc.Driver jdbc.master.url = jdbc:mysql://localhost:3306/longebo?useUnicode=true&amp;characterEncoding=UTF-8&amp;generateSimpleParameterMetadata=true
jdbc.master.username = root
jdbc.master.password = 1234 jdbc.slave.url = jdbc:mysql://localhost:3306/longebo?useUnicode=true&amp;characterEncoding=UTF-8&amp;generateSimpleParameterMetadata=true
jdbc.slave.username = root
jdbc.slave.password = 1234

3.在http的resources文件夹下新建applicationContext.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" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- spring管理接口和事物,只扫描 -->
<context:component-scan base-package="com.longebo.common.*,com.longebo.http.server.*">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:application.properties" />
</bean>
<aop:aspectj-autoproxy/> <import resource="spring-datasource-master.xml"/>
<import resource="spring-datasource-slave.xml"/>
</beans>

4.在http的resources文件夹下新建spring-datasource-master.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" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
"> <!--可视化访问地址 http://localhost:8080/druid-->
<bean id="dataSourceMaster" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc.master.url}" />
<property name="username" value="${jdbc.master.username}" />
<property name="password" value="${jdbc.master.password}" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="1" />
<property name="minIdle" value="2" />
<property name="maxActive" value="20" /> <!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" /> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat" />
</bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory1" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSourceMaster" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:mybatis/*/*Mapper.xml"></property>
<!--自动扫描定义typeAliases类型-->
<property name="typeAliasesPackage" value="com.longebo.common.*"/>
</bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.longebo.common.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory1"></property>
</bean> <bean id="sqlSessionMaster" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
<constructor-arg index="0" ref="sqlSessionFactory1"/>
</bean> <aop:config>
<aop:pointcut id="appService"
expression="execution(* com.longebo.common.service..*Service*.*(..))"/>
<aop:advisor advice-ref="txAdvice1" pointcut-ref="appService"/>
</aop:config>
<tx:advice id="txAdvice1" transaction-manager="transactionManager1">
<tx:attributes>
<tx:method name="select*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="save*" read-only="false"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- 注解式事物 -->
<tx:annotation-driven transaction-manager="transactionManager1" />
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager1"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSourceMaster" />
</bean> </beans>

5.在http的resources文件夹下新建spring-datasource-slave.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" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
"> <bean id="dataSourceSlave" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc.slave.url}" />
<property name="username" value="${jdbc.slave.username}" />
<property name="password" value="${jdbc.slave.password}" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="1" />
<property name="minIdle" value="1" />
<property name="maxActive" value="20" /> <!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" /> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat" />
</bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory2" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSourceSlave" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:mybatis/*/*Mapper.xml"></property>
<!--自动扫描定义typeAliases类型-->
<property name="typeAliasesPackage" value="com.longebo.common.*"/>
</bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.longebo.common.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory2"></property>
</bean> <bean id="sqlSessionSlave" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
<constructor-arg index="0" ref="sqlSessionFactory2"/>
</bean> <aop:config>
<aop:pointcut id="appService"
expression="execution(* com.longebo.common.service..*Service*.*(..))"/>
<aop:advisor advice-ref="txAdvice2" pointcut-ref="appService"/>
</aop:config> <tx:advice id="txAdvice2" transaction-manager="transactionManager2">
<tx:attributes>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice> <!-- 注解式事物 -->
<tx:annotation-driven transaction-manager="transactionManager2" />
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager2"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSourceSlave" />
</bean> </beans>

6.打开http模块下的pom.xml文件:添加如下代码:

 <!--spring mvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 导入java ee jar基础包 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<!-- 引入标签库 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- 自定义标签库 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>

7.在WEB-INF下新建:spring-mvc.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" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="com.longebo.http.*" >
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
<!--
<mvc:annotation-driven /> 是一种简写形式,完全可以手动配置替代这种简写形式,简写形式可以让初学都快速应用默认配置方案。
<mvc:annotation-driven /> 会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,
是spring MVC为@Controllers分发请求所必须的。 并提供了:数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,
@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)。后面,我们处理响应ajax请求时,就使用到了对json的支持。
后面,对action写JUnit单元测试时,要从spring IOC容器中取DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter
两个bean,来完成测试,取的时候要知道是<mvc:annotation-driven />这一句注册的这两个bean。
-->
<mvc:annotation-driven />
<!-- 避免IE执行AJAX时,返回JSON出现下载文件-->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
</list>
</property>
</bean> <!-- 定义跳转的文件的前后缀 ,视图模式配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean> <!-- 静态资源配置 --> <mvc:resources mapping="/static/**" location="static/"/> <!-- 拦截器配置 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.longebo.http.interceptor.HttpInterceptor">
<!--是否开启longebo头部信息认证-->
<property name="islongeboAccess" value="true"/>
<property name="allowUrls">
<list>
<!-- 如果请求中包含以下路径,则不进行拦截 -->
<value>/</value>
<value>/static</value>
</list>
</property>
</bean>
</mvc:interceptor>
</mvc:interceptors>
</beans>

8.在web.xml中添加如下代码:

 <!-- Spring和mybatis的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param> <!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<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> <!-- 防止Spring内存溢出监听器,放在所有监听的最上面 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring MVC servlet -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet>
<servlet-name>DruidStatView</servlet-name>
<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DruidStatView</servlet-name>
<url-pattern>/druid/*</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>

9.建立文件夹系统:

10.建立测试用例(1):http->interceptor  新建HttpInterceptor.java

package com.longebo.http.interceptor;

import com.mysql.jdbc.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class HttpInterceptor extends HandlerInterceptorAdapter {
public final static Logger logger= LoggerFactory.getLogger(HttpInterceptor.class); //是否只能longebo用户访问:此处是的默认值为false,就是所有请求都可访问,如果spring-mvc.xml的过滤器配置参数为true,则此处被修改为true
private boolean islongeboAccess=false;
public void setIslongeboAccess(boolean islongeboAccess) { this.islongeboAccess = islongeboAccess; }
private String[] allowUrls;
public void setAllowUrls(String[] allowUrls) {
this.allowUrls = allowUrls;
}
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
//得到请求头Header中的参数User-Agent
String userAgent=request.getHeader("User-Agent");
//得到请求地址的相对路径
String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");
//如果请求地址为"/",则不进行任何处理,可能会直接到下一个过滤器,ruturn 可以不要;
if("/".equals(requestUrl)){
System.out.println("测试 '/' 访问......");
return true;
}
if(!islongeboAccess){
//处理longebo用户的访问和非此用户的访问,比如做了一个移动端的APP, 分享后的访问不一定是App里面的请求,此时要做一些处理,ruturn 可以不要;
return true;
}
if(!StringUtils.isNullOrEmpty(userAgent)){
//对请求头进行处理,ruturn 可以不要;
return true;
}
//如果请求中包含以下路径,则不进行拦截
if(null != allowUrls && allowUrls.length>=1) {
for(String url : allowUrls) {
if(!"/".equals(url) && requestUrl.contains(url)) {
return true;
}
}
}
logger.error("非longebo客户端访问",userAgent);
response.getWriter().write("Not Longebo");
return false;
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}

11.建立测试用例(2):http->resources->mybatis->system新建UserMapper.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="com.longebo.common.dao.UserDao"> <resultMap id="result" type="com.longebo.common.entity.User">
<id property="userId" column="user_id"/>
<result property="userName" column="user_name"/>
<result property="passWord" column="password"/>
</resultMap> <insert id="saveUser" parameterType="com.longebo.common.entity.User" useGeneratedKeys="true" keyProperty="userId">
INSERT INTO user (user_name
<if test="passWord!=null and passWord!=''">
,password
</if>
)
VALUES (#{userName}
<if test="passWord!=null and passWord!=''">
,#{passWord}
</if>
)
</insert> <select id="findUserByUserName" parameterType="java.lang.String" resultMap="result">
SELECT * FROM user WHERE user_name=#{userName}
</select> </mapper>

12.建立测试用例(3):http->controller新建UserController.java

package com.longebo.http.controller;

import com.longebo.common.entity.User;
import com.longebo.common.service.UserSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView; @Controller
public class UserController { @Autowired
private UserSerivce userSerivce;
/**
* 显示index.jsp页面
* @return
*/
@RequestMapping(value = "/", method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView index() {
return new ModelAndView("index");
} /**
* 登陆
* @return
*/
@RequestMapping(value = "/login", method = {RequestMethod.POST})
@ResponseBody
public String login(User user) {
User user1= userSerivce.findUserByUserName(user.getUserName());
if(user1!=null&&user1.getPassWord().equals(user.getPassWord())){
return "success!";
}
return "fail!";
}
/**
* 注册
* @return
*/
@RequestMapping(value = "/register", method = {RequestMethod.POST})
@ResponseBody
public String register(User user) {
try {
userSerivce.saveUser(user);
return "success!";
} catch (Exception e) {
return "fail!";
}
}
}

13.建立测试用例(4):common->service新建UserSerivce.java

package com.longebo.common.service;

import com.longebo.common.entity.User;

public interface UserSerivce {
/**
* 保存用户信息,自动设置保存对象的userid
* @param user
* @return
* @throws Exception
*/
void saveUser(User user) throws Exception;
/**
* 根据用户id查询用户信息
* @param name
* @return
*/
User findUserByUserName(String name);
}

14.建立测试用例(5):common->service->impl新建UserSerivceImpl.java

package com.longebo.common.service.impl;

import com.longebo.common.dao.UserDao;
import com.longebo.common.entity.User;
import com.longebo.common.service.UserSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserSerivceImpl implements UserSerivce {
@Autowired
private UserDao userDao; @Transactional
public void saveUser(User user) throws Exception {
userDao.save("saveUser",user);
}
public User findUserByUserName(String name) {
return userDao.selectOne("findUserByUserName",name);
}
}

15.建立测试用例(6):common->entity新建User.java

package com.longebo.common.entity;

import com.longebo.common.basics.AbstractObject;

public class User extends AbstractObject {

    /** 用户Id */
private Integer userId;
/** 用户昵称 */
private String userName="";
/** 密码 */
private String passWord=""; public Integer getUserId() {
return userId;
} public void setUserId(Integer userId) {
this.userId = userId;
} 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;
} @Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
'}';
}
}

16.建立测试用例(7):common->dao新建BasicDao.java

package com.longebo.common.dao;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Service; import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List; @Service
public abstract class BasicDao<T extends Serializable>{
protected SqlSessionTemplate writeMapper;
protected SqlSessionTemplate readMapper; @Resource(name = "sqlSessionMaster")
private void setWriteMapper(SqlSessionTemplate sqlSession) {
this.writeMapper = sqlSession;
}
@Resource(name = "sqlSessionSlave")
private void setReadMapper(SqlSessionTemplate sqlSession) {
this.readMapper = sqlSession;
} public T selectOne(String statement,T t){
return readMapper.selectOne(statement,t);
} public <B,V> V selectOne(String statement,B b){
return readMapper.selectOne(statement,b);
} public List<T> selectList(String statement){
return readMapper.selectList(statement);
} public List<T> selectList(String statement,String t){
return readMapper.selectList(statement,t);
} public <B,V> List<V> selectList(String statement,B b){
return readMapper.selectList(statement,b);
} public int save(String statement,T t) throws Exception{
return writeMapper.insert(statement , t);
} public <B> int save(String statement,B b) throws Exception{
return writeMapper.insert(statement , b);
} public int update(String statement,T t) throws Exception{
return writeMapper.update(statement , t);
} public <B> int update(String statement,B b) throws Exception{
return writeMapper.update(statement , b);
} }

17.建立测试用例(8):common->dao新建UserDao.java

package com.longebo.common.dao;
import com.longebo.common.entity.User;
import org.springframework.stereotype.Service;
@Service
public class UserDao extends BasicDao<User> {
}

18.建立测试用例(9):common->basics新建AbstractObject.java

package com.longebo.common.basics;

import java.io.Serializable;

/**
* 抽象类,替代Object成为序列化对象
*/
public abstract class AbstractObject implements Serializable{
}

19.建立测试用例(10):WEB-INF->view新建index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>index</title>
</head>
<body>
<h1>login</h1>
<form action="/register" method="post">
<input type="text" name="userName" value="中国">
<input type="text" name="passWord" value="123">
<button type="submit">register</button>
</form>
<form action="/login" method="post">
<input type="text" name="userName" value="中国">
<input type="text" name="passWord" value="123">
<button type="submit">login</button>
</form>
</body>
</html>

20.运行项目

3.配置Spring+SpringMvc+Mybatis(分库or读写分离)--Intellij IDAE 2016.3.5的更多相关文章

  1. 2.配置Spring+SpringMvc+Mybatis(分库or读写分离)--Intellij IDAE 2016.3.5

    建立好maven多模块项目后,开始使用ssm传统的框架: 1.打开总工程下的pom.xml文件:添加如下代码: <!--全局的所有版本号定义--> <properties> & ...

  2. Maven配置Spring+SpringMVC+MyBatis(3.2.2)Pom 以及 IntelliJ IDEA 怎样打开依赖视图

    Maven配置Spring+SpringMVC+MyBatis(3.2.2)Pom 配置原则: 利用依赖,将所需的jar包加载到project中. 先依赖主要jar包 Spring + Spring ...

  3. spring集成mybatis实现mysql读写分离

    前言 在网站的用户达到一定规模后,数据库因为负载压力过高而成为网站的瓶颈.幸运的是目前大部分的主流数据库都提供主从热备功能,通过配置两台数据库主从关系,可以将一台数据库的数据更新同步到另一台服务器上. ...

  4. SSM框架的配置Spring+Springmvc +Mybatis

    ssm框架是由spring mvc +spring+mybatis组成 快速阅读 通过spring的配置文件spring.xml,在servlet中指定spring mvc的配置文件spring-mv ...

  5. spring结合mybatis实现数据库读写分离

    随着系统用户访问量的不断增加,数据库的频繁访问将成为我们系统的一大瓶颈之一.由于项目前期用户量不大,我们实现单一的数据库就能完成.但是后期单一的数据库根本无法支撑庞大的项目去访问数据库,那么如何解决这 ...

  6. Spring Boot + MyBatis + MySQL 实现读写分离

    读写分离要做的事情就是对于一条SQL该选择哪个数据库去执行,至于谁来做选择数据库这件事儿,无非两个,要么中间件帮我们做,要么程序自己做. 读写分离有两种实现方式: 第一种是依靠中间件(比如:MyCat ...

  7. 基于Spring+SpringMVC+Mybatis的Web系统搭建

    系统搭建的配置大同小异,本文在前人的基础上做了些许的改动,重写数据库,增加依据权限的动态菜单的实现,也增加了后台返回json格式数据的配置,详细参见完整源码. 主要的后端架构:Spring+Sprin ...

  8. SSM 框架-05-详细整合教程(Eclipse版)(Spring+SpringMVC+MyBatis)

    SSM 框架-05-详细整合教程(Eclipse版)(Spring+SpringMVC+MyBatis) 如果你使用的是 Intellij IDEA,请查看: SSM的配置流程详细的写了出来,方便很少 ...

  9. Spring+springmvc+Mybatis整合案例 xml配置版(myeclipse)详细版

    Spring+springmvc+Mybatis整合案例 Version:xml版(myeclipse) 文档结构图: 从底层开始做起: 01.配置web.xml文件 <?xml version ...

随机推荐

  1. hadoop集群搭建(hdfs)

    (搭建hadoop集群的前提是服务器已成功安装jdk以及服务器之间已设置免密码登录,服务器之间的免密码登录可参考<linux服务器间ssh免密码登录>) 1.下载hadoop安装包 wge ...

  2. tkinter如何设置界面消失 当制作一个登陆界面时,登陆成功之后,如何让登陆界面本身消失

    tkinter如何设置界面消失 当制作一个登陆界面时,登陆成功之后,如何让登陆界面本身消失 if querySQL.checkAll():#用户名和密码都输入正确 self.root.withdraw ...

  3. 提取PPT中的原始图片

    写Word的不如做Excel 的,做Excel不如做PPT的,写代码的不如做PPT. 为了在电子邮件中上传PPT,其中的图片大都经过压缩,以便缩小PPT的体积.那么如何将PPT中的图片,还原成没有经过 ...

  4. 09-04 java 接口

    接口的引出 继续回到我们的猫狗案例,我们想想狗一般就是看门,猫一般就是作为宠物了,对不.但是,现在有很多的驯养员或者是驯兽师,可以训练出:猫钻火圈,狗跳高,狗做计算等. 而这些额外的动作,并不是所有猫 ...

  5. 解释一下核主成分分析(Kernel Principal Component Analysis, KPCA)的公式推导过程(转载)

    KPCA,中文名称”核主成分分析“,是对PCA算法的非线性扩展,言外之意,PCA是线性的,其对于非线性数据往往显得无能为力,例如,不同人之间的人脸图像,肯定存在非线性关系,自己做的基于ORL数据集的实 ...

  6. 剑指offer九之变态跳台阶

    一.题目 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级.求该青蛙跳上一个n级的台阶总共有多少种跳法. 二.思路 1.关于本题,前提是n个台阶会有一次n阶的跳法.分析如下: f(1) ...

  7. nc命令简介

    nc介绍 ncat/nc 既是一个端口扫描工具,也是一款安全工具,还能是一款监测工具,甚至可以做为一个简单的 TCP 代理. 在大多数 Debian 发行版中,nc 是默认可用的,它会在安装系统的过程 ...

  8. python使用(五)

    1.shell_option.py 2.db_option.py 1.shell_option.py # coding=utf8 __author__ = 'SummerChill' import o ...

  9. (转)Python3 模块3之 Urllib之 urllib.parse、urllib.robotparser

    原文:https://blog.csdn.net/qq_36148847/article/details/79153738 https://blog.csdn.net/zly412934578/art ...

  10. 基于vue的web应用如何构建成手机端的原生安装包

    话不多说,点击前往