spring aop,@PathVariable

在开发过程中想要页面根据用户所选语言显示不同的语言文字。

相关国际化技术: http://slnddd.iteye.com/admin/blogs/2339737

上篇文章使用的url形式是 127.0.0.1:8080/list?lang=en

但是总觉得不太好,想变换成restful风格的url  : 127.0.0.1:8080/en/list 这种

又因为想要在每个RequestMapping页面跳转的方法后,都能把当前的lang传递到前台,所以就想到了aop的形式。

@Aspect
@Component
public class ControllerInterceptor {
    //拦截前四个参数是 request,response,model,lang的requestMapping请求
    @Pointcut("execution(* com.xxxx.xxxx.xxxx.controller..*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)")  
    public void excute(){}
    
    @Around("excute() && args(request,response,model,lang,..)")
    public ModelAndView around(ProceedingJoinPoint joinPoint,HttpServletRequest request,HttpServletResponse response,ModelAndView model,String lang) throws Throwable {
        
        Object[] args = joinPoint.getArgs();
        joinPoint.getArgs()[3] = lang;
        joinPoint.proceed(args); 
        
        model.addObject("lang", lang);
        
        return model;
    }
    
}

   

//正则表达式形式
   @RequestMapping(value = "/{lang:en|zh}/list")
    public ModelAndView list(HttpServletRequest request,HttpServletResponse response,ModelAndView model,@PathVariable String lang) {
     
        model.setViewName("index");
        
        return model;
        
    }

 这种带参数的url 如果在没有 @PathVariable ,那么127.0.0.1:8080/en/list 这种形式,在aop那里获取是获取不到的,加上@PathVariable 就可以获取到了。

也就是说127.0.0.1:8080/{lang}/list 这种形式的,首先必须要传参数,不然直接就是404了,然后是需要使用@PathVariable

还有一点很奇怪的是String lang这种形式传递不过来,但是如果是对象类型的bean就可以传递进来了,是因为程序在执行的时候,发现是127.0.0.1:8080/{lang}/list这种类型的url时,首先会查找参数中是否有@PathVariable注解,如果有并且是同名的就进行赋值了,bean对象的话就是直接查找有同名的就进行赋值了

    

猜你喜欢

转载自slnddd.iteye.com/blog/2342103