• ssm复习资料


    【】Spring概念

    Spring是基于JavaEE的企业级应用各层对象的管理框架。

    【】Spring功能

    管理各层对象的创建,销毁和依赖。能与各个流行框架集成,完成系统功能。

    【】Spring组成

    1. IoC核心模块(Core Container容器): 管理SpringBean对象。

    (1) IoC Core容器:管理Bean的机构。(2) IoC Bean:被管理的对象。

    (3) Context:  IoC容器的API:接口,类。(4) Spring EL语言:访问Bean的机制。

    2.切面模块: 将各个层对象的各个

    方法方法中的共同代码封装为切面类,再织入到代码原来的位置。

    (1)切面类(Aspect)

    (2)切面实现机制:Spring内置机制,AspectJ实现机制。

    3.数据访问模块:与各种持久层框架集成

    集中管理各个持久层对象的创建。

    (1)ORM模块:与HibernateJPA, Toplink等集成。(2)JDBC模块:封装JDBC操作。

    (3)OXM模块:实现JavaBeanXML映射。(4)事务处理模块:管理业务层事务处理。

    4.Web模块:实现VC层的模块。

    (1) Spring MVC模块(Pull模式)

    (2) Spring REST API模块(pull模式) 开发SPA(Single Page Application)应用

    (3) Spring WebSocket模块(push模式)

    【】Spring框架的引入

    1.Builder方式-----将需要的模块的jarcopy/WEB-INF/lib

    2.Maven模式-----将模块的依赖配置信息,copypom.xml

    【】Spring IoC容器

    1.概念:IoC容器是管理Bean的机制。2.功能:管理Bean对象:创建,注入,销毁。

    【】Spring IoC管理类的配置方式

    1. XML方式2.Java编程方式

    【】Spring IoC管理BeanXML方式

    1.创建XML文件(classpath)

    <?xml version="1.0" encoding="UTF-8"?>

    <beans xmlns="http://www.springframework.org/schema/beans"

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

       <bean id="departmentService" class="com.city.oa.service.impl.DepartmentServiceImpl">  

             </bean>

    2.使用<bean>完成Bean的配置

     <bean id="beanid"  class="类全名" />

    【】取得Spring IoC管理Bean对象

    1.连接到SpringIoC容器

     ApplicationContext ac=new ClassPathXmlApplicationContext("context.xml");

    2.取得管理的Bean对象

    IDepartmentService ds02=ac.getBean("departmentService". IDepartmentService.class);

    3.调用对象的方法

    ds.add(xxx);

    02Spring Bean管理和依赖注入

    【】Java对象的取得方式

    1.直接主动创建式-------IA a=new A1();IA a=new A2();

    2.间接主动创建式-------IA a=Factory.createA();

    3.间接主动查找式-------IA a=(IA)ctx.lookup("jndiA");

    4.间接被动注入式 -IoC(*)

    protected void doGet(HttpServletRequest request,

    HttpServletResponse response)

     {

    }

    【】IoC概念

    IoCInversion of Control)反向控制

    对象的取得由其他机构创建并送给需要的对象。

    【】DI概念

    DI- Dependency Injection 依赖注入

    一个对象使用另一个对象,通过方法参数的取得,由其他对象负责注入。

    DIIoC的实现方式。

    Spring的核心是IoC容器。

    Spring 使用DI完成对象的注入。

    【】Spring完成对象的取得和配置方式

    1.使用new方式取得指定的对象。

    (1) XML方式

    <bean id="对象的ID"

               class="包名.类名" />

    案例:

    <bean id="departmentService"

    class="com.city.oa.service.impl.DepartmentServiceImpl">  </bean>

    (2)Java注解方式配置(*

    Spring提供多个注解类用于配置Bean的创建

    @Component:一般类前面            @Service:用于业务层类的前面

    @Repository:用于持久层类的前面     @Controller:用于控制层类的前面

    @RestController:用于REST API

    控制层类的前面(用于开发SPA

    案例:

    @Service("departmentService")

    public class DepartmentServiceImpl

    {}

    使用注解模式配置Spring Bean,需要设置Spring扫描的路径。

    <context:component-scan

    base-package="com.city.oa"/>

    2.使用静态工厂类取得对象

    (1) XML方式

    A a=Factory.createA();

    配置语法:

    <bean id="idxxx" class="工厂类全名"

       factory-method="工厂方法"

    />

    案例:

    SessionFactory sf=HibernateSessionFactory

    .createSessionFactory();

    XML配置代码:

    <!-- 通过静态工厂方法取得对对象 -->

    <bean id="sessionFactory"

          class="com.city.oa.factory.HibernateSessionFactory"

          factory-method="createSessionFactory"    

     />

    (2)注解方式

    3.动态工厂取得对象配置

    (1) XML

    <bean id="工厂id" class="工厂类全名" />

    <bean id="对象Id" factory-bean="工厂id"

        factory-method="非静态的工厂方法" />

    (2)注解方式

    4.JNDI查找对象的配置

    XML方式

    (1)通过Spring提供的JNDI工厂类查找指定

    的对象。

    <bean id="对象ID"

       class="...JndiObjectFactoryBean">

       <property name="jndiName" >

           <value>java:comp/env/cityoa</value>

       </property>

    </bean>

    5.DI注入模式:

    Spring支持2种方式实现DI注入。

    (1) Set方法注入

    (2)构造方法注入

    【】Spring Set方法实现DI注入

    1.定义依赖的类的对象属性变量。

    private SessionFactory sf=null;

    2.为依赖的属性变量创建set方法

    public void setSf(SessionFactory sf) {

    this.sf = sf;

    }

    3.实现Set方法的依赖注入配置:

    (1)XML方式

    <bean id="id" class="类全名">

        <property name="属性名"

        ref="依赖BeanID" />

    </bean>

    (2)注解方式

    (2)

    Spring03DI的实现与配置

    【】练习题

    1.根据要求写出完成如下任务的代码

    (1)XML方式配置取得类A的对象。(2)Java注解方式取得A的对象

    (3)XML方式取得工厂Factory静态 方法create创建的对象

    (4)XML方法取得工厂Factory动态方法create得到的对象

    (5)提高查找命名空间对象"cityoa"

    答:

    (1) <bean id="a" class="A" />

    (2)

        @Component

        public class A{}

    (3)<bean id="a" class="Factory"

          factory-method="create" />

    (4)<bean id="factory" class="Factory" />

         <bean id="a" factory-bean="factory"

           factory-method="create" />

    (5) <bean id="a" class="JndiObjectFactoryBean">

            <property name="jndiName">

                  <value>cityoa</value>

            </property>

          </bean>

    【】Spring DI的实现方式

    1.属性注入方式    2.构造方法注入方式

    【】Spring属性(Property)注入实现DI

    1.属性条件:

    (1)类变量       (2)提供getset方法

    2.XML方式:

    (1)语法:

       <bean id="id" class="类全名" >

           <property name="属性名" >

                注入的值

           </propery>

       </bean>

    (2).注入简单类型:

    <property name="属性">

       <value></value>

    </property>

    (3).注入对象类型:

    <1> 标准语法:

    <property name="ssf">

        <bean ref="sqlSessionFactory" />

    </property>

    <2>简化语法

    <property name="ssf"

     ref="sqlSessionFactory" />

    (4)注入集合对象

    3.Java注解方式实现属性注入

    (1)语法:使用@Autowiredset方法前。

     @Autowired

     public void setXxx(){}

    【】Spring使用构造方法实现DI

    1.前提条件:(1)定义注入的类变量    (2)定义构造方法传入注入变量

    2.XML方式注入DI对象

    语法:

    <bean id="" class="" >

        <constructor-arg ref="" />

    </bean>  

    3.Java注解方式实现构造方法DI注入

    @Autowired

    public 构造方法(DI参数){

    }

    Spring0405AOP编程

    【】AOP概念----------AOP=Aspect Oriented Programming

    面向切面编程。

    Aspect(切面)概念:就是多个类的多个方法中部分重复的代码。

    AOP的实质是指将重复的代码从多个类的多个方法中移动切面类中。

    【】AOP的基本元素(*

    1.Joinpoint(连接点):

      切面运行的位置。

       Spring AOP只支持普通方法的切入。

       方法前,方法后,方法前后,

       方法抛出异常后。

    2.Pointcut(切入点)

       相同位置的连接点的集合。

     切入点1:所有业务类add方法前。

     切入点2:所有业务类所有方法后。

    3.Advice(通知)

       切面的执行的代码。

    4.Aspect(切面)

       Aspect=Advice+Pointcut

    5.Target(目标)

       切面要切入的对象。

    6.Proxy(代理)

       Spring创建代理对象实现目标对象和切面对象的整合。

    7.Weaving(织入)

       SpringTargetAspect整合为Proxy 的过程称为织入。

    【】Spring Adivice的类型

    1.Before Advice: 方法前Advice

    2.After Returning Advice: 方法返回后Advice方法运行没有异常,正常返回。

    3.After Advice:方法后Advice 方法运行正常结束,或抛出异常结束。

    4.Around Advice: 方法前和后执行。

    5.After Throwing Advice:方法抛出异常后。

    【】Spring AOP的编程模式

    1. Advice接口模式+XML配置Spring 2.0之前使用此模式。

    2. POJO+XML

    POJO=Plain Old Java Object不实现任何接口,不继承任何父类。

    3.POJO+Annotation模式

    使用POJO类编写Advice,同时在Advice类上使用Spring AspectJ的注解类

    声明AdvicePointcut

    【】POJO+Annotation模式编写AOP

    1.Spring IoC容器配置中启用注解AspectJ模式

      <aop:aspectj-autoproxy />

    2.编写 POJO Advice

    3.增加切面注解:

       @Aspect

    4.增加Spring 扫描

       @Component

    案例:

    @Component

    @Aspect

    public class ServiceMethodAdvice {}

    【】编写方法前Advice方法

    (1)编写普通方法

    (2)方法前增加注解: @Before("切入点")

    案例:

    @Before(value="execution(* com.city.oa.service.impl.*.*(..))")

    public void serviceMethodBefore() throws Exception{

      System.out.println("方法前切面方法执行。。。");

    }

    【】编写方法返回后Advice方法:

    (1)定义普通方法

    (2)方法前增加@AfterReturning

    案例:

    @AfterReturning(value="execution

    (* com.city.oa.service.impl.*.*(..))")

    public void serviceMethodAfterReturning() throws Exception{

      System.out.println("方法返回后切面方法执行。。。");

    }

    【】编写方法后Advice

    (1)定义普通方法

    (2)方法前增加@After

    案例:

    @After(value="execution

    (* com.city.oa.service.impl.*.*(..))")

    public void serviceMethodAfter() throws Exception{

     System.out.println("方法后切面方法执行。。。");

    }

    05讲授课内容

    【】环绕Around Advice

    1.功能:对目标对象指定的方法 方法执行前和方法执行后分别切入 Advice代码。

    2.编程:在Advice方法前使用@Around

    @Around(value="切入点表达式")

    public Object  方法名(ProceedingJoinPoint pjp) throws Throwable{

        //方法前代码    

        Object result = pjp.proceed(); //调用目标对象方法

        //方法后代码

        return result;

    }

    案例:

    @Around(value="execution(* com.city.oa.service.impl.*.*(..))")

    public Object  serviceMethodAround(ProceedingJoinPoint pjp) throws Throwable{

    System.out.println("环绕Advice方法前....");

    Date start=new Date();

    Object result=pjp.proceed();

    Date end=new Date();

    long runtime=end.getTime()-start.getTime();

    System.out.println("目标方法执行时间:"+runtime+"毫秒");

    System.out.println("环绕Advice方法后....");

    return result;

    }

    案例:

    @Around(value="execution(* com.city.oa.service.impl.*WithAOP.*(..))")

    public Object  serviceTransactionAround(ProceedingJoinPoint pjp) throws Throwable{

    System.out.println("MyBatis环绕Advice方法前....");

    SqlSession session =ssf .openSession();

    IDepartmentDao dd=session.getMapper(IDepartmentDao.class);

    if(pjp.getTarget() instanceof DepartmentServiceImplWithAOP) {

    ((DepartmentServiceImplWithAOP)pjp.getTarget()).setDd(dd);

    }

    Object result=pjp.proceed();

    session.commit();

    session.close();

    System.out.println("MyBatis环绕Advice方法后....");

    return result;

    }

           

    【】方法异常捕获Exception ThrowAdvice

    1.功能:用于捕获目标对象方法抛出异常后的处理工作。

    2.编程:在Advice方法前使用

    @AfterThrowing注解类

    语法:

    @AfterThrowing(value="切入点"

    ,throwing="对象名")

    public void 方法名(JoinPoint jp,异常类型 对象名) throws Exception

    {

       处理代码

    }

    【】Advice方法参数

    1.JoinPoint::所有的Advice方法

    1个参数都可以是JoinPoint类型对象。

    该对象如下方法:

    getTarget(): 取得目标的对象。getSignature() 取得拦截的方法名。

    getArgs(): Object[]: 取得参数。getArgs()[getArgs().length-1]

    2.ProceedingJoinPoint:   环绕Advice方法必须使用此参数。

    【】Pointcut定义

    1.Pointcut的定义类型:

    (1)内嵌式定义

    @Around(value="execution(* com.city.oa.service.impl.*WithAOP.*(..))")

    (2)独立式定义

    单独定义切入点,在切面类中使用@Pointcut定义切入点。

    推荐:创建单独的切面类,只定义切入点方法。

    package com.city.oa.advice;

    import org.aspectj.lang.annotation.Aspect;

    import org.aspectj.lang.annotation.Pointcut;

    import org.springframework.stereotype.Component;

    //切入点类

    @Component

    @Aspect

    public class ServicePointcut {

    @Pointcut("execution(* com.city.oa.service.impl.*.*(..))")// the pointcut expression

    private void anyServiceMethon() {}

    @Pointcut("execution(* com.city.oa.service.impl.*AOP.*(..))")// the pointcut expression

    private void anyAOPServiceMethon() {}}

    引用定义好的切入点

    @Before(value="com.city.oa.advice.ServicePointcut.anyServiceMethon()")

    public void serviceMethodBefore() throws Exception{

    System.out.println("方法前切面方法执行。。。");

    }

    2.

    【】XML方式实现AOP配置

    Spring06Spring集成Hibernate

    【】Hibernate 编程

    1.读取配置信息://取得hibernate.properties

    Configuration cfg=new Configuration();

    //取得默认的XML配置文件:hibernate.cfg.xml

    cfg.configure();

    2.创建SessionFactory

    SessionFactory sf=cfg.buildSessionFactory();

    3.打开一个Session

    Session session=sf.openSession();

    4.开始一个事务

    Transaction tx=session.beginTransaction();

    5.这些CUDR操作

       session.save(pm);

       session.update(pm);

       session.delete(pm);

       ProductModel pm=session.get(id,ProductModel.class);

    6.提交事务

       tx.commit();

    7.关闭会话

       session.close();

    【】Spring集成Hibernate的管理

    1.管理数据库连接池

    2.管理SessionFactory创建,Spring内置Hibernate SessionFactory工厂类。

    3.Spring内置Hibernate事务管理器

    4.Spring内置事务处理配置自动有事务切面,可以配置到业务层。

    5.Spring自动打开Session,自动关闭Session 自动事务提交和回滚。

    【】Spring管理数据库连接池

    1.使用Spring内置的连接池框架(测试使用,生产环境不推荐使用)

    <bean id="ds01" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

      <property name="driverClassName">com.mysql.jdbc.Driver</property>

    <property name="url">jdbc:mysql://localhost:3306/cityoa</property>

       <property name="username">root</property>

      <property name="password">root</property>

      </bean>

    2.使用Apache DBCP框架

    <bean id="myDataSource"

    class="org.apache.commons.dbcp.BasicDataSource"

    destroy-method="close">

    <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>

    <property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/>

    <property name="username" value="sa"/>

    <property name="password" value=""/>

    </bean>

    3.使用C3P0框架配置连接池

    4.使用JavaEE配置的连接池

    <jee:jndi-lookup id="dsjndi"

    jndi-name="java:comp/env/cityoa"/>

    1. 使用Proxool连接池框架

    【】Spring配置HIbernateSessionFactory工厂Bean根据使用Hibernate版本的不同需要选择不同的SessionFactory工厂Bean案例使用HIbernate5的工厂Bean

    类型:org.springframework.orm.hibernate5.LocalSessionFactoryBean

    案例:

    <!-- 配置Hibernate SessionFactory工厂Bean -->

    <bean id="ssf" class=

    "org.springframework.orm.hibernate5.LocalSessionFactoryBean">

    <property name="dataSource" ref="ds01"/>

    <property name="packagesToScan">

    <list>

    <value>com.city.oa.model</value>

    </list>

    </property>

    <property name="hibernateProperties">

    <value>

    hibernate.dialect=org.hibernate.dialect.MySQLDialect

    hibernate.show_sql=true

    hibernate.format_sql=true

    </value>

    </property>

    </bean>

    【】配置Hibernate SessionFactory工厂Bean

    的主要属性

    1.dataSource: 指定数据源。

    <property name="dataSource" ref="ds01"/>

    2.mappingResources:指定XML映射文件

    <property name="mappingResources"><list>

    <value>product.hbm.xml</value></list>

    3.mappingDirectoryLocations:指定XML文件的路径

    <property name="mappingDirectoryLocations">

       <list>

          <value>com/city/oa/hr/model/xml

          <value>com/city/oa/sales/model/xml

        </list>

    </property>

    自动扫描 xxx.hbm.xml文件

    4.packagesToScan:

     指定注解Model类的扫描包

    <property name="packagesToScan">

       <list>

          <value>com.city.oa.model</value>

       </list>

    </property>

    【】配置Spring管理Hibernate事务管理器

    针对不同的Hibernate版本

    Spring提供了不同版本的事务管理器

    <bean id="transactionManager"

    class="org.springframework.orm.hibernate5.

    HibernateTransactionManager

    ">

    <property name="sessionFactory" ref="sessionFactory"/>

    </bean>

    【】Spring声明式事务切面的配置方式

    1.XML方式    2.Java Annotation方式

    【】Java Annotation方式

    1.Spring IoC配置文件中启用注解事务方式

    <tx:annotation-driven transaction-manager=

    "transactionManager"/>

    如果事务管理器的IDtransactionManager

    可以省略属性transaction-manager

    简写模式:<tx:annotation-driven />

    2.在需要事务管理的类上使用事务注解类

    @Transactional

    2

    Spring07Spring集成MyBatis

    【】Spring集成MyBatis的基本原理

    Spring管理数据库连接,

    Spring管理MyBatis SqlSessionFactory

    创建,

    Spring负责创建MyBatis DAO接口对象。

    Spring负责事务管理器。

    Spring负责业务层的事务切面。

    Spring负责创建业务对象,并将Dao接口

    注入到业务对象。

    【】Spring管理数据库连接

    Spring配置DataSource

    1)使用Spring内置的DataSource框架

    <!-- 使用Spring内置的连接池框架配置连接池 -->

    <bean id="ds01" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>

        <property name="url" value="jdbc:mysql://localhost:3310/cityoa"></property>

        <property name="username" value="root"></property>

       <property name="password" value="root"></property>

      </bean>

    【】Spring配置MyBatisSqlSessionFactory

    工厂Bean

    <!-- 配置MyBatis SqlSessionFactory -->

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

    <property name="dataSource" ref="dataSource"/>

    <property name="configLocation" value="classpath:mybatis-config-spring.xml"/>

    <property name="mapperLocations" value="classpath*:com/city/oa/dao/xml/*.xml" />

    <property name="typeAliasesPackage" value="com.city.oa.model" />

    </bean>

    主要属性:

    (1)dataSource:指定数据源

    (2)configLocation:指定MyBatis的配置文件

    (3)mapperLocations:指定映射文件

    (4)typeAliasesPackage

         指定别名的Model的包

    【】配置MyBatis的事务管理器

    Spring没有提供MyBatis的事务管理器。

    使用JDBC事务管理器

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

    <property name="dataSource" ref="dataSource" />

    </bean>

    【】启用Spring事务切面注解

    <!-- 启用注解事务声明 -->

    <tx:annotation-driven transaction-manager="transactionManager"/>

    【】配置Spring注册MyBatis DAO接口

    1.每次注册一个DAO接口(不推荐使用)

    <bean id="departmentDao" class="org.mybatis.spring.mapper.MapperFactoryBean">

      <property name="mapperInterface" value="com.city.oa.dao.IDepartmentDao" />

      <property name="sqlSessionFactory" ref="sqlSessionFactory" />

    </bean>

    每次只能注册一个Mapper接口。

    2.注册多个DAO接口-Bean方式

    <!-- 批量注册DAO接口 -->

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

       <property name="basePackage" value="com.city.oa.dao" />

       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />

    </bean>

    3.注册多个DAO接口-mybatis命名空间方式

    MyBatis-Spring新版提供了专门

    的命名空间<mybaits>

    Springcontext.xml文件中

    增加<mybatis>命名空间:

    xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"

    http://mybatis.org/schema/mybatis-spring

    http://mybatis.org/schema/mybatis-spring.xsd

    增加命名空间后,使用<mybatis>空间的属性

    <mybatis:scan base-package="org.mybatis.spring.sample.mapper" />

    Spring08Spring MVC

    【】MVC概念和组成部分职责

    1.MVCModel -View -Controller

    2.Model模型层的职责

    (1)表达业务数据: Model

    (2)持久化业务数据: DAO

    (3)模拟业务处理:Service

    3.View层职责

    (1)收集用户的输入信息:FORMFORM元素

    (2)显示用户需要的业务信息:

        列表模式,详细模式

    4.Controller层的职责

    (1)取得View收集的数据。

    String sage=request.getParameter("age");

    (2)验证数据的合法性

    使用正则表达式验证。

    (3)类型转换:String-int, double, Date

    int age=Integer.parseInt(sage);

    (4)组装Model对象

    EmployeeModel em=new EmployeeModel();

    em.setAge(age);

    ....

    (5)调用业务层方法实现业务处理

    Servlet取得业务层对象:

    ApplicationContext ac=new ClassPathXmlApplicationContext

    ("context.xml");

    IEmployeeService esaop=ac.getBean

    ("employeeServiceWithAOP",

    IEmployeeService.class);

    es.add(em);

    List list=es.getList();

    (6)传递View需要的数据

    request.setAttribute("list",list);

    (7)跳转到指定View对象(转发,重定向)。

    request.getRequestDispatcher("list.jsp").

    forwared(request,response);

    response.sendRedirect("tomain.do");

    【】Spring MVC概念

    Spring MVC是基于JavaEE

    VC层框架

    【】Spring MVC功能

    实现VC层的职责。

    【】Spring MVC引入

    Spring Web模块,Spring WebMVC模块

    【】Spring MVC组成

    1.前端核心控制器DispatcherServlet

       接收所有HTTP请求

       分配具体的控制器负责请求处理。

       根据结果类型实现结果处理(转发,重定向,

       生成XML,生成PDF,生成JSON)

    2.RequestMapping请求地址映射

    3.实际控制器Controller

       完成具体的控制功能。

    4.结果解析器:

       对控制器方法的返回结果进行解析

       生成结果类型。(重点:返回JSON

       REST API编程)

    【】Spring MVC前端控制器Dispatcher

    Servlet配置

    1./WEB-INF/web.xml配置

       Spring IOC的载入监听器

     <!-- Spring IoC容器XML位置参数 -->

      <context-param>

    <param-name>contextConfigLocation</param-name>

    <param-value>classpath:context.xml</param-value>

    </context-param>

     <!-- Spring IoC容器启动监听器 -->

    <listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

    </listener>

    2.配置Spring MVC的前端控制器

    <!-- Spring MVC的前端控制器 -->

    <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>*.mvc</url-pattern>

    </servlet-mapping>

    3.配置Spring MVCXML文件

    创建springmvc.xmlclasspath下。

    Spring MVC配置XML文件中:

    <!-- Spring MVC注解启用 -->

    <mvc:annotation-driven />

    【】编写Controller

    Spring MVC支持POJO模式的控制器类。

    1.编写POJO类。

    2.声明@Controller

    3.编写控制方法。

    4.为控制方法映射请求地址

       @RequestMapping("URI")

    Spring09Spring MVC控制器编程

    【】Controller的类型

    1.常规控制器:

       使用@Controller声明

       功能:主要是完成转发和重定向。

                  JSPJSTL协作。

    2.基于REST API的控制器:

       使用@RestController

       功能:直接向浏览器发送响应。

                  主要是JSON类型的响应。

       主要实现SPA应用。

       JSON结果需要引入Jackson框架类库。

       在自己的电脑上安装软件:Postman (64)

    Postman-win64-7.1.1-Setup.exe

    【】控制器方法

    Spring MVC的控制器方法没有特定的要求

    规范。

    方法名任意,方法参数类型众多。

    方法返回类型多种。

    根据业务需求自己确定参数和返回类型。

    【】方法的URI请求地址映射

    Spring MVC每个控制方法对应一个唯一的

    URI地址。

    URI:/oassm/department/add.jsp

    URL:http://localhost:8080/oassm/

             department/add.jsp

    URI地址使用@RequestMapping实现

    映射

    @RequestMapping语法:

    @RequestMapping(属性=,属性=,....)

    常用的属性:

    (1)value="uri": 指定URI地址,默认属性。

    (2)path="uri", value相同。

    (3)method={} 指定请求的方法

    method= {RequestMethod.POST,

    RequestMethod.GET}

    (4)params={} 指定包含的请求参数

      params={"userid","username"}

    (5)headers={} 指定包含的请求头

    headers={"User-Agent"}

    (6) consumes={} 指定请求的类型

    consumes={"application/json"}

    consumes={"multipart/form-data"}

    目前流行的Web框架:AngularVue.js

      React 都默认使用JSON请求。

      Bootstrap

    正常的表单请求:www.form-data

    <form action="add.mvc" >

    </form>

    文件上传的请求

    <form action="add.mvc" enctype="multipart/form-data" >

    </form>

    (7)produces={}指定响应的类型

    生成JSON响应:

    produces={"application/json"}

    produces={"image/jpeg"}

    【】控制器的方法参数

    Spring MVC控制器方法的参数支持多种类型。

    1.Model类对象:

       Spring MVC支持粗粒度数据。

       自动将请求参数转换为Model对象。

    2.Java常用类型:Stringint, double, Date

    使用细粒度方式接收单个数据。

    Spring MVC提供2种方式接收单个参数:

    (1)请求地址参数:

       <a href="list.mvc?rows=10&page=1" >下页</a>

    可以使用注解类:@RequestParam注解

    @RequestParam语法:

    @RequestParam(属性=,属性=)

    主要属性:required=true|false 强制与选项

    public List<DepartmentModel>

    getListWithPage(

    @RequestParam(required=false,

    defaultValue="2")  int rows,

    @RequestParam(required=false,

    defaultValue="1") int page)

    throws Exception{

    第11讲 Spring MVC处理文件上传与下载

    【】文件上传的实现机制

    1.表单的定义

    <form action="url" method="post"

        enctype="multipart/form-data" >

    </form>

    2.定义文件选择域:

    <input type="file" name="photo"  />

    3.提交的数据类型:

      请求体包含文本和二进制数据。

    4.服务器端接收时需要解析出

       文本和二进制数据。

    5.解析一般使用文件上传解析器。

    (1)JSPSmartUpload

    (2) Apache Common upload

    (3) JavaEE Server 内置的文件解析器

         Servlet3.1版本以上)

    【】Spring MVC实现文件上传的机制

    1.使用外部的文件上传框架

    (1)Apache Common upload

    (2)Servlet3.1以上的文件解析器

    2.Sping  MVC定义了Multipart数据的解析器

      Spring MVC Context配置文件中

       配置使用以上2个文件上传框架的解析器

    3.Spring MVC在接收到Mulitpart请求时

       自动交给解析器进行解析。

        解析的文本使用传统的方式接收。

        解析的文件使用MultipartFile接收

    4.通过MultipartFile的方法实现

       文件的处理。

    【】Spring MVC文件解析器的配置

    1.使用Apache Common Upload框架

    (1) 引入Common Upload JAR文件。

    (2) 引入common IO jAR

    (3)Spring MVC Context配置文件中

        配置使用upload的解析器

    <!-- 使用Apache Common Upload文件解析器 -->

    <bean id="commonUploadmultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <!-- one of the properties available; the maximum file size in bytes -->

    <property name="maxUploadSize" value="20000000"/>

    </bean>

    2.Servlet3.1文件上传解析器

    (1)web.xmlDispatcherServlet中配置

        启用Servlet3.1文件解析器

    <multipart-config>

    <max-file-size>20848820</max-file-size>

    <max-request-size>418018841</max-request-size>

    <file-size-threshold>1048576</file-size-threshold>

    </multipart-config>

    (2)Spring MVCContext配置文件中

    配置Servlet3.1文件上传解析器:

    参见书P391代码。

    【】Spring MVC控制器接收上传文件

    Spring MVC使用MultipartFile接收文件。

    1.单个文件:

    <input type="file" name="photo" >

    接收:

    定义变量:

    MultipartFile photo

    2.多个文件:

    <input type="file" name="photo" >

    <input type="file" name="photo" >

    <input type="file" name="photo" >

    接收:

    MultipartFile[] photo

    【】Spring MVC处理文件下载

    1.使用Servlet API编程

    通过在Controller类中引入Servlet API

    Response接口对象实现编程。

    1. 通过返回ResponseEntity<byte[]>

    Spring09_10Spring MVC控制器编程

    【】Controller的类型

    1.常规控制器:

       使用@Controller声明

       功能:主要是完成转发和重定向。

                  JSPJSTL协作。

    2.基于REST API的控制器:

       使用@RestController

       功能:直接向浏览器发送响应。

                  主要是JSON类型的响应。

       主要实现SPA应用。

       JSON结果需要引入Jackson框架类库。

       在自己的电脑上安装软件:Postman (64)

    Postman-win64-7.1.1-Setup.exe

    【】控制器方法

    Spring MVC的控制器方法没有特定的要求

    规范。

    方法名任意,方法参数类型众多。

    方法返回类型多种。

    根据业务需求自己确定参数和返回类型。

    【】方法的URI请求地址映射

    Spring MVC每个控制方法对应一个唯一的

    URI地址。

    URI:/oassm/department/add.jsp

    URL:http://localhost:8080/oassm/

             department/add.jsp

    URI地址使用@RequestMapping实现

    映射

    @RequestMapping语法:

    @RequestMapping(属性=,属性=,....)

    常用的属性:

    (1)value="uri": 指定URI地址,默认属性。

    (2)path="uri", value相同。

    (3)method={} 指定请求的方法

    method= {RequestMethod.POST,

    RequestMethod.GET}

    (4)params={} 指定包含的请求参数

      params={"userid","username"}

    (5)headers={} 指定包含的请求头

    headers={"User-Agent"}

    (6) consumes={} 指定请求的类型

    consumes={"application/json"}

    consumes={"multipart/form-data"}

    目前流行的Web框架:AngularVue.js

      React 都默认使用JSON请求。

      Bootstrap

    正常的表单请求:www.form-data

    <form action="add.mvc" >

    </form>

    文件上传的请求

    <form action="add.mvc" enctype="multipart/form-data" >

    </form>

    (7)produces={}指定响应的类型

    生成JSON响应:

    produces={"application/json"}

    produces={"image/jpeg"}

    【】控制器的方法参数

    Spring MVC控制器方法的参数支持多种类型。

    1.Model类对象:

       Spring MVC支持粗粒度数据。

       自动将请求参数转换为Model对象。

        如果接收JSON请求,

        需要使用注解类@RequestBody

    2.Java常用类型:Stringint, double, Date

    使用细粒度方式接收单个数据。

    Spring MVC提供 种方式接收单个参数:

    (1)请求地址参数:

       <a href="list.mvc?rows=10&page=1" >下页</a>

    可以使用注解类:@RequestParam注解

    @RequestParam语法:

    @RequestParam(属性=,属性=)

    主要属性:required=true|false 强制与选项

    public List<DepartmentModel>

    getListWithPage(

    @RequestParam(required=false,

    defaultValue="2")  int rows,

    @RequestParam(required=false,

    defaultValue="1") int page)

    throws Exception{}

    (2)URI中变量参数:

    语法: <a href="list/{rows}/{page}.mvc" >

    list/10/2.mvc

    Spring MVC使用注解@PathVariable("name")

    (3)请求头的参数:

    方法名(@RequestHeader("name") 参数)

    案例:

    @RequestMapping(value="/checkHeader")

    public String checkHeader(@RequestHeader("Content-Length") int length) throws Exception{

    System.out.println("长度:"+length);

    return "OK";

    }

    @RequestHeader("User-Agent") String browser

    (4)取得Cookie的值

    Spring MVC提供取得指定nameCookie的值

    @CookieValue("userid") String user

    add(@CookieValue("userid") String user) {

    }

    3.请求对象:HttpServletRequest

    一般情况下很少直接使用Request对象

    4.响应对象:HttpServletResponse

    当控制器发送图片等,可以使用响应对象。

    5.会话对象:HttpSession

    取得用户登录信息,需要使用会话对象。

    login(String id,String password, HttpSession session){

       

    }

    【】控制器方法的返回类型

    1.当使用REST Controller时,可以返回

    任何能转换为JSON的类型。

    普通的Controller使用@ResponseBody

    @RestController=@Controller+

                                 @ResponseBody

    2.使用传统的Controller时,

       一般返回String, 表示JSP的地址

      或者是控制器的地址。

      return "department/add";

      return "redirect:/department/tomain.mvc";

    【】SPA模式

    SPA-Single Page Application

    系统启动主页后,地址栏不改变。

    所有的子网页都是通过某种机制

    动态嵌入到主页中。

    jquery通过load方法。

    Angular通过组件组装。

    【】复习Jquery

    1.语法:

    (1)  $("选择器").函数(参数,.....);

    (2) $.函数(参数,.....);

    function(){

    $("div#leftmenu a").on("click",function(event){

    var href=$(this).attr("href");

    $("div#maincontent").load(href);

    event.preventDefault();

    });

    }

    【】定位器

    jquey使用CSS定位器

    1. 标记定位:

       a { font-size:40px};

       $("a").css("font-size","40px");

    2.ID定位器: <a  id="xxxx" ></a>

       $("a#xxxx").html("连接01");

    3.类定位器: <a  class="main" ></a<

       $("a.main").html("aaaa");

    4.子元素定位器:

    <div id="main"> <span></span></div>

      var info=  $("div#main span").html();

    【】jQuery常用的函数

    1.html(), html(参数);取得和设置标记的内容

    var info=  $("div#main span").html();

    $("div#main span").html("aaaa");

    2.attr("name"), attr("name","value")

    取得标记属性的值,

    或设置属性的值。

    3.on("事件名",function(){处理代码});

  • 相关阅读:
    Linux 添加环境变量
    postgresql 获取修改列的值
    5月30日周一上午
    周日5月29日
    2016年5月26日
    如何使用Gson(添加到项目里去)
    linux内核分析课程总结()待完善
    5月5日离散课笔记
    4月28日的离散课(还少了一部分)
    2016年4月29日
  • 原文地址:https://www.cnblogs.com/dys6/p/11304184.html
Copyright © 2020-2023  润新知