第五次总结

第五次总结


所学内容:

spring第三天

5.2.切入点表达式的写法

<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop.xsd">

<!--    配置spring的Ioc,把service对象配置进去-->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>

<!--    spring中基于XML的AOP配置步骤
        1.把通知Bean也交给spring来管理
        2.使用aop:config标签开始AOP的配置
        3.使用aop:aspect标签表明配置切面
                id属性:是给切面提供一个唯一的标识
                ref属性:是指定通知类bean的id
        4.在aop:aspect标签的内部使用对应标签来配置通知的类型
                让printLog方法在切入点方法执行之前执行,所以是前置通知
                aop:before:表示配置前置通知
                    method属性:用于指定Logger类中哪个方法是前置通知
                    pointcut属性:用于指定切入点表达式,该表达式的含义指的是对业务层中哪些方法增强
                切入点表达式的写法:
                    关键字:execution(表达式)
                    表达式:
                        访问修饰符   返回值 包名.包名....类名.方法名(参数列表)
                标准表达式写法:
                    public void com.itheima.service.impl.AccountServiceImpl.saveAccount()
                访问修饰符可以省略
                    void com.itheima.service.impl.AccountServiceImpl.saveAccount()
                返回值可以使用通配符,表示任意返回值
                    * com.itheima.service.impl.AccountServiceImpl.saveAccount()
                包名可以使用通配符,表示任意包,但是有几级包就需要写几个*.
                    * *.*.*.*.AccountServiceImpl.saveAccount()
                包名可以使用..表示当前包及其子包
                    * *..AccountServiceImpl.saveAccount()
                类名和方法名都可以使用*来实现通配
                    * *..*.*()
                参数列表:
                    可以直接写数据类型
                        基本类型直接写名称           int
                        引用类型写包名.类名的方式     java.lang.String
                    可以使用通配符表示任意类型,但必须有参数
                    可以使用..表示有无参数均可,有参数或者多个参数都可以
                全通配写法
                    * *..*.*(..)

                实际开发中切入点表达式的通常写法
                    切到业务层实现类的所有方法
                        * com.itheima.service.impl.*.*(..)
        -->


<!--    配置Logger类-->
    <bean id="Logger" class="com.itheima.utils.Logger"></bean>
<!--    配置AOP-->
    <aop:config>
        <aop:aspect id="logAdvice" ref="Logger">
<!--            配置通知的类型,并且建立通知方法和切入点方法的关联-->
            <aop:before method="printLog" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:before>
        </aop:aspect>
    </aop:config>

</beans>

5.3.aop:pointcut

<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop.xsd">

<!--    配置spring的Ioc,把service对象配置进去-->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>




<!--    配置Logger类-->
    <bean id="Logger" class="com.itheima.utils.Logger"></bean>
<!--    配置AOP-->
    <aop:config>
        <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.saveAccount(..))"/>
        <aop:aspect id="logAdvice" ref="Logger">
<!--            配置前置通知,在切入点方法执行之前执行-->
            <aop:before method="beforePrintLog" pointcut-ref="pt1"></aop:before>
<!--            配置后置通知,在切入点方法正常执行之后执行,它和异常通知永远只能执行一个-->
            <aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>
<!--            配置异常通知,在切入点方法执行产生异常后执行-->
            <aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>
<!--            配置最终通知,无论切入点方法是否正常执行,它都会在后面执行-->
            <aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>
<!--            配置切入点表达式,id属性用于指定表达式的唯一标识。expression属性用于指定表达式内容
                此标签写在aop:aspect标签内部,只能当前标签使用。
                它还可以写在aop:aspect外面,此时就变成了所有切面可用。放在外面时必须放在aspect标签前面-->
        </aop:aspect>


    </aop:config>

</beans>

5.4.环绕通知

/**
 * 环绕通知
 * 问题:当配置了环绕配置之后,切入点方法没有执行,而通知方法执行了
 * 分析:
 *      通过对比动态代理中的环绕通知代码。发现动态代理中的环绕通知,有明确的切入点方法调用。而我们的代码中没有。
 * 解决:
 *      spring框架为我们提供了一个接口,ProceedingJoinPoint。该接口有一个方法proceed(),此方法就相当于明确调用切入点方法。
 *      该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用
 *
 * spring中的环绕通知
 *      它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式
 *
 */
public Object aroundPrintLog(ProceedingJoinPoint pjp){
    Object rtValue = null;
    try {
        Object [] args = pjp.getArgs();//得到方法执行所需要的参数
        System.out.println("Logger类中的aroundPrintLog方法开始记录日志了--前置");
        rtValue = pjp.proceed();//明确调用业务层方法(切入点方法)
        System.out.println("Logger类中的aroundPrintLog方法开始记录日志了--后置");

        return rtValue;
    } catch (Throwable e) {
        System.out.println("Logger类中的aroundPrintLog方法开始记录日志了--异常");
        throw new RuntimeException(e);
    } finally {
        System.out.println("Logger类中的aroundPrintLog方法开始记录日志了--最终");

    }

5.5.注解

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

<!--    配置spring创建容器时要扫描的包-->
    <context:component-scan base-package="com.itheima"></context:component-scan>

<!--    配置spring开启注解AOP的支持-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>


</beans>

使用注解时,通知执行的顺序可能会有问题,推荐使用环绕通知

5.2.8版本修复了这个bug 所以注解aop可以正常执行

spring第四天

1.spring中的JdbcTemplate

​ JdbcTemplate的作用:
​ 它就是用于和数据库交互的,实现对表的CRUD操作

2.spring基于AOP的事务控制

3.spring中的事务控制

​ 基于XML的
​ 基于注解的

明确

​ 第一:JavaEE体系进行分层开发,事务处理位于业务层,spring提供了分层设计业务层的事务处理解决方案。
​ 第二:spring框架为我们提供了一组事务控制的接口。spring-tx-5.3.7.jar中。
​ 第三:spring的事务控制都是基于AOP的,它既可以使用编程方式实现,也可以使用配置的方式实现。我们学习的重点是使用配置的方式实现。

1.PlatformTransaction

​ 接口PlatformTransaction,开发中都是用它的实现类

真正管理事务的对象
org.springframework.jdbc.datasource.DataSourceTransactionManager :使用 Spring JDBC 或 iBatis 进行持久化数据时使用
org.springframework.orm.hibernate5.HibernateTransactionManager :使用 Hibernate 版本进行持久化数据时使用

2.TransactionDefinition

​ 它是事务的定义信息对象,里面有如下方法。

​ 获取事务对象名称
​ String getName()

​ 获取事务隔离级别
​ int getIsolationLevel()

​ 获取事务传播行为:增删改必须有事务,查可有可没有
​ int getPropagationBehavior()

​ 获取事务超时时间
​ int getTimeout()

​ 获取事务是否只读
​ boolean isReadOnly()

3.spring基于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: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/tx
  http://www.springframework.org/schema/tx/spring-tx.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop.xsd">

<!--    配置业务层-->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

<!--    配置账户的持久层-->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

<!--    配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql:///spring"></property>
        <property name="username" value="root"></property>
        <property name="password" value="0103"></property>
    </bean>

<!--    spring基于XML的声明式事务管理器配置步骤
        1.配置事务管理器
        2.配置事务的通知:
            此时我们要导入事务的约束,tx的名称空间和约束,同时也需要aop的
            使用tx:advice标签配置事务通知
                属性:
                    id:给事务通知起一个唯一标识
                    transaction-manager:给事务通知提供一个事务管理器引用
        3.配置AOP中的通用切入点表达式
        4.建立事务通知和切入点表达式的对应关系
        5.配置事务的属性
            是在事务的通知tx:advice标签的内部
-->
<!--    配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
<!--    配置事务的通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--        配置事务的属性
                isolation:用于指定事务的隔离级别,默认值是DEFAULT,表示使用数据库的隔离级别。
                propagation:用于指定事务的传播行为,默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS。
                read-only:用于指定事务是否只读,只有查询方法才能设置为true,默认值是false,表示可写
                timeout:用于指定事务的超时时间,默认值是-1,表示永不超时,如果指定了该数值,一秒为单位。
                roll-back-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚,没有默认值,表示任何异常都回滚。
                no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回滚,没有默认值,表示任何异常都回滚。


-->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>

<!--    配置aop-->
    <aop:config>
<!--        配置切入点表达式-->
        <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"></aop:pointcut>
<!--        建立切入点表达式和事务通知的对应关系-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>

    </aop:config>


</beans>

4.spring基于注解的声明式事务控制

​ 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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
  http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context.xsd">

<!--    配置业务层-->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">

    </bean>
<!--    配置spring创建容器时要扫描的包-->
    <context:component-scan base-package="com.itheima"></context:component-scan>

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

<!--    配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql:///spring"></property>
        <property name="username" value="root"></property>
        <property name="password" value="0103"></property>
    </bean>

<!--    spring基于注解的声明式事务控制配置步骤
            1.配置事务管理器
            2.开启spring对注解事务的支持
            3.在需要事务支持的地方使用@Transactional注解
-->
<!--    配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

<!--    开启spring对注解事务的支持-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>


</beans>

​ service

package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 账户的业务层实现类
 *
 * 事务控制应该都是在业务层
 */
@Service("accountService")
@Transactional(propagation= Propagation.SUPPORTS,readOnly = true)//只读型事务的配置
public class AccountServiceImpl implements IAccountService{

    @Autowired
    private IAccountDao accountDao;



    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);

    }


    //需要的是读写型事务配置
    @Transactional(propagation=Propagation.REQUIRED,readOnly=false)
    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("transfer....");
            //2.1根据名称查询转出账户
            Account source = accountDao.findAccountByName(sourceName);
            //2.2根据名称查询转入账户
            Account target = accountDao.findAccountByName(targetName);
            //2.3转出账户减钱
            source.setMoney(source.getMoney()-money);
            //2.4转入账户加钱
            target.setMoney(target.getMoney()+money);
            //2.5更新转出账户
            accountDao.updateAccount(source);

            int i=1/0;

            //2.6更新转入账户
            accountDao.updateAccount(target);
    }
}

SpringMVC

第一天

1.SpringMVC执行流程

  1. 当启动Tomcat服务器的时候,因为配置了load-on-startup标签,所以会创建DispatcherServlet对象, 就会加载springmvc.xml配置文件 2. 开启了注解扫描,那么HelloController对象就会被创建 3. 从index.jsp发送请求,请求会先到达DispatcherServlet核心控制器,根据配置@RequestMapping注解 找到执行的具体方法 4. 根据执行方法的返回值,再根据配置的视图解析器,去指定的目录下查找指定名称的JSP文件 5. Tomcat服务器渲染页面,做出响应
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LXzrt0js-1626782467310)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\image-20210720102058615.png)]

2.涉及的组件

2.1 DispatcherServlet:前端控制器

用户请求到达前端控制器,它就相当于 mvc 模式中的 c,dispatcherServlet 是整个流程控制的中心,由 它调用其它组件处理用户的请求,dispatcherServlet 的存在降低了组件之间的耦合性。

2.2 HandlerMapping:处理器映射器

HandlerMapping 负责根据用户请求找到 Handler 即处理器,SpringMVC 提供了不同的映射器实现不同的 映射方式,例如:配置文件方式,实现接口方式,注解方式等。

2.3 Handler:处理器

它就是我们开发中要编写的具体业务控制器。由 DispatcherServlet 把用户请求转发到 Handler。由 Handler 对具体的用户请求进行处理。

2.4 HandlAdapter:处理器适配器

通过 HandlerAdapter 对处理器进行执行,这是适配器模式的应用,通过扩展适配器可以对更多类型的处理 器进行执行。

2.5 View Resolver:视图解析器

View Resolver 负责将处理结果生成 View 视图,View Resolver 首先根据逻辑视图名解析成物理视图名 即具体的页面地址,再生成 View 视图对象,最后对 View 进行渲染将处理结果通过页面展示给用户。

2.6 View:视图

SpringMVC 框架提供了很多的 View 视图类型的支持,包括:jstlView、freemarkerView、pdfView 等。我们最常用的视图就是 jsp。 一般情况下需要通过页面标签或页面模版技术将模型数据通过页面展示给用户,需要由程序员根据业务需求开 发具体的页面。

3.mvc:annotation-driven

在 SpringMVC 的各个组件中,处理器映射器、处理器适配器、视图解析器称为 SpringMVC 的三大组件。 使 用 mvc:annotation-driven 自动加载 RequestMappingHandlerMapping (处理映射器) 和 RequestMappingHandlerAdapter ( 处 理 适 配 器 ) , 可 用 在 SpringMVC.xml 配 置 文 件 中 使 用mvc:annotation-driven 替代注解处理器和适配器的配置。

4.常用注解

4.1.@RequestMapping

作用: 用于建立请求 URL 和处理请求方法之间的对应关系。

出现位置:
类上:
请求 URL 的第一级访问目录。此处不写的话,就相当于应用的根目录。写的话需要以/开头。
它出现的目的是为了使我们的 URL 可以按照模块化管理:
例如:
账户模块:
/account/add
/account/update
/account/delete

订单模块:
/order/add
/order/update
/order/delete
红色的部分就是把 RequsetMappding 写在类上,使我们的 URL 更加精细。
方法上:
请求 URL 的第二级访问目录。
属性:
value:用于指定请求的 URL。它和 path 属性的作用是一样的。
method:用于指定请求的方式。
params:用于指定限制请求参数的条件。它支持简单的表达式。要求请求参数的 key 和 value 必须和
配置的一模一样。
例如:
params = {“accountName”},表示请求参数必须有 accountName
params = {“moeny!100”},表示请求参数中 money 不能是 100。
headers:用于指定限制请求消息头的条件。
注意:
以上四个属性只要出现 2 个或以上时,他们的关系是与的关系。

4.2.@RequestParam

/*@RequestParam
作用:把请求中指定名称的参数给控制器中的形参赋值

属性:
      value|name:请求参数中的名称。
       required:请求参数中是否必须提供此参数。默认值:true。表示必须提供,如果不提供就会报错
       */
    @RequestMapping(path="/testRequestParam")
    public String testRequestParam(@RequestParam(name="username") String name){
        System.out.println("执行了");
        System.out.println(name);
        return "success";
    }

4.3.RequestBody:json有用

/*@RequestBody
作用:
    用于获取请求体内容,直接使用得到是key=value&key=value...结构的数据
    get请求方式不适用
属性:
    required:是否必须有请求体,默认值是true。
    当取值是true时,get请求方式会报错,如果取值为false时,get请求得到的是null
*/

@RequestMapping(path="/testRequestBody")
    public String testRequestBody(@RequestBody String body){
        System.out.println("执行了");
        System.out.println(body);
        return "success";
    }

4.4.PathVariable

restful编程风格

/*
作用:
用于绑定 url 中的占位符。例如:请求 url 中 /delete/{id},这个{id}就是 url 占位符。
url 支持占位符是 spring3.0 之后加入的。是 springmvc 支持 rest 风格 URL 的一个重要标志。
属性:
value:用于指定 url 中占位符名称。
required:是否必须提供占位符。
*/
@RequestMapping(path="/testPathVariable/{sid}",method= RequestMethod.PUT)
    public String testPathVariable(@PathVariable("sid") String id){
        System.out.println("执行了");
        System.out.println(id);
        return "success";
    }
4.4.1.HiddentHttpMethodFilter
/*作用: 
由于浏览器 form 表单只支持 GET 与 POST 请求,而 DELETE、PUT 等 method 并不支持,Spring3.0 添
加了一个过滤器,可以将浏览器请求改为指定的请求方式,发送给我们的控制器方法,使得支持 GET、POST、PUT 
与 DELETE 请求。
使用方法: 
第一步:在 web.xml 中配置该过滤器。
第二步:请求方式必须使用 post 请求。
第三步:按照要求提供_method 请求参数,该参数的取值就是我们需要的请求方式。*/

4.5.RequestHeader

/*
作用:
用于获取请求消息头。
属性:
value:提供消息头名称
required:是否必须有此消息头
注:
在实际开发中一般不怎么用。
*/

4.6.CookieValue

/*
作用:
用于把指定 cookie 名称的值传入控制器方法参数。
属性:
value:指定 cookie 的名称。
required:是否必须有此 cookie。
*/

4.7.ModelAttribute

/*
作用:
该注解是 SpringMVC4.3 版本以后新加入的。它可以用于修饰方法和参数。
出现在方法上,表示当前方法会在控制器的方法执行之前,先执行。它可以修饰没有返回值的方法,也可
以修饰有具体返回值的方法。
出现在参数上,获取指定的数据给参数赋值。
属性:
value:用于获取数据的 key。key 可以是 POJO 的属性名称,也可以是 map 结构的 key。
应用场景:
当表单提交数据不是完整的实体类数据时,保证没有提交数据的字段使用数据库对象原来的数据。
例如:
我们在编辑一个用户时,用户有一个创建信息字段,该字段的值是不允许被修改的。在提交表单数
据是肯定没有此字段的内容,一旦更新会把该字段内容置为 null,此时就可以使用此注解解决问题。
*/

 /*@RequestMapping("/testModelAttribute")
    public String testModelAttribute(User user){
        System.out.println("testModelAttribute执行了");
        System.out.println(user);
        return "success";
    }*/

    @RequestMapping("/testModelAttribute")
    public String testModelAttribute(@ModelAttribute("abc") User user){
        System.out.println("testModelAttribute执行了");
        System.out.println(user);
        return "success";
    }

    /*
     * 该方法会先执行
     */
    /*@ModelAttribute
    public User showUser(String name){
        System.out.println("showUser执行了");
        //通过用户名查询数据库
        User user = new User();
        user.setName(name);
        user.setAge(20);
        user.setDate(new Date());
        return user;
    }*/

    @ModelAttribute
    public void showUser(String name, Map<String,User> map){
        System.out.println("showUser执行了");
        //通过用户名查询数据库
        User user = new User();
        user.setName(name);
        user.setAge(20);
        user.setDate(new Date());
        map.put("abc",user);
    }

4.8.SessionAttributes

/*
作用:
用于多次执行控制器方法间的参数共享。
属性:
value:用于指定存入的属性名称
type:用于指定存入的数据类型。
*/


package com.itcast.controller;

import com.itcast.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/*
  常用的注解

  @RequestParam
  作用:把请求中指定名称的参数给控制器中的形参赋值

  属性:
  		value|name:请求参数中的名称。
  	    required:请求参数中是否必须提供此参数。默认值:true。表示必须提供,如果不提供就会报错

    @RequestBody
    作用:
        用于获取请求体内容,直接使用得到是key=value&key=value...结构的数据
        get请求方式不适用
    属性:
        required:是否必须有请求体,默认值是true。
        当取值是true时,get请求方式会报错,如果取值为false时,get请求得到的是null


 */
@Controller
@RequestMapping(path="/anno")
@SessionAttributes(value = {"msg"})//把msg=美美存入到session域对象中
public class AnnoController {


    /**
     * 在request域中存取值
     * @return
     */
    @RequestMapping("/testSessionAttributes")
    public String testSessionAttributes(Model model){
        System.out.println("testSessionAttributes");
        //底层会存储到request域对象中
        model.addAttribute("msg","美美");

        return "success";
    }

    /**
     * 取值
     * @param model
     * @return
     */
    @RequestMapping("/getSessionAttributes")
    public String getSessionAttributes(Model model){
        System.out.println("getSessionAttributes");
        Object msg = model.getAttribute("msg");
        System.out.println(msg);
        return "success";
    }

    /**
     * 清空
     * @param status
     * @return
     */
    @RequestMapping("/delSessionAttributes")
    public String delSessionAttributes(SessionStatus status){
        System.out.println("delSessionAttributes");
        status.setComplete();
        return "success";
    }

}

5.post中文乱码

web.xml中配置过滤器

<!--  配置解决中文乱码的过滤器-->
  <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>

6.自定义数据类型转换器

<!--    配置自定义类型转换器-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.itcast.utils.StringToDateConverter"></bean>
            </set>
        </property>
    </bean>


<!--    开启SpringMVC框架注解的支持-->
    <mvc:annotation-driven  conversion-service="conversionService"></mvc:annotation-driven>

7.在控制器中使用原生的ServletAPI对象

只需要在控制器的方法参数定义HttpServletRequest和HttpServletResponse对象

8.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>入门程序</h3>

<%--    <a href="hello">入门程序</a>--%>

<%--    <a href="param/testParam?username=hehe&password=123">RequestMapping注解</a>--%>
<%--        把数据封装到Account类中--%>
    <%--<form action="param/saveAccount" method="post">
        姓名:<input type="text" name="username">
        密码:<input type="text" name="password">
        金额:<input type="text" name="money">
        用户姓名:<input type="text" name="user.name">
        用户年龄:<input type="text" name="user.age">
        <input type="submit" value="提交">
    </form>--%>

<%--    把数据封装到Account类中,类中存在List和map的集合--%>
    <%--<form action="param/saveAccount" method="post">
        姓名:<input type="text" name="username">
        密码:<input type="text" name="password">
        金额:<input type="text" name="money">
        用户姓名:<input type="text" name="list[0].name">
        用户年龄:<input type="text" name="list[0].age">

        用户姓名:<input type="text" name="map['one'].name">
        用户年龄:<input type="text" name="map['one'].age">
        <input type="submit" value="提交">
    </form>--%>

<%--    自定义类型转换--%>
    <%--<form action="param/saveUser" method="post">
        用户姓名:<input type="text" name="name">
        用户年龄:<input type="text" name="age">
        用户生日:<input type="text" name="date">
        <input type="submit" value="提交">
    </form>--%>

        <a href="param/testServlet">Servlet原生的API</a>

</body>
</html>

9.@Controller

@Controller用于标记在一个类上,使用它标记的类就是一个SpringMvc Controller对象,分发处理器会扫描使用该注解的类的方法,并检测该方法是否使用了@RequestMapping注解。
@Controller只是定义了一个控制器类,而使用@RequestMapping注解的方法才是处理请求的处理器。
@Controller标记在一个类上还不能真正意义上说它就是SpringMvc的控制器,应为这个时候Spring还不认识它,这个时候需要把这个控制器交给Spring来管理

有两种方式可以管理:

<!--基于注解的装配-->
<!--方式一-->
<bean class="com.HelloWorld"/>
<!--方式二-->
<!--路径写到controller的上一层-->
<context:component-scan base-package="com"/>

10.视图解析器

<!-- 视图解析器    视图解析器可以根据方法的返回值,自动的拼接最终的viewName数据.
	viewName= prefix + 服务方法返回值 + suffix
	/WEB-INF/pages/+ ok + .jsp -> /jsp/ok.jsp

              前后缀的使用限制: 不能处理带有forward|redirec前缀的方法返回值.

              前后缀只能处理请求转发,不能处理响应重定向的字符串返回结果.

      -->

     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

              <property name="prefix"value="/WEB-INF/pages/"/>

              <property name="suffix"value=".jsp"/>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值