Spring 基礎學習一

1.什麼是Spring
    --開源的輕量級應用開發框架
    --簡化企業級應用程序開發,下降入侵性
    --爲系統提供了一個總體的解決方法。
    --提供的IOC和AOP功能,能夠將組建的耦合度價值最低
        便於系統往後的維護和升級
2.Spring的主要功能
    --DAO : Spring JDBC ; Transaction management
    --ORM : Hibemate、JPA、TopLink、JDO、OJB、iBatis
    --AOP : Spring AOP、AspectJ integration
    --JEE : JMX、JMS、JCA、Remoting、EJBs、Email
    --Web : Spring Web MVC、Framework Integration、Struts、
        WebWork、Tapestry、JSF...
    --Core: The IOC container前端

>>>>>>>>>>>>>>>>>>> Spring 容器 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
--在Spring中,任何的Java類和JavaBean都被當成Bean來處理
    這些Bean經過Spring容器 管理和使用。
--Spring容器實現了IOC機制和AOP機制,這些機制能夠簡化Bean對象
    的建立和管理Bean對象之間的關係(解耦)
--Spring容器三種類型:BeanFactory(接口)和ApplicationContext(接口)
    以及AbstractApplicationContext(具備關閉容器的方法)
1.Spring  容器的實例化
    --ApplicationContext繼承自BeanFactory接口,且擁有更多的企業級方法。
    --須要有一個配置文件,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:jdbc="http://www.springframework.org/schema/jdbc"  
        xmlns:jee="http://www.springframework.org/schema/jee" 
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:aop="http://www.springframework.org/schema/aop" 
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:util="http://www.springframework.org/schema/util"
        xmlns:jpa="http://www.springframework.org/schema/data/jpa"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
            http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">        
    </beans>
    --實例化容器:
        String conf = "ApplicationContext.xml"
        ApplicationContext ac = 
            new ClassPathXmlApplicationContext(conf);
    注:ClassPathXmlApplicationContext類實例化了ApplicationContext
2.實例化一個Bean
    1)在容器配置文件中添加Bean定義
        <bean id="惟一標識符" class="包名.類名"/>
    2)實例化Spring容器
    3)調用getBean()方法獲取Bean的實例
    ---Properties p = ac.getBean("config",Properties.class);
>>>>>>>>>>>>>>>>>>>> 容器對Bean的管理 <<<<<<<<<<<<<<<<<<<<<<<<<
1.Bean 的實例化
    1)構造器來實例化**重要**
    --id或name屬性用於指定Bean的名稱,用於從spring中查找這個Bean對象。
    --class:用於指定Bean類型,會自動調用無參構造器建立對象
    --使用無參構造器
       stp1:類應該提供無參構造器(或缺省構造器)
       stp2:在配置文件中。使用bean元素來配置
       stp3:調用容器的getbean方法
        <!-- 使用無參構造器建立對象 -->
        <!-- id屬性:bean的名稱,要求惟一
            class屬性:bean的完整的類名 -->
        <bean id="eb" class="basic.ExampleBean"/>
    2)使用靜態工廠方法實例化(瞭解)
        --factory-method 屬性用於指定工廠中建立Bean對象的方法,
            必須用static修飾方法。
        <!-- 使用靜態工廠方法建立對象 -->
        <!-- factory-method屬性:指定一個靜態方法 -->
        <bean id="cal" class="java.util.Calendar" 
            factory-method="getInstance"/>
    3)使用實例化工廠方法實例化(瞭解)
        <!-- 使用實例工廠方法建立對象 -->
        <!-- 
            factory-bean屬性:某個bean的id,指定工廠Bean對象
            factory-method屬性:指定實例方法,指定工廠中建立Bean對象的方法。
         -->
        <bean id="cal" class="java.util.Calendar" 
            factory-method="getInstance"/> 
        <bean id="date" factory-bean="cal" factory-method="getTime"/>
2.Bean的命名
    --每一個Bean都須要有名字(即標識符),能夠用id或name屬性指定
    --若是須要指定一個別名的話,以下
        <alias name="date" alias="date1"/>
3.Bean的做用域
    --默認狀況下,對於一個bean的配置,容器只會建立一個實例。
    <!-- 配置做用域 -->
    <!--  scope 屬性的默認值是"singleton"(單例)
          若是屬性值是"prototype",則每次調用getBean方法時,會建立一個新的實例-->
    <bean id="student" class="basic.Student" scope="prototype"/>    
    ▉做用域    ▉描述
    singleton    默認值,一個容器只建立一個對象實例
    prototype     調用一個getBean方法就建立一個新的實例
    request     在一次http請求中,一個Bean對應一個實例(web環境)
    session        在一個http session中,一個Bean對應一個實例(web環境)
  global Session 在全局的http session中,一個Bean對應一個實例
4.延遲加載
    --默認狀況下,容器啓動後,會將全部做用域爲"singleton"的bean建立好。
    若是設置lazy-init屬性值爲true,表示延遲加載。
    (即容器啓動以後,對於做用域爲singleton的bean, 再也不建立相應的實例)
    <!-- 配置延遲加載
      lazy-init屬性若是爲true,表示延遲加載
      (即容器啓動以後,對於此做用域爲singleton的bean,再也不建立響應的實例)
     -->
    <bean id="tea1" class="basic.Teacher" lazy-init="true"/>
5.生命週期
    <!-- 初始方法
        init-method屬性:初始化方法名
        destroy-method屬性:銷燬方法名
     -->
    <bean id="message" class = "basic.MessageBean" 
        init-method="init" destroy-method="destroy"/>
    --初始化:使用init-method屬性來指定初始化方法。
    --銷燬:使用destroy-method屬性指定銷燬方法。
    注:若是scope屬性設置爲prototype,則銷燬方法不起做用。
    --須要使用具備關閉方法的子接口AbstractApplicationContext
    AbstractApplicationContext ac = 
        new ClassPathXmlApplicationContext("conf/basic2.xml");java

>>>>>>>>>>>>>>>>>>>>>>>>>>> IOC <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<web

1.IOC是什麼?
    --IOC:Inversion Of Controll 控制反轉
    --指程序中對象的獲取方式發生反轉,由new建立方式轉變爲
        第三方框架建立、注入(DI),它下降了對象之間的耦合度
    --Spring容器纔有DI方式實現了IOC控制,IOC是Spring的基礎和核心
2.DI是什麼?
    --DI: Dependcy injection 依賴注入
    --容器經過調用對象提供的set方法或者構造器來創建對象之間的依賴關係。
    注:IOC是目標,DI是手段。
3.使用set方法注入來創建對象之間的依賴關係
    --主要用於無參構造器注入屬性的值
    <!-- 使用set 方法來注入對象之間的依賴關係 -->
    <bean id="a1" class="ioc.A" >
        <property name="b" ref="b1"></property>
    </bean>
    <bean id="b1" class="ioc.B"/>
    注:B類實例化A類中調用的一個接口,同理C類也能實例化這個接口
        也就是A類在不改代碼的狀況向下也能夠調用C。
4.使用構造器注入來創建對象之間的依賴關係
    --經過調用帶參的構造器來實現的
    --容器在實例化bean時,根據參數類型執行相應的構造器
    <bean id="b1" class="ioc.B"></bean>
    <!-- 配置構造器方式注入
        index屬性:指定參數的下標(從0開始)
        ref屬性:指定一個bean的id
     -->
    <bean id="a1" class="ioc.A">
        <constructor-arg index="0" ref="b1"/>
        <constructor-arg index="1" ref="c1"/>
        <constructor-arg index="2" value="參數3"/>
    </bean>
5.自動裝配
    --spring容器依據某種規則,自動創建對象之間的依賴關係。
--規則:
    --默認狀況下,容器禁止自動裝配
  >>設置autowire屬性讓容器自動裝配
    --byName:容器會查找id等於屬性名稱的bean,而後調用對應的set方法來完成注入
        若是找不到對應的bean,會注入null值
        --<bean id="rest" class="autowire.Restaurant" autowire="byName"/>    
    --byType:容器會查找與屬性類型一致的bean,而後調用對應的set方法來完成注入。
        注意:若是找不到對應的bean,會注入null。找到多個值會報錯。
        --<bean id="rest" class="autowire.Restaurant" autowire="byType"/>
    --constructor:相似byType,只不過調用的是構造器來完成注入
6.注入基本類型的值
    --使用value屬性
    --使用value屬性來完成注入
    <bean id="emp" class="other.ExampleBean" >
        <property name="name" value="小嶽嶽"/>
        <property name="age" value="18"/>
    </bean>
7.注入集合類型的值
----List
    <bean id="emp" class="other.ExampleBean" >
        <property name="cities">
            <list>
                <value>北京</value>
                <value>上海</value>
                <value>深圳</value>
                <value>深圳</value>
            </list>
        </property>
    </bean>
----Set
    <bean id="emp" class="other.ExampleBean" >
        <property name="interest">
            <set>
                <value>汽車</value>
                <value>打遊戲</value>
                <value>看小說</value>
                <value>美食</value>
                <value>美食</value>
            </set>
        </property>
    </bean>
----map
    <bean id="emp" class="other.ExampleBean" >
        <property name="score">
            <map>
                <entry key="english" value="66"/>
                <entry key="math" value="99"/>
                <entry key="JAVA" value="80"/>
            </map>
        </property>
    </bean>
----properties
    <bean id="emp" class="other.ExampleBean" >
        <property name="db">
            <props>
                <prop key="username">tiger</prop>
                <prop key="passoword">1234</prop>
            </props>
        </property>
    </bean>
8.使用引用的方式注入集合類型的值
    --使用引用的方式注入集合類型的值
    --將集合配置成一個bean
        命名空間:類名
    <util:list id="citiesBean">
        <value>長沙</value>
        <value>岳陽</value>
        <value>華容</value>
    </util:list>
    <bean id="eb2" class="other.ExampleBean">
        <property name="cities" ref="citiesBean"/>
    </bean>
    --使用spring容器讀取properties文件的內容
    <!-- 使用spring容器讀取properties文件的內容,並存放到Properties對象。
        classpath:從類路徑下面查找 -->
    <util:properties id="config" location="classpath:config.properties"/>
9.Spring表達式
    --用來訪問bean或集合的值
    --Spring引入的一種表達式語言,與EL類似。
    <!-- 使用Spring表達式訪問其餘bean的屬性 -->
    <bean id="sel" class="other.SpringELBean">
        <property name="name" value="#{emp.name}"/>
        <property name="city" value="#{citiesBean[1]}"/>
        <property name="score" value="#{emp.score['英語']}"/>
        <property name="pagesize" value="#{config.pagesize}"/>
    </bean>spring

>>>>>>>>>>>>>>>>>>>>> 組件掃描 <<<<<<<<<<<<<<<<<<<<<<<
--組件掃描:使用Spring主機代替XML配置來聲明Bean,
    並使用註解來管理Bean對象
1.什麼是組件掃描?
    --容器會掃描指定包及其子包下面的全部類,
    --若是該類包含有特定的註解(好比@Component),
    --則容器會將該類歸入容器進行管理(至關於配置文件中有一個bean的配置)
2.如何使用組件掃描?
step1: 在類名前添加相應的註解
    @Component 通用組件
    @Service 業務層組件
    @Respository 持久層組件
    @Controller 控制層組件
step2: 在配置文件中配置文件掃描
    <!-- 配置組件掃描  base-package屬性:包名 -->
    <context:component-scan base-package="annotation"/>
--@Component("id") : 缺省值是首字母小寫的類名
3.做用域
    --類前面加 @Scope("prototype")
4.延遲加載
    --類前面加 @Lazy(true)    
5.生命週期:初始化和銷燬回調
    --@PostConstruct和@PreDestroy
    --這兩個註解來自於javaee,須要導入annotation.jar文件
    public class ExampleBean {
        @PostConstruct
        public void init(){    }
        @PreDestroy
        public void destroy(){}
    }
6.注入Spring表達式的值
    -- @Value("#{sping表達式}")
    注:該註解能夠加到屬性前,也能夠加到屬性的set方法前面
        加載屬性前面,使用的是反射的直接賦值
    1)在xml配置中指定要注入的properties文件
        <util:properties id="config" 
            location="classpath:config.properties"/>
    2)在屬性前面使用@value註解
        @Component("mb")
        public class MessageBean {
            @Value("#{config.pagesize}")
            private String pagesize;
            @Value("北京市海淀區")
            private String address;
        }
7.指定依賴注入關係
    --具備依賴關係的Bean對象,
        利用如下任意一種註解均可以實現關係注入
    --@Autowired/@Qualifier
        能夠處理構造器注入和Set方法注入(包括加在屬性前面)
        --@Autowired加到set方法前面,
        --@Qualifier用來指定 要注入的bean的id。
    注,若是不使用@Qualifier,會使用 byType的方式來注入
    --@Resource
        只能處理Set注入(包括加在屬性前面)
    --@Inject/@Named (瞭解)
        和Autowire用法一致
    1)@Autowired/@Qualifier
    @Component("rest")
    public class Restaurant {
        @Autowired
        @Qualifier("wt")
        private Waiter wt;
        @Autowired
        public School(@Qualifier("wt") Waiter wt) {
            this.wt = wt;
        }
    }
    2)@Resource (也能夠放在set方法前面)
    @Component("bar")
    public class Bar {
        @Resource(name="wt") 
        private Waiter wt;
    }
8.注入Spring表達式值
    --@Value 註解能夠注入spring表達式值
    1)在XML配置中指定要注入的properties文件
        <util:properties id="const" location="classpath:comst.properties"/>
    2)而後在屬性或Setter方法前使用@Value註解
        @Component
        public class DemoBean{
            @Value("#{const.PAGE_SIZE}")
            private int pageSize;
        }sql

>>>>>>>>>>>>>>>>>>>>>> Spring-MVC **重要** <<<<<<<<<<<<<<<<<<<<<<<<<<<
1.SpringMVC是什麼?
    --是Spring框架的一個功能模塊
    --一個用來簡化開發MVC結構的web的框架。
    注:SpringMVC屬於Spring框架的一部分數據庫

2.SpringMVC的五大組件:
    -- DispatcherServlet (前端控制器,請求入口) 
    -- HandlerMapping (請求派發)
        入口:SimpleUrlHandlerMapping
    -- Controller (處理器,請求處理流程)
    -- ModelAndView (模型,防撞業務處理結果和視圖)
    -- ViewResolver (視圖解析器,視圖顯示處理器)
        出口:InternalResourceViewResolver
step1,DispatcherServlet收到請求以後,
    依據 HandlerMapping的配置,調用相應的Controller.handleRequest來處理。
step2,Controller將處理結果封裝到ModelAndView對象。 
    而後將該對象返回給DispatcherServlet來處理。 
    ◆注:ModelAndView對象包含有兩部分數據,一是處理結果,     
    另外,還包含有視圖名(就是一個字符串,好比"hello")。 
step3,DispatcherServlet依據ViewResolver的解析,
    調用相應的視圖對象(好比jsp)來生成相應的頁面。
3.編程步驟
    step1,導包 spring-webmvc 
    step2,添加spring的配置文件。
    step3,配置DispatcherServlet。(web.xml)
    step4,寫Controller類。
    step5,寫jsp。
    step6,配置HandlerMapping和ViewResolver。apache

    <!-- 配置HandlerMapping -->
    <!-- 
        HandlerMapping告訴DispatcherServlet請求地址(url)與處理器(Controller)的對應關係
     -->
     <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
         <property name="mappings">
             <props>
                 <prop key="/hello.do">hc</prop>
             </props>
         </property>
     </bean>
     <bean id="hc" class="controller.HelloController"/>編程

     <!-- 配置ViewResolver -->
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         <property name="prefix" value="/WEB-INF/"/>
         <property name="suffix" value=".jsp"/>
     </bean>數組


>>>>>>>>>>>>>>>>>>> 基於註解的SpringMVC應用<<<<<<<<<<<<<<<<<<<<<<<<
1.編程步驟
    step1. 導包。
    step2. 添加spring配置文件。
    step3. 配置DispatcherServlet。
    step4. 寫Controller。
    a. 不用實現Controller接口。
    b. 能夠添加多個方法。
    c. 方法名稱不做要求,返回值的類型能夠是 ModelAndView,也能夠是String。
    d. 在類名前添加@Controller。
    e. 在類名前或者方法前添加@RequestMapping。
    ◆注:@RequestMapping的做用至關於HandlerMapping。
    step5. 寫jsp。
    step6. 配置視圖解析器,配置組件掃描, 配置springmvc註解掃描
        (讓spring容器可以識別 @RequestMapping)。spring-mvc

2.使用@Controller註解聲明Controller組件    
    --這樣能夠不實現Controller接口,
        請求方式也能夠靈活定義
    @Controller
    public class BmiController {
    }
    --爲了@Controller註解生效,須要配置Spring的XML文件
    <!-- 配置包掃描 -->
    <context:component-scan base-package="controller"/>
    --爲了開啓@RequestMapping註解映射,須要配置Spring的XML文件
    <!-- 配置註解掃描 Spring 3.2版本之後 -->
    <mvc:annotation-driven/>

3.接收請求參數
    /**
     * 第一種方式,使用request獲取請求參數
     */
    @RequestMapping("/login.do")
    public String checkLogin(HttpServletRequest req){
        String adminCode = req.getParameter("adminCode");
        String pwd = req.getParameter("pwd");
        return "index";
    }
    /**
     * 第二種方式,使用@RequestParam獲取請求參數
     *         即便形參名字和傳過來的key值一致,
     *         最好在每一個形參前面加上@RequestParam
     *         由於Java反射機制不記錄形參的名字
     */
    @RequestMapping("/login2.do")
    public String checkLogin2(
            @RequestParam("adminCode")String adminCode, 
            @RequestParam("pwd")String password){
        System.out.println(adminCode+";"+password);    
        return "index";
    }
    /**
     * 推薦使用
     * 第三種方式,封裝成一個JavaBean獲取請求參數
     *     1.寫一個Java類,屬性和傳入的參數對應
     *     2.處理方法須要帶有這個Java類的參數
     */
    @RequestMapping("/login3.do")
    public String checkLogin3(Admin a){
        System.out.println(a.getAdminCode()+";"+a.getPwd());    
        return "index";
    }
    /**
     *用於封裝請求參數值的JavaBean,要求:
     *    1.屬性名與請求參數名一致
     *     2.屬性值有對應的get/set方法
     */
    public class Admin implements Serializable {
        private String adminCode;
        private String pwd;
        public String getAdminCode() {
            return adminCode;
        }
        public void setAdminCode(String adminCode) {
            this.adminCode = adminCode;
        }
        public String getPwd() {
            return pwd;
        }
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
    }

4.向頁面傳值
方式一;將數據綁定到request對象
    /**向頁面傳值
     * 第一種方式:綁定數據到request對象
     */
    @RequestMapping("/login4.do")
    public String checkLogin4(Admin a,HttpServletRequest req){
        req.setAttribute("adminCode", a.getAdminCode());
        //SpringMVC 默認使用轉發機制來跳轉
        return "index";
    }
方式二;返回對象ModelAndView對象
    /**
     * 第二種方式:返回ModelAndView對象
     */
    @RequestMapping("/login5.do")
    public ModelAndView checkLogin5(Admin a){
        System.out.println("checkLogin5()");
        System.out.println(a);
        Map<String,Object> model = new HashMap<String,Object>();
        model.put("adminCode", a.getAdminCode());
        return new ModelAndView("index", model);
    }
方式三:將ModelMap做爲方法入參
    /**
     * 第三種方式:將ModelMap做爲方法入參
     */
    @RequestMapping("/login6.do")
    public String checkLogin6(Admin a,ModelMap mm){
        System.out.println("checkLogin6()");
        System.out.println(a);
        mm.addAttribute("adminCode", a.getAdminCode());
        return "index";
    }

方式四:將數據綁定到session對象
    /**
     * 第四種方式:將數據綁定到session對象
     */
    @RequestMapping("/login7.do")
    public String checkLogin7(Admin a,HttpSession session){
        System.out.println("checkLogin7()");
        System.out.println(a);
        session.setAttribute("adminCode", a.getAdminCode());
        return "index";
    }
5.重定向
    
    /**
     * 方式一:返回值是String
     */
    @RequestMapping("/login8.do")
    public String checkLogin8(){
        System.out.println("checkLogin8()");
        return "redirect:toIndex.do";
    }
    @RequestMapping("/toIndex.do")
    public String toIndex(){
        return "index";
    }
    /**
     * 方式二:返回值是ModelAndView
     */
    @RequestMapping("/login9.do")
    public ModelAndView checkLogin9(){
        RedirectView rv = new RedirectView("toIndex.do");
        return new ModelAndView(rv);
    }
    @RequestMapping("/toIndex.do")
    public String toIndex(){
        return "index";
    }

6.解決接收數據亂碼問題
    在web.xml文件當中,配置springmvc提供的一個過濾器(CharacterEncodingFilter)。
    須要注意:
        a.表單提交方式必須設置爲"post"。
        b.過濾器的編碼設置與表單的編碼要一致。
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
7.攔截器
    1)什麼是攔截器?
        --前端控制器在調用處理器以前,若是發現有攔截器存在, 
            則會先調用攔截器,而後再調用處理器。
        ◆注:過濾器屬於servlet規範當中定義的組件,
            而攔截器 屬於spring框架定義的組件。
    2)如何寫一個攔截器?
        step1. 寫一個java類,實現HandlerInterceptor接口。
        public class SomeInterceptor implements HandlerInterceptor {
            //handler:處理器方法對象
            public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler)
                    throws Exception {
                //方法體
                return true;
            }
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                    ModelAndView modelAndView) throws Exception {
                //方法體
            }
            // ex:處理器拋出異常
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
                    throws Exception {
                //方法體
            }
        }
        step2. 將攔截處理邏輯寫在相應的接口方法裏面:
        --preHandle方法:前端控制器先調用攔截器的preHandle方法, 
            若是該方法返回值爲true,則攔截器繼續向後調用;
            若是 該方法返回值爲false,則攔截器再也不向後調用,請求處理完成。
        --postHandle方法:處理器方法已經執行完成,
            正準備將 ModelAndView對象返回給前端控制器以前執行。
            能夠在 該方法裏面,修改ModelAndView對象。
        --afterCompletion方法:最後執行的方法,要注意,
            若是 preHandle方法返回值爲false,該方法不會執行。
        step3. 配置攔截器。
        <!-- 攔截器 -->
        <!-- 能夠配置多個攔截器,配置的前後順序決定了攔截器執行的前後順序 -->
        <mvc:interceptors>
            <mvc:interceptor>
                <-- /** 表示全部 -->
                <mvc:mapping path="/**"/>
                <mvc:exclude-mapping path="/toLogin.do"/>
                <mvc:exclude-mapping path="/login.do"/>
                <mvc:exclude-mapping path="/createImg.do"/>
                <bean class="com.tarena.netctoss.
                        interceptors.SessionInterceptor"/>
            </mvc:interceptor>
        </mvc:interceptors>
8.讓spring框架來處理異常
    --將異常拋給spring,由spring框架依據相應的配置,來處理異常。
    方式一: 使用簡單異常處理器。
        --適合全局處理簡單異常
        step1. 配置簡單異常處理器。
        <!-- 簡單異常處理器 -->
        <bean class="org.springframework.web.servlet.
            handler.SimpleMappingExceptionResolver">
            <property name="exceptionMappings">
                <props>
                    <-- key是異常的類型,value是跳轉的視圖頁面 -->
                    <prop key="java.lang.Exception">hello1_error</prop>
                </props>
            </property>
        </bean>     
        step2. 編寫異常處理頁面。即:hello1_error.jsp
    方式二: 使用@ExceptionHandler或者實現HandlerExceptionResolver接口
    --適合全局處理有「處理過程」的異常
    step1. 在處理器類當中,添加一個用來處理異常的方法, 
        該方法必須添加@ExceptionHandler。
    step2. 在異常處理方法裏面,依據異常類型,分別進行不一樣的處理。
    /**
     * ex: 其餘方法拋出的異常
     * 這是一個異常處理方法,能夠處理其餘方法拋出的異常
     */
    @ExceptionHandler
    public String excute(Exception ex, HttpServletRequest req){
        if(ex instanceof NumberFormatException){
            req.setAttribute("error", "請輸入數字");
            return "error";
        }
        if(ex instanceof StringIndexOutOfBoundsException){
            req.setAttribute("error", "數組越界");
            return "error";
        }
        //其餘異常
        req.setAttribute("error", "系統異常,請稍後再試");
        return "error";
    }

>>>>>>>>>>>>>>>>>>>>>>>>> spring jdbc <<<<<<<<<<<<<<<<<<<<<<<< 1.spring jdbc是什麼?     --spring框架對jdbc的封裝。 2.如何使用spring jdbc?     --spring框架提供了一個JdbcTemplate類,提供了大量的 實現的方法,     咱們只須要配置好該對象,而後調用其方法便可。 --step1.導包 : spring-webmvc,ojdbc,dbcp,junit,spring-jdbc --step2.添加spring配置文件,配置JdbcTemplate。     <!-- 配置DataSource -->     <bean id="ds" class="org.apache.commons.dbcp.BasicDataSource"         destroy-method="close">         <property name="driverClassName" value="#{db.driver}" />         <property name="url" value="#{db.url}" />         <property name="username" value="#{db.user}" />         <property name="password" value="#{db.pwd}" />         <property name="initialSize" value="#{db.initSize}" />         <property name="maxActive" value="#{db.maxSize}" />     </bean>     <!-- 配置JdbcTemplates -->     <bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">         <property name="dataSource" ref="ds" />     </bean> --step3.調用JdbcTemplate的方法來訪問數據庫。     @Repository     public class EmpDao {         @Resource(name="jt")         private JdbcTemplate jt;             /**          * JdbcTemple 會將底層的異常捕獲以後,統一轉化成運行異常統一拋出          */         public void save(Emp emp){             String sql = "INSERT INTO emp_zxc VALUES(seq_emp_zxc.nextval,?,?)";             Object[] param = new Object[]{emp.getName(),emp.getAge()};             jt.update(sql,param);         }     }

相關文章
相關標籤/搜索