1. 程式人生 > >Spring --17.Spring中的核心監聽器ContextLoaderListener

Spring --17.Spring中的核心監聽器ContextLoaderListener

開發環境:

JDK 1.8
Idea 2017
Tomcat:apache-tomcat-8
Spring:5.0.7

1、概述

ContextLoaderListener是Spring中的核心監聽器,當web工程啟動時,
該監聽器負責建立Spring的IOC容器,存放在ServletContext中;當需要用IOC容器時,就從ServletContext中獲取。

好處:

1、不用我們手動建立IOC容器,由監聽器負責建立;

2、可以保證整個工程中只有一個IOC容器;

2、建立web工程、引入依賴

工程目錄:

建立工程模板 

匯入依賴pom.xml

 <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
            <!-- JSP相關 -->
            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jsp-api</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>5.0.7.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
            </dependency>
            <!-- jdbc模板 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
            </dependency>

            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
        <dependency>
            <groupId>com.day04_tx</groupId>
            <artifactId>Spring_tx</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
        <build>
            <plugins>
                <!-- 配置Tomcat外掛 -->
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <configuration>
                        <port>8080</port>
                        <path>/</path>
                    </configuration>
                </plugin>
            </plugins>


            <finalName>ContextLoaderListener</finalName>
            <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
                <plugins>
                    <plugin>
                        <artifactId>maven-clean-plugin</artifactId>
                        <version>3.0.0</version>
                    </plugin>
                    <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                    <plugin>
                        <artifactId>maven-resources-plugin</artifactId>
                        <version>3.0.2</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-compiler-plugin</artifactId>
                        <version>3.7.0</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>2.20.1</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-war-plugin</artifactId>
                        <version>3.2.0</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-install-plugin</artifactId>
                        <version>2.5.2</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-deploy-plugin</artifactId>
                        <version>2.8.2</version>
                    </plugin>
                </plugins>
            </pluginManagement>
        </build>

3、建立相關類

AccountDao.java

package com.day04_listener.dao;


import com.day04_listener.domain.Account;

import java.util.List;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 9:36 2018/11/15
 */
public interface AccountDao {

    /**
     * 查詢所有使用者資訊
     * @return 返回集合
     */
    public abstract List<Account> findAll();
}

AccountDaoImpl.java

package com.day04_listener.dao.Impl;

import com.day04_listener.dao.AccountDao;
import com.day04_listener.domain.Account;
import com.day04_listener.rowmapper.AccountRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/**
 *
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 9:38 2018/11/15
 */

public class AccountDaoImpl implements AccountDao {

    //jdbcTemplate依賴注入
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * 查詢所有使用者資訊
     * @return 返回集合
     */
    @Override
    public List<Account> findAll() {
       List<Account> list = this.jdbcTemplate.query("SELECT id,name,money FROM account ", new AccountRowMapper());
        return list;
    }
}

AccountService.java

package com.day04_listener.service;

import com.day04_listener.domain.Account;

import java.util.List;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 9:50 2018/11/15
 */
public interface AccountService {

    /**
     * 查詢所有使用者資訊
     * @return 返回集合
     */
    List<Account> findAllAccount();
}

AccountServiceImpl.java

package com.day04_listener.service.Imlp;
import com.day04_listener.dao.AccountDao;
import com.day04_listener.domain.Account;
import com.day04_listener.service.AccountService;

import java.util.List;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 9:53 2018/11/15
 */

public class AccountServiceImpl implements AccountService {
    //accountDao依賴注入、set方法
    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    /**
     * 查詢所有使用者資訊
     * @return 返回集合
     */
    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAll();
    }
}

Account.java

package com.day04_listener.domain;

import java.io.Serializable;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 8:50 2018/11/15
 */
public class Account implements Serializable {
    private Long id;
    private String name;
    private Double money;

    public Account(Long id, String name, Double money) {
        this.id = id;
        this.name = name;
        this.money = money;
    }

    public Account() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money='" + money + '\'' +
                '}';
    }
}

AccountRowMapper.java 將資料庫資料轉換成java物件

package com.day04_listener.rowmapper;

import com.day04_listener.domain.Account;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;

/**將資料庫資料轉成java物件
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 8:51 2018/11/15
 */
public class AccountRowMapper implements RowMapper<Account> {
    @Override
    public Account mapRow(ResultSet resultSet, int row) throws SQLException {
        Account account = new Account();
        account.setId(resultSet.getLong("id"));
        account.setName(resultSet.getString("name"));
        account.setMoney(resultSet.getDouble("money"));
        return account;
    }
}

 

AccountServlet.java

package com.day04_listener.servlet;

import com.day04_listener.domain.Account;
import com.day04_listener.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 10:03 2018/11/16
 */
public class AccountServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //從servletContext中獲取唯一的Ioc容器
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        //從ioc容器中獲取AccountService
        AccountService accountService = (AccountService) ac.getBean("accountService");
        List<Account> list = accountService.findAllAccount();
        request.setAttribute("accounts",list);
        request.getRequestDispatcher("/accounts.jsp").forward(request,response);
    }
}

4、把相關bean配置到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
        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/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">

        <!--匯入jdbc-->
        <context:property-placeholder location="classpath:jdbc.properties"/>

        <bean id="accountService" class="com.day04_listener.service.Imlp.AccountServiceImpl">
            <property name="accountDao" ref="accountDao"></property>
        </bean>

       <bean id="accountDao" class="com.day04_listener.dao.Impl.AccountDaoImpl">
           <property name="jdbcTemplate" ref="jdbcTemplate"></property>
       </bean>

        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSource"></property>
        </bean>

        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${jdbc.driverClass}"></property>
            <property name="url" value="${jdbc.url}"></property>
            <property name="username" value="${jdbc.username}"></property>
            <property name="password" value="${jdbc.password}"></property>
         </bean>


        <!--配置事務管理器-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <!--注入資料來源-->
            <property name="dataSource" ref="dataSource"></property>
        </bean>


        <!--配置事務的屬性-->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                <!--find開頭的方法加只讀事務、*表示萬用字元、匹配任意方法-->
                <tx:method name="find*" read-only="true"/>
                <!--其餘方法是加可讀寫的事務-->
                <tx:method name="*"/>
            </tx:attributes>
        </tx:advice>


        <!--配置事務的切面-->
        <aop:config>
            <!--配置切入點表示式、告訴框架哪些方法要控制事務-->
            <aop:pointcut id="pt" expression="execution(* com.day04_listener.service.Imlp.*.*(..))"/>
            <!--將定義好的事務屬性應用到上述切入點-->
            <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
        </aop:config>

</beans>

jdbc.properties

jdbc.driverClass = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mybatis
jdbc.username = root
jdbc.password = sswqzx

log4j.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=D:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=debug, stdout, file

5、在web.xml中配置核心監聽器

webapp/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_2_5.xsd"
         version="2.5">
    <!--指定Spring核心配置檔案路徑-->
    <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!--配置監聽器、當工程啟動時、建立IOC容器、存放在ServletContext中-->
    <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--配置servlet  可用註解@WebServlet("/accountServlet")-->
    <servlet>
        <servlet-name>AccountServlet</servlet-name>
        <servlet-class>com.day04_listener.servlet.AccountServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>AccountServlet</servlet-name>
        <url-pattern>/accountServlet</url-pattern>
    </servlet-mapping>

</web-app>

6、建立jsp頁面

accounts.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <style type="text/css">
        #customers {
            font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
            width: 100%;
            border-collapse: collapse;
        }

        #customers td, #customers th {
            font-size: 1em;
            border: 1px solid #98bf21;
            padding: 3px 7px 2px 7px;
        }

        #customers th {
            font-size: 1.1em;
            text-align: left;
            padding-top: 5px;
            padding-bottom: 4px;
            background-color: #A7C942;
            color: #ffffff;
        }

        #customers tr.alt td {
            color: #000000;
            background-color: #EAF2D3;
        }
    </style>

</head>
<body>
<table id="customers">
    <tr>
        <th>編號</th>
        <th>姓名</th>
        <th>餘額</th>
    </tr>
    <c:forEach items="${accounts}" var="account">
        <tr>
            <td>${account.id}</td>
            <td>${account.name}</td>
            <td>${account.money}</td>
        </tr>
    </c:forEach>

</table>

</body>
</html>