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");

>>>>>>>>>>>>>>>>>>>>>>>>>>> IOC <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

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主机代替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;
        }

>>>>>>>>>>>>>>>>>>>>>> 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。

    <!-- 配置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)。

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);
        }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值