Java教程

java整合SSM的基本配置

本文主要是介绍java整合SSM的基本配置,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

如果只实现简单的CRUD用到的技术有以下几点,那么我们就基于以下几点做一个配置
基础框架 ssm(Spring-SpringMVC-Mybatis)

数据库 Mysql

前端框架 bootStrap

项目管理工具 maven

逆向工程-Mybatis-Generator 自动生成代码

首先配置Spring的配置文件

**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:aop="http://www.springframework.org/schema/aop"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/util http://www.springframework.org/schema/util/spring-util.xsd
         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
">
        
        <!--扫描业务组件-->
        <context:component-scan base-package="com.wanghao.ssm">
                <!--除了控制器,其他的业务逻辑组件都要扫-->
                <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
        
        <!--Spring的配置文件,这里主要配置和业务逻辑有关的信息-->
        <!--数据源,事务控制-->
        <context:property-placeholder location="dbconfig.properties"></context:property-placeholder>
        <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
                <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
                <property name="driverClass" value="${jdbc.driverClass}"></property>
                <property name="user" value="${jdbc.user}"></property>
                <property name="password" value="${jdbc.password}"></property>
        </bean>

        <!--配置和mybatis的整合,创建SqlSessionFactory对象-->
        <bean id="SqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
                <!--指定mybatis全局配置文件的位置-->
                <property name="configLocation" value="classpath:mybatis-config.xml"></property>
                <!--指定数据源-->
                <property name="dataSource" ref="pooledDataSource"></property>
                <!--指定mybatis mapper文件的位置-->
                <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
        </bean>

        <!--配置扫描器,将Mybatis接口的实现加入到IOC容器中-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
                <property name="basePackage" value="com.wanghao.ssm"></property>
        </bean>

        <!--事务控制-->
        <bean id="DataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
                <!--控制住数据源-->
                <property name="dataSource" ref="pooledDataSource"></property>
        </bean>

        <!--开启基于注解的事务,或使用xml配置的事务(主要的都是使用配置式)-->
        <aop:config>
                <!--切入点表达式-->
                <aop:pointcut id="txpoint" expression="execution(* com.wanghao.ssm..*(..))"></aop:pointcut>
                <!--配置事务增强-->
                <aop:advisor advice-ref="txadvice" pointcut-ref="txpoint"/>
        </aop:config>

        <!--配置事务增强,事务如何切入-->
        <tx:advice id="txadvice" transaction-manager="DataSourceTransactionManager">
                <tx:attributes>
                        <!--所有方法都是事务方法-->
                        <tx:method name="*"/>
                        <tx:method name="get*" read-only="true"/>
                        <!-- 为什么要设置  read-only true 当事务方法为get*开头的方法时,我们默认其执行的是查询操作
                         如果你一次执行单条查询语句,则没有必要启用事务支持,数据库默认支持SQL执行期间的读一致性;
如果你一次执行多条查询语句,例如统计查询,报表查询,在这种场景下,多条查询SQL必须保证整体的读一致性,
否则,在前条SQL查询之后,后条SQL查询之前,数据被其他用户改变,则该次整体的统计查询将会出现读数据不一致的状态,此时,应该启用事务支持。
【注意是一次执行多次查询来统计某些信息,这时为了保证数据整体的一致性,要用只读事务】
                        -->
                </tx:attributes>
        </tx:advice>

        <!--Spring配置文件按的核心点:(数据源、与mybatis整合、事务控制)-->
</beans>

数据库的配置

 dbconfig.properties
  jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_crud?&useSSL=false&serverTimezone=UTC
  jdbc.driverClass=com.mysql.cj.jdbc.Driver
  jdbc.user=root
  jdbc.password=xxxx

SpringMVC的配置

<?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:mvc="http://www.springframework.org/schema/mvc"
       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">
        <!--SpringMVC的配置文件,包含网站跳转逻辑的控制 配置-->
            <!--扫描所有的业务逻辑组件-->
    <context:component-scan base-package="com.wanghao.ssm" use-default-filters="false">
        <!--SpringMVC不能扫描所有的组件注解,所有我们设置只扫描控制器-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter>
    </context:component-scan>

    <!--配置视图解析器,方便页面返回 视图渲染-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--两个标准配置-->
    <!--1.默认的servlet处理器,将Springmvc不能处理的请求交给tomcat,这样就使得动静态资源都能访问了-->
    <mvc:default-servlet-handler/>
    <!--2.注解驱动,可以支持SpringMVC更高级一些的功能,比如JSR303校验,快捷的ajax请求...映射动态请求,视图处理器-->

    <mvc:annotation-driven/>
</beans>

web下的配置

web.xml
  <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--启动Spring容器-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!--配置Springmvc的前端控制器,拦截所有请求-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:SpringMVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>url</url-pattern>
    </servlet-mapping>

    <!--字符编码过滤器,一定要放在所有过滤器之前-->
    <filter>
        <filter-name>CharacterEncodingFilter</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>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!--使用Restful风格的URI,配置隐式过滤器-->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
   <filter-mapping>
       <filter-name>HiddenHttpMethodFilter</filter-name>
       <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

以上基本就是整合SSM的全部配置内容,但由于考虑要写的mapper,pojo 等代码量太大,我们可以使用mybatis的逆向工程,来自动生成我们所需要的代码
在工程下创建mbg.xml进行以下配置:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否去除自动生成的注释 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!-- Mysql数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/ssm_crud?useUnicode=true&amp;characterEncoding=utf-8&amp;
                        useSSL=false&amp;serverTimezone = GMT"
                        userId="root"
                        password="xxxx"
        />
        <!-- 默认为false,把JDBC DECIMAL 和NUMERIC类型解析为Integer,为true时 把JDBC DECIMAL 和NUMERIC类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!-- targetProject:生成POJO类的位置 -->
        <javaModelGenerator
                targetPackage="com.wanghao.ssm.Entity" targetProject=".\src\main\java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="true" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="mapper"
                         targetProject=".\src\main\resources">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- targetProject:mapper接口生成的的位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.wanghao.ssm.Dao" targetProject=".\src\main\java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 指定数据表 -->
        <table tableName="emp" domainObjectName="Employee"></table>
        <table tableName="dept" domainObjectName="Department"></table>
    </context>
</generatorConfiguration>

进行代码生成测试

  @Test
    public void generator() throws Exception {
        List<String> warnings = new ArrayList<String> ();
        boolean overwrite = true;
        // 指定配置文件
        File configFile = new File ("mbg.xml");
        ConfigurationParser cp = new ConfigurationParser (warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }
这篇关于java整合SSM的基本配置的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!