从Spring AOP方面返回自定义HttpServletResponse不起作用

时间:2019-02-09 15:20:03

标签: java spring-boot spring-aop spring-annotations

我正在尝试实现一个简单的注释@RequiresLogin

package com.nonce.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiresLogin { }

这里是Aspect

package com.nonce.aspect;

import com.nonce.annotation.RequiresLogin;
import com.nonce.security.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Aspect
public class SecurityManager {

    @Around("@annotation(com.nonce.annotation.RequiresLogin) && args(request,..)")
    public Object authenticate(ProceedingJoinPoint proceedingJoinPoint, HttpServletRequest request) throws Throwable {
        System.out.println(request.getRequestURI());
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        if(!SecurityUtils.isLoggedIn(request)) {
            response.sendRedirect("/");
            return null;
        }
        else {
            return proceedingJoinPoint.proceed();
        }
    }
}

然后,我尝试在我的一个控制器中使用注释。

package com.nonce.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.nonce.timeplex.annotation.RequiresLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.nonce.security.SecurityUtils;
import com.nonce.utils.Constants;
import com.nonce.utils.URLStore;

@Controller
@RequestMapping(URLStore.INDEX)
public class ProfileController {

    @Autowired
    HttpSession session;

    @RequiresLogin
    @RequestMapping(value = URLStore.PROFILE, method = RequestMethod.GET)
    public String showProfile(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        SecurityUtils.injectCSRFToken(session);
        return Constants.PROFILE;
    }
}

在方法showProfile()中,当我删除参数HttpServletResponse response时,注解不起作用,尽管方法调用被拦截,但重定向不会发生。

我试图了解为什么会发生这种情况?有线索吗?

0 个答案:

没有答案