SpringMVC拦截Controller方法

9 篇文章 0 订阅

spring配置:

<?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:mvc="http://www.springframework.org/schema/mvc"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:aop="http://www.springframework.org/schema/aop"
   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/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        
      ">

<!-- 【启用springmvc注解驱动】 -->
<mvc:annotation-driven />

<!-- 使用cglib代理 -->
<aop:aspectj-autoproxy proxy-target-class="true"/>

<bean id="runAdvisor"
     class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
   <property name="advice">
      <bean class="com.**.api.web.interceptor.MyInterceptor"></bean>
   </property>
   <property name="mappedNames">
      <list>
         <value>getDetails</value><!-- 要拦截的方法,用*号匹配多个 -->
      </list>
   </property>
</bean>
<!-- 使用ProxyFactoryBean 产生代理对象 -->
<bean
      class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
   <property name="beanNames">
      <list>
               <!-- 注意:如果是Controller,首字母不要小写了 -->
         <value>MyController</value><!-- 要拦截的bean,可以用*号匹配多个。-->
      </list>
   </property>
   <property name="interceptorNames">
      <list>
         <value>runAdvisor</value>
      </list>
   </property>
</bean>


拦截处理类:

public class MyInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        if (条件判断) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("error", "失败返回");
            return jsonObject;
        }
        return methodInvocation.proceed();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值