java - 从另一个 Controller 访问controlleradvice对象

标签 java spring spring-mvc

我有一个 @ControllerAdvice 类,我用它来设置整个应用程序中的用户配置文件信息。通过这种方式,我可以在每个 JSP 中获取用户配置文件。但是,我尝试像这样在 @Controller 中访问该对象,但没有成功:

@ControllerAdvice
public class CommonControllerAdvice {

    @ModelAttribute("PROFILE")
    public Profile populateUserProfile(HttpSession session){
        return (Profile) session.getAttribute("PROFILE");
    }
}


@Controller
public class ActivityController {

    @GetMapping("/view/activity/{id}")
    public ModelAndView getActivity(ModelAndView modelAndView, @PathVariable Integer id) {
        Profile profile = (Profile) modelAndView.getModel().get("PROFILE");
    ... ...
    }
}

但我只得到一个 NullPointerException 因为配置文件为空。但是,我知道它不是 null 因为我可以在相关的 JSP 中使用它。

最佳答案

我找到了解决方案。只需将 @ControllerAdvice 类中定义的 @ModelAttribute 作为参数传递,而不是尝试从 ModelAndView 中获取它。

@Controller
public class ActivityController{

   @GetMapping("/view/activity/{id}")
   public ModelAndView getActivity (
       ModelAndView modelAndView,
       @ModelAttribute Profile profile,
       @PathVariable Integer id) {
            //Profile object is well populated
            //However I don't understand why this model is empty
          ModelMap model = modelAndView.getModelMap();
          ...
   }
}

它解决了我的问题,我对此解决方案感到满意,尽管如此,我希望能够直接在 ModelMap 中访问此信息,但它是空的。我想知道为什么。

关于java - 从另一个 Controller 访问controlleradvice对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48720046/

相关文章:

java - Spring Boot 与 JAX-RS (ReSTLet) 的简单微服务对比

spring-mvc - spring MVC Controller 版本控制

Java Swing JScrollPane 按住 Shift 并使用鼠标滚轮时不滚动

java - 如何在java中的jxdatepicker中设置当前月份和年份(03-2014)作为默认值

java - 发生异常时,可选的 orElse() 无法返回替代值

java - 在 hibernate 中动态添加查询字符串中的表名

java - 如何解决java中的启动类型错误?

java - 检测 VirtualMachine.attach()/virtualMachine.loadAgent

java - 在 Spring Boot 中使用应用程序属性动态更改 bean

java - @min 注释不起作用