SpringMVC拦截Controller方法

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


<mvc:annotation-driven />


<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>getDetailsvalue>
      list>
   property>
bean>

<bean
      class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
   <property name="beanNames">
      <list>
               
         <value>MyControllervalue>
      list>
   property>
   <property name="interceptorNames">
      <list>
         <value>runAdvisorvalue>
      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();
    }
}

你可能感兴趣的:(java,spring)