Spring AOP pass argument of a controller method

我怕爱的太早我们不能终老 提交于 2019-12-13 00:54:35

问题


I have a controller as follows

@Controller
@RequestMapping(value = "/")
public class HomeController {
    @RequestMapping("/")
    public String home(Map<String,Object> map) {
        map.put("val2","val2");
        return "mainpage"; //it is the jsp file name
    }
}

Now In my aspect class method I want to put another value in this map variable defined in the controller method

@Aspect
public class UserInfo {
    @Before("execution(* org.controller.HomeController(..)) ")
    public void m1(){
        //Map<String,Object> map
        // get the map here and add
        map.put("val1","val1);
    }
}

so that when i call this map form mainpage.jsp file I get both value as

${val1}
${val2}

How can I do this???


回答1:


You could use getArgs on JoinPoint to get the argument to the method like:

Object[] signatureArgs = joinPoint.getArgs();

Your m1 method should be like:

public void m1(JoinPoint joinPoint){

You already know that you just have on argument to the method, so you would need to type cast it to a map and then put your new values and call proceed method to proceed with further actual call.




回答2:


Actually SMA's solution is nice, but not very elegant and type-safe. How about binding the argument to a correctly typed and conveniently named argument right in the pointcut?

@Before("execution(* org.controller.HomeController.*(..)) && args(map)")
public void m1(Map<String, Object> map) {
    map.put("AspectJ", "magic");
}


来源:https://stackoverflow.com/questions/29326705/spring-aop-pass-argument-of-a-controller-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!