ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

SpringMVC

2022-04-27 19:33:53  阅读:161  来源: 互联网

标签:事务 SpringMVC void Object AOP public out


SpringMVC

1、1:作用:类似于servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理

SpringMVC拦截器(interceptor)

Myinterceptors1.java

public class MyInterceptor1 implements HandlerInterceptor {
    @Override
    /**
     * 在目标方法执行之前执行
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("preHandle");
        return true;
    }

    @Override
    /**
     * 在目标方法执行之后视图返回之前执行
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override
    /**
     * 在整个流程执行完毕执行
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}

spring-mvc.xml

 	<!--配置拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/><!--对哪个资源执行拦截操作-->
            <bean class="cn.itcast.interceptor.MyInterceptor1"></bean>
        </mvc:interceptor>
        <mvc:interceptor>
            <mvc:mapping path="/**"/><!--对哪个资源执行拦截操作-->
            <bean class="cn.itcast.interceptor.MyInterceptor2"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

SpringMVC异常处理

简单异常处理器MVC自带的

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!--        <property name="defaultErrorView" value="error"/>-->
        <property name="exceptionMappings">
            <map>
                <entry key="java.lang.ClassCastException" value="error1"/>
                <entry key="cn.itcast.exception.MyException" value="error2"/>
            </map>
        </property>
    </bean>

自定义异常处理

resolver:分解器

public class MyExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {

        ModelAndView modelAndView = new ModelAndView();
        if(e instanceof MyException){
            modelAndView.addObject("info","自定义异常");
        }else if (e instanceof ClassCastException){
            modelAndView.addObject("info","类型转换异常");
        }
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

什么是AOP(面向切面编程)

oop->aop

作用:在程序运行期间,在不修改源码的情况下对方法进行功能增强

优势:减少代码重复,提高开发效率,并且便于维护

AOP动态代理技术

常用的动态代理技术

  • JDK代理:基于接口的动态代理技术

    缺点:必须要有接口

  • cglib代理:基于父类的动态代理技术(不需要接口,基于父类的)

AOP相关概念(P126)

  • Target
  • Proxy
  • Joinpoint
  • Pointcut(切入点)
  • Advice(通知/增强)
  • Asprct(切面)
  • Weaving(织入)

基于XML的AOP开发

开发明确事项:

  1. 谁是切点
  2. 谁是通知/增强
  3. 将切点和通知进行织入配置

知识要点:

将增强类引入spring

<bean id="myAspect" class="cn.itcast.proxy.aop.MyAspect"/>

通知:

  1. 前置通知
  2. 后置通知
  3. 环绕通知
  4. 异常抛出通知
  5. 最终通知

<aop:pointcut id="myPointcut" expression="execution(* cn.itcast.proxy.aop..(..))"/>抽取

execution(* cn.itcast.proxy.aop..(..)):【修饰符】 返回值类型 包名 类名 方法名(参数)

修饰符可以缺省

 <aop:config>
        <!--声明切面  告诉spring引入的类是增强方法-->
        <aop:aspect ref="myAspect">
            <aop:pointcut id="myPointcut" expression="execution(* cn.itcast.proxy.aop.*.*(..))"/>
            <!--切面=通知+切点表达式             pointcut:切点-->
<!--            <aop:before method="before" pointcut="execution(public void cn.itcast.proxy.aop.TargetInterfaceImpl.save())"></aop:before>-->
<!--        <aop:before method="before" pointcut="execution(* cn.itcast.proxy.aop.*.*(..))"/>-->
<!--        <aop:after-returning method="afterReturning" pointcut="execution(* cn.itcast.proxy.aop..*.*(..))"/>-->
<!--        -->
            <aop:around method="around" pointcut-ref="myPointcut"/>
<!--        <aop:after-throwing method="afterThrowing" pointcut="execution(* cn.itcast.proxy.aop.*.*(..))"/>-->
        <aop:after method="after" pointcut-ref="myPointcut"/>
        </aop:aspect>
    </aop:config>
    //环绕
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕前...");
        //切点方法
        Object proceed = pjp.proceed();

        System.out.println("环绕后");
        return proceed;
    }

基于注解的AOP开发

1、创建目标接口和目标类(内部有切点)

2、创建切面类(内部有增强方法)

3、将目标类和切面类的对象创建权交给spring

4、在切面类中使用注解配置织入关系

5、在配置文件中开启组件扫描和AOP的自动代理

6、测试

事务控制

1、PlatformTransactionManager接口是spring的事务管理器,他里面提供了我们常用的操作事务的方法

TransactionStatus getTransaction(TransactionDefination defination):获取事务的状态信息

void commit(TransactionStatus status):提交事务

void rollback(TransactionStatus status):回滚事务

编程时事务控制相关对象

2、TransactionDefinition

1、事务隔离级别

设置隔离级别,可以解决事务并发产生的问题,如脏读,不可重复读,虚读

2、事务传播行为

ruquired:默认

supports:

mandatory

3、TransactionStatus

boolean hasSavepoint():是否存储回滚点

boolean isCompleted():事务是否完成

boolean isNewTransaction():是否是新事务

boolean isRollbackOnly():事务是否回滚

基于XMl的声明式事务控制

案例

AccountController层

  public static void main(String[] args) {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = app.getBean(AccountService.class);
        accountService.transfer("tom","lucy",500);
    }

service层

  public void transfer(String outMan, String inMan, double money) {

        accountDao.out(outMan,money);
        int i=1/0;
        accountDao.in(inMan,money);


    }

applicationContext.xml

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/>
        <property name="user" value="root"/>
        <property name="password" value="123456"/>
    </bean>

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

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

    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>
    <!--配置平台事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--通知 事务的增强-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--设置事务的属性信息-->
        <tx:attributes>
            <tx:method name="*"/>
        </tx:attributes>

    </tx:advice>

    <!--配置事务的aop的织入-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.itheima.service.impl.*.*(..))"/>
    </aop:config>

<tx:advice id="txAdvice" transaction-manager="transactionManager">

tx:attributes
<tx:method name="*"/>
</tx:attributes>

https://blog.csdn.net/qq_37272886/article/details/88638575

1647867250852

标签:事务,SpringMVC,void,Object,AOP,public,out
来源: https://www.cnblogs.com/IsMhhla/p/16200215.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有