問題
@[java] @[代碼] @[巧妙]
Spring被譽(yù)為Java Web程序員的春天,絕非浮夸。
打開spring的源代碼我們會發(fā)現(xiàn)他使用了大量的AOP,面向切面編程。
這一次,項(xiàng)目中需要用來解決前端傳參的類型匹配問題,所以使用了AOP。
如果我們用Spring的攔截器的話,就會發(fā)現(xiàn)。request可以setAttribute但是不能setParameter,可能是為了安全考慮,Spring不允許在攔截器中對前臺傳過來的參數(shù)做任何改動。
可是,如果真的有這個需求怎么辦呢?
解決方案
做準(zhǔn)備
- 導(dǎo)入spring-aop相關(guān)的包(百度一大把)
- 在applicationContext中做配置,我們使用注解的方式
<!-- 配置自動掃描的包 -->
<context:component-scan base-package="com.xxx" />
<!-- 激活自動代理功能 -->
<aop:aspectj-autoproxy proxy-target-class="true" />
- 在自動掃描的包內(nèi)新建一個類,類的頭上加入以下注解
@Component
@Aspect
@Order(10000) //order的值越小越優(yōu)先執(zhí)行
寫代碼
下面是類的代碼(假定我們要切的是所有配置了注解RequestMapping,并且方法名是create的方法)
@Component
@Aspect
@Order(10000) //order的值越小越優(yōu)先執(zhí)行
public class SecurityAspect {
@Autowired
private HttpServletRequest request; // 簡單的注入request
@Pointcut("execution(@org.springframework.web.bind.annotation.RequestMapping * *(..))")
public void aspect() {
}
@Around(value = "aspect() and execution(* create(..)))")
public Object aroundCreate(ProceedingJoinPoint joinPoint) throws Throwable {
Object[] params = joinPoint.getArgs();
params[0] = "只是被修改的值"; // 這里我們修改了第一個參數(shù)
return joinPoint.proceed(params);
}
}