码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-06-22 13:25:18      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:views   stat   writer   事务   ace   手动   自定义标签库   技术分享   row   

  建立好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>
View Code

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
View Code

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>
View Code

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>
View Code

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>
View Code

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>
View Code

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>
View Code

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>
View Code

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 {
    }
}
View Code

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>
View Code

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!";
        }
    }
}
View Code

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);
}
View Code

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);
    }
}
View Code

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 + ‘\‘‘ +
                ‘}‘;
    }
}
View Code

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

}
View Code

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> {
}
View Code

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

技术分享
package com.longebo.common.basics;

import java.io.Serializable;

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

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>
View Code

20.运行项目

技术分享

 

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

标签:views   stat   writer   事务   ace   手动   自定义标签库   技术分享   row   

原文地址:http://www.cnblogs.com/yysbolg/p/6909021.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!