SSM框架整合

在这里插入图片描述

导入jar文件

项目需要mybatis的jar和spring的jar文件,和整合jar文件
1.aoplliance
2.aspectjweaver
3.commons-logging
4.log4j
5.mybatis
6.mysql-connector-java
7.spring-aop
8.spring-beans
9.spring-context
10.spring-core
11.spring-expression
12.spring-jdbc
13.spring-tx
14commons-dbcp
15.commons-pool
16.commons-fileupload
17.commons-io
18.commons-lang
19.fastjson
20.hibernate-validator
21.jboss-logging
22.jstl
23.mybatis-spring
24.spring-web
25.spring-webmvc
26.standard
27.validation-api

配置文件

1.webxml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!--
2.3默认不解析el表达式
<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>-->
    <display-name>Archetype Created Web Application</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

	/*配置默认字符编码*/
    <filter>
        <filter-name>encodingFileter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFileter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


/*配置监听器  配置了监听器否则在controller层不能使用注解对于Service层* /
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
/*对于mvc的配置**/
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:application-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern> /*拦截所有请求*/
    </servlet-mapping>


</web-app>

Spring配置文件(resources)

1.applicationContext-mybatis.xml
applicationContext-mybatis.xml是spring配置文件,该文件内的主要配置信息有数据源对象,事务管理 ,以及MyBatis的配置信息

<?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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:property-placeholder location="classpath:database.properties"/>

    <context:component-scan base-package="service"/>

    <!--配置数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"  scope="singleton">
        <!--<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url">
            <value><![CDATA[jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull]]></value>
        </property>
        <property name="username" value="root"/>
        <property name="password" value="root"/>-->
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${user}"/>
        <property name="password" value="${password}"/>
<!--        数据库连接池在初始化连接时,要创建的连接个数-->
        <property name="initialSize" value="${initialSize}"/>
<!--        定义连接池中同时连接的最大连接数,默认连接8-->
        <property name="maxActive" value="${maxActive}"/>
<!--        定义连接池中可允许最大空闲连接数-->
        <property name="maxIdle" value="${maxIdle}"/>
<!--        定义连接池最小的连接数-->
        <property name="minIdle" value="${minldle}"/>
<!--        定义最大等待连接时间  ms-->
        <property name="maxWait" value="${maxWait}"/>
<!--        定义配置项的作用是告诉连接池是否开启无用连接回收的机制-->
        <property name="removeAbandoned" value="${removeAbandoned}"/>
<!--        当开启连接回收机制后,配置该配置项控制连接池在超出配置的时间后回收没有用的连接-->
        <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}"/>

<!--        sql心跳-->
<!--        开启Evict的定时校验-->
        <property name="testWhileIdle" value="true"/>
<!--定义在进行borrowObject处理时,对拿到的连接是否进行校验-->
        <property name="testOnBorrow" value="false"/>
<!--        定义returnObject时,对返回的连接是否进行校验-->
        <property name="testOnReturn" value="false"/>
<!--        定义校验使用的sql语句-->
        <property name="validationQuery" value="select 1"/>
        <!--        定义Evict的时间间隔 ms  必须大于0-->
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!--        定义每次校验连接的数量-->
        <property name="numTestsPerEvictionRun" value="${numTestsPerEvictionRun}"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations">
            <list>
                <value>classpath:dao/**/*.xml</value>
            </list>
        </property>
        <!--pagehelper在ssm框架中的配置 在springboot中不用设置-->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <!--使用下面的方式配置参数,一行配置一个 -->
                        <value>
                            offsetAsPageNum=true
                            rowBoundsWithCount=true
                            pageSizeZero=true
                            reasonable=true
                        </value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="dao"/>
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

<!--    aop事务处理-->
    <aop:aspectj-autoproxy/>
    <aop:config proxy-target-class="true">
        <aop:pointcut id="transService" expression="execution(*.* service..*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="transService"/>
    </aop:config>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/>
        </tx:attributes>
    </tx:advice>

</beans>

对应的数据库文件database.properties.

driver=com.mysql.cj.jdbc.Driver
#在和mysql传递数据的过程中,使用unicode编码格式,并且字符集设置为utf-8
url=jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull
user=root
password=root
initialSize=10
maxActive=50
maxIdle=8
minldle=10
maxWait=-1
removeAbandoned=true
removeAbandonedTimeout=10
numTestsPerEvictionRun=50

2.applicationContext-mvc.xml
applicationContext-mvc.xml主要有以下功能
1.配置mvc:annotation-driver/(包括消息转换器配置)
2.通过mvc:resources/标签配置静态文件访问
3.配置支持文件上传——MultipartResolver
4.配置多视图解析器——ContentNegotiatingViewResolver
5.配置拦截器——interceptors

<?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:mvc="http://www.springframework.org/schema/mvc"
       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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="controller"/>
    <mvc:annotation-driven>
<!--        消息转换器-->
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=utf-8</value>
                    </list>
                </property>
            </bean>
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=utf-8</value>
                        <value>application/json</value>
                    </list>
                </property>
                <property name="features">
                    <list>
<!--                        输出Date的日期转换器-->
                        <value>WriteDateUseDateFormat</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>


    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <!--<property name="favorParameter" value="true"/>
        <property name="defaultContentType" value="text/html"/>
        <property name="mediaTypes">
            <map>
                <entry key="html" value="text/html;charset=utf-8"/>
                <entry key="json" value="application/json;charset=utf-8"/>
                <entry key="xml" value="application/xml;charset=utf-8"/>
            </map>
        </property>-->
        <property name="viewResolvers">
            <list>
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="prefix" value="/WEB-INF/jsp/"/>
                    <property name="suffix" value=".jsp"/>
                </bean>
            </list>
        </property>
    </bean>

<!--    文件上传-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5000000"/>
        <property name="defaultEncoding" value="utf-8"/>
    </bean>

    <mvc:resources mapping="/statis/**" location="/statis/"/>

    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
<!--            不拦截某个页面-->
            <mvc:exclude-mapping path="/"/>
            <mvc:exclude-mapping path="/tologin"/>
            <bean class="interceptor.SysInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>


</beans>

对应的视图拦截器,可以自己手动配置文件。
拦截器主要有三个方法
preHandle():请求到达handler之前,先执行该前置处理方法,当该方法返回false时,请求直接返回,若返回true时,请求继续往下传递。由于prehandle()会在Controller之前执行。
postHandle():在请求被HandlerAdapter执行后,执行这个兵团处理方法,由于postHandle()在controller处理方法生成视图之前执行,因此我们可以在该方法中修改ModelAndView
afterCompletion():在响应已经被渲染之后,最后执行该方法,可用于释放资源。

public class SysInterceptor extends HandlerInterceptorAdapter {

    private Logger logger=Logger.getLogger(SysInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.debug("SysInterceptor prehandle");
        HttpSession session=request.getSession();
        User user=(User)session.getAttribute(Constants.USER_SESSION);
        if (null==user){
            response.sendRedirect(request.getContextPath()+"/error.jsp");
            return false;
        }
        return true;
    }
}

3.其他配置文件
在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:context="http://www.springframework.org/schema/context"

       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

<!--    <context:component-scan base-package="dao"/>-->
    <import resource="application-mybatis.xml"/>
</beans>

log4j.properties文件中

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.how2java=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

对应的mybatis-config.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="lazyLoadingEnabled" value="false"/>
    </settings>

    <typeAliases>
        <package name="pojo"/>
    </typeAliases>


</configuration>

这样我们的配置文件基本配置完成。

然后我们开始创建对应的包和类,即可开始代码。项目结构
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值