小编典典

使用AspectJ的Spring MVC

jsp

我有一个正在工作的Spring MVC项目。我想使用AspectJ通过控制器记录每个请求。相关代码:

控制器:(在hu.freetime.controller包中)

@Controller
@RequestMapping("/")
public class BaseControllerImpl {
    @RequestMapping(method = RequestMethod.GET)
    public String index(Model model) {
        return "index";
    }
}

方面:

@Aspect
public class ControllerAspectImpl {
    Logger logger = LoggerFactory.getLogger(ControllerAspectImpl.class);

    @Pointcut("execution(public * hu.freetime.controller.BaseControllerImpl.*(..))")
    public void logController() {
    }


    @Around("logController()")
    public void log(final ProceedingJoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        logger.info("Calling Controller method: " + method.getName() + "()");
        try {
            pjp.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

WebAppInitializer:

public class CashflowWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { RootConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

WebConfig类:

@Configuration
@EnableWebMvc
@EnableAspectJAutoProxy
@ComponentScan(basePackages = { "hu.freetime.controller", "hu.freetime.aspect" })
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;
    }

    @Bean
    public ControllerAspectImpl getControllerAspect() {
        return new ControllerAspectImpl();
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

问题是,两个组件中只有一个正在工作。如果我“关闭” AOP,则MVC可以正常工作,但是当我“打开”并且要转到主页时,出现此错误:

HTTP Status 404 - .../WEB-INF/views/.jsp
The requested resource is not available.

奇怪的是,它要映射“ .jsp”而不是“
index.jsp”,就像我在Controller的index()方法中所写的那样。我在运行时进行调试,但它确实在控制器方法处停止。

我该如何运作?


阅读 279

收藏
2020-06-10

共1个答案

小编典典

Your around advice does not return the result of pjp.proceed(). That is the
return value of the advised method and must be returned by the advice!
Otherwise you are turning the advised method into a void as well.

public **Object** log(final ProceedingJoinPoint pjp) {
...
    try {
        **return** pjp.proceed(); <<< !
    } catch (Throwable e) {
        e.printStackTrace();
    }    
}
2020-06-10