1. 程式人生 > 實用技巧 >SSM - 整合配置彙總

SSM - 整合配置彙總

目錄

0 Maven - pom.xml

jar包座標

<dependencies>


    <!-- servlet3.1規範的座標 -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    

    
    
    
    <!-- Spring整合MyBatis -->
    
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.6</version>
    </dependency>
    
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>
    
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.21</version>
    </dependency>
    
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.6</version>
    </dependency>
    
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.26</version>
    </dependency>
    
    <!-- 分頁外掛 -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.2</version>
    </dependency>

    
    
    
    <!-- SpringMVC -->
    
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.4</version>
    </dependency>
    
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>
    
    
    
    
    
    <!-- JSON -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.8</version>
    </dependency>
    
    



    <!--spring整合junit單元測試-->
    
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>

    
  </dependencies>

外掛

   <build> 
    <plugins> 
        
      <!--tomcat外掛-->  
      <plugin> 
        <groupId>org.apache.tomcat.maven</groupId>  
        <artifactId>tomcat7-maven-plugin</artifactId>  
        <version>2.1</version>  
        <configuration> 
          <port>80</port>  
          <path>/</path> 
        </configuration> 
      </plugin> 
        
    </plugins> 
  </build> 

1 xml與註解混合配置方式

1.1 MyBatis對映配置檔案 - xxxDao.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.itheima.dao.UserDao">

    <!--新增-->
    <insert id="save" parameterType="user">
        insert into user(userName,password,realName,gender,birthday)values(#{userName},#{password},#{realName},#{gender},#{birthday})
    </insert>

    <!--刪除-->
    <delete id="delete" parameterType="int">
        delete from user where uuid = #{uuid}
    </delete>

    <!--修改-->
    <update id="update" parameterType="user">
        update user set userName=#{userName},password=#{password},realName=#{realName},gender=#{gender},birthday=#{birthday} where uuid=#{uuid}
    </update>

    <!--查詢單個-->
    <select id="get" resultType="user" parameterType="int">
        select * from user where uuid= #{uuid}
    </select>

    <!--分頁查詢-->
    <select id="getAll" resultType="user">
        select * from user
    </select>

    <!--登入-->
    <select id="getByUserNameAndPassword" resultType="user" >
        select * from user where userName=#{userName} and password=#{password}
    </select>

</mapper>

1.2 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: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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    
    <!-- 實際開發中, spring註解掃描和springmvc註解掃描的包不要重複 -->
	<!-- spring: 排除有@Controller註解的類 -->
	<context:component-scan base-package="com.itheima">
		<context:exclude-filter type="annotation" 						
                           expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>
    
    <!-- 開啟AOP註解驅動支援 -->
    <aop:aspectj-autoproxy/>

    <!-- 載入perperties配置檔案的資訊 -->
    <context:property-placeholder location="classpath:*.properties"/>

    <!-- 載入druid第三方資源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!-- spring整合mybatis後控制的建立連線用的物件,從mybatis核心配置檔案來 -->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--起別名-->
        <property name="typeAliasesPackage" value="com.itheima.domain"/>
        <!--分頁外掛-->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <props>
                            <prop key="helperDialect">mysql</prop>
                            <prop key="reasonable">true</prop>
                        </props>
                    </property>
                </bean>
            </array>
        </property>
    </bean>

    <!-- 載入mybatis對映配置的掃描,從mybatis核心配置檔案來,確定SQL對映位置 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.itheima.dao"/>
    </bean>

     <!-- 配置service作為spring的bean,注入dao -->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>
    
    
    <!--事務管理-->
    <!--開啟註解式事務-->
    <tx:annotation-driven transaction-manager="txManager"/>
    <!--定義事務管理器-->
    <bean id="txManager" 
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

可選 - 事務管理純xml

	<!--定義事務管理器-->
    <bean id="txManager" 
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
	<!--定義事務管理的通知類-->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <!--定義控制的事務-->
        <tx:attributes>
            <tx:method name="*" read-only="false"/>
            <tx:method name="find*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!--配置事務AOP-->
    <aop:config>
        <aop:pointcut id="pt" expression="execution(* 
                                          com.itheima.service.*Service.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
    </aop:config>

3 SpringMVC配置檔案 - spring-mvc.xml

標準配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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.xsd
              http://www.springframework.org/schema/mvc
              http://www.springframework.org/schema/mvc/spring-mvc.xsd
              http://www.springframework.org/schema/context
              http://www.springframework.org/schema/context/spring-context.xsd">
    
	<!-- 實際開發中, spring註解掃描和springmvc註解掃描的包不要重複 -->
	<!-- SpringMVC: 只掃描controller包下的類 -->
	<context:component-scan base-package="com.itheima.controller"/>
    
    <!-- 開啟註解驅動支援 -->
    <mvc:annotation-driven />
    
    <!-- 放行靜態資源請求 (核心控制器攔截的是所有請求) -->
	<mvc:default-servlet-handler />
    
    
</beans>

可選 - 自定義格式轉換器

	<!--開啟註解驅動,載入自定義格式化轉換器對應的型別轉換服務-->
    <mvc:annotation-driven conversion-service="conversionService"/>
    <!--自定義格式化轉換器-->
    <bean id="conversionService" 
          class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <!--覆蓋格式化轉換器定義規則,該規則是一個set集合,
				對格式化轉換器來說是追加和替換的思想,而不是覆蓋整體格式化轉換器-->
        <property name="formatters">
            <set>
                <!--具體的日期格式化轉換器-->
                <bean class="org.springframework.format.datetime.DateFormatter">
                    <!--具體的規則,不具有通用性,僅適用於當前的日期格式化轉換器-->
                    <property name="pattern" value="yyyy-MM-dd"/>
                </bean>
            </set>
        </property>
    </bean>

    
    <!--開啟註解驅動,載入自定義格式化轉換器對應的型別轉換服務-->
    <mvc:annotation-driven conversion-service="conversionService"/>
    <!--自定義型別轉換器-->
    <bean id="conversionService" 
          class="org.springframework.context.support.ConversionServiceFactoryBean">
        <!--覆蓋型別轉換器定義規則,該規則是一個set集合,對型別轉換器來說是追加和替換的思想,
										而不是覆蓋整體格式化轉換器-->
        <property name="converters">
            <set>
                <!--新增自定義的型別轉換器,會根據定義的格式覆蓋系統中預設的格式-->
                <!--當前案例中是將String轉換成Date的型別轉換器進行了自定義,
					所以新增後,系統中原始自帶的String——>Date的型別轉換器失效-->
                <bean class="com.itheima.converter.MyDateConverter"/>
            </set>
        </property>
    </bean>

可選 - 頁面訪問快捷設定

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="prefix" value="/WEB-INF/page/"/>
	<property name="suffix" value=".jsp"/>
</bean>

可選 - 簡單異常處理器 SimpleMappingExceptionResolver

SpringMVC已經定義好了該型別轉換器,在使用時可以根據專案情況進行相應異常與檢視的對映配置

	<!--配置簡單對映異常處理器-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="defaultErrorView" value="error.jsp"/>   <!--預設錯誤檢視-->
        <property name="exceptionMappings">
            <map>
                <!--  key:異常型別  value:錯誤檢視-->
                <entry key="com.itheima.exception.MyException" value="error"/>
                <entry key="java.lang.ClassCastException" value="error"/>
            </map>
        </property>
    </bean>

4 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_3_1.xsd"
         version="3.1">

    
    <!--啟動伺服器時,通過監聽器載入spring執行環境-->
    <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!-- Spring整合SpringMVC, 載入Spring配置檔案-->
    <context-param>
    	<param-name>contextConfigLocation</param-name>
    	<param-value>classpath*:applicationContext.xml</param-value>
    </context-param>
    
    
    <!-- 配置SpringMVC核心控制器 -->
    <!-- 將請求轉發到對應的具體業務處理器Controller中 -->
    <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*:spring-mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</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>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

可選 - Restful請求配置

	<!--配置攔截器,解析請求中的引數_method,否則無法發起PUT請求與DELETE請求,配合頁面表單使用-->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <servlet-name>DispatcherServlet</servlet-name>
    </filter-mapping>

2 純註解配置方式

2.1 Spring整合MyBatis

MyBatis對映 - UserDao

public interface UserDao {
    
    @Insert("insert into user(userName,password)values(#{userName},#{password})")
    public boolean save(User user);

    @Update("update user set userName=#{userName},password=#{password} where uuid=#{uuid}")
    public boolean update(User user);

    @Delete("delete from user where uuid = #{uuid}")
    public boolean delete(Integer uuid);

    @Select("select * from user where uuid = #{uuid}")
    public User get(Integer uuid);

    @Select("select * from user")
    public List<User> getAll();

    @Select("select * from user where userName=#{userName} and password=#{password}")
    public User getByUserNameAndPassword(@Param("userName") String userName,
                                         @Param("password") String password);
}

配置類 config包 - JdbcConfig類

public class JdbcConfig {
    //使用注入的形式,讀取properties檔案中的屬性值,等同於<property name="*******" value="${jdbc.driver}"/>
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String userName;
    @Value("${jdbc.password}")
    private String password;

    //定義dataSource的bean,等同於<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    @Bean("dataSource")
    public DataSource getDataSource(){
        //建立物件
        DruidDataSource ds = new DruidDataSource();
        //手工呼叫set方法,等同於set屬性注入<property name="driverClassName" value="******"/>
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(userName);
        ds.setPassword(password);
        return ds;
    }
}


配置類 config包 - MyBatisConfig類

public class MyBatisConfig {
    //定義MyBatis的核心連線工廠bean,等同於<bean class="org.mybatis.spring.SqlSessionFactoryBean">
    @Bean
    //引數使用自動裝配的形式載入dataSource,為set注入提供資料,dataSource來源於JdbcConfig中的配置
    public SqlSessionFactoryBean getSqlSessionFactoryBean(@Autowired DataSource dataSource,@Autowired Interceptor interceptor){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        //等同於<property name="typeAliasesPackage" value="com.itheima.domain"/>
        ssfb.setTypeAliasesPackage("com.itheima.domain");
        //等同於<property name="dataSource" ref="dataSource"/>
        ssfb.setDataSource(dataSource);
//        //等同於<bean class="com.github.pagehelper.PageInterceptor">
//        Interceptor interceptor = new PageInterceptor();
//        Properties properties = new Properties();
//        properties.setProperty("helperDialect","mysql");
//        properties.setProperty("reasonable","true");
//        //等同於<property name="properties">
//        interceptor.setProperties(properties);
        ssfb.setPlugins(interceptor);
        return ssfb;
    }

    //定義MyBatis的對映掃描,等同於<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    @Bean
    public MapperScannerConfigurer getMapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        //等同於<property name="basePackage" value="com.itheima.dao"/>
        msc.setBasePackage("com.itheima.dao");
        return msc;
    }

    @Bean("pageInterceptor")
    public Interceptor getPageInterceptor(){
        Interceptor interceptor = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("helperDialect","mysql");
        properties.setProperty("reasonable","true");
        //等同於<property name="properties">
        interceptor.setProperties(properties);
        return interceptor;
    }

}

配置類 config包 - SpringConfig類

import javax.sql.DataSource;

@Configuration
//等同於<context:component-scan base-package="com.itheima">
@ComponentScan(value = "com.itheima",excludeFilters =
    //等同於<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    @ComponentScan.Filter(type= FilterType.ANNOTATION,classes = {Controller.class}))
//等同於<context:property-placeholder location="classpath*:jdbc.properties"/>
@PropertySource("classpath:jdbc.properties")
//等同於<tx:annotation-driven />,bean的名稱預設取transactionManager
@EnableTransactionManagement
@Import({MyBatisConfig.class,JdbcConfig.class})
public class SpringConfig {
    //等同於<bean id="txManager"/>
    @Bean("transactionManager")
    //等同於<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    public DataSourceTransactionManager getTxManager(@Autowired DataSource dataSource){
        DataSourceTransactionManager tm = new DataSourceTransactionManager();
        //等同於<property name="dataSource" ref="dataSource"/>
        tm.setDataSource(dataSource);
        return tm;
    }
}

2.2 Spring整合SpringMVC

配置類 config包 - ServletContainersInitConfig類

public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {

    //建立Servlet容器時,使用註解的方式載入SPRINGMVC配置類中的資訊,並載入成WEB專用的ApplicationContext物件
    //該物件放入了ServletContext範圍,後期在整個WEB容器中可以隨時獲取呼叫
    @Override
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(SpringMvcConfig.class);
        return ctx;
    }

    //註解配置對映地址方式,服務於SpringMVC的核心控制器DispatcherServlet
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    @Override
    //基本等同於<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    protected WebApplicationContext createRootApplicationContext() {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(SpringConfig.class);
        return ctx;
    }

    //亂碼處理作為過濾器,在servlet容器啟動時進行配置,相關內容參看Servlet零配置相關課程
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        //觸發父類的onStartup
        super.onStartup(servletContext);
        //1.建立字符集過濾器物件
        CharacterEncodingFilter cef = new CharacterEncodingFilter();
        //2.設定使用的字符集
        cef.setEncoding("UTF-8");
        //3.新增到容器(它不是ioc容器,而是ServletContainer)
        FilterRegistration.Dynamic registration = servletContext.addFilter("characterEncodingFilter", cef);
        //4.新增對映
        registration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE), false, "/*");
    }
}

配置類 config包 - SpringMvcConfig類

@Configuration
//等同於<context:component-scan base-package="com.itheima.controller"/>
@ComponentScan("com.itheima.controller")
//等同於<mvc:annotation-driven/>,還不完全相同
@EnableWebMvc
public class SpringMvcConfig {
}