2

I have a @Controller that has a @RequestMapping to map an endpoint to my jsp page. In that controller, I use a @ModelAttribute annotation to make a @Bean I have in my configuration file accessible in my jsp.

@Controller
public class WebPageController {

    @Autowired
    private MyBean myBean;

    @ModelAttribute
    public MyBean myBean() {
        return myBean;
    }

    @RequestMapping("/mypage")
    public String myPage() {
        return "myPage";
    }
}

In my config file, I have the @Bean, and an InternalResourceViewResolver.

@Configuration
@EnableWebMvc
@ComponentScan({"my.package"})
public class WebConfig extends WebMvcConfigurerAdapter {
    @Bean
    public MyBean myBean {
        return new MyBean();
    }

    @Bean
    public InternalResourceViewResolver getInternalResourceViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/pages/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}

This works fine and I can access myBean on my jsp page.

<script type="text/javascript">
    version = "${myBean.version}"
</script>

However, I want to move my controller into the Java Config. I can accomplish the same @RequestMapping using a ViewController in my WebConfig.

@Override
public void addViewControllers(final ViewControllerRegistry viewControllerRegistry) {
    viewControllerRegistry.addViewController("/myPage").setViewName("myPage");
}

Now, I need to add the myBean as a @ModelAttribute to be accessible on myPage.jsp. How can I do this in the Java Config?

EDIT: This is not a duplicate of this question. That shows how you would do it with xml configuration. I would like to know how to do it in my Java @Configuration file.

Community
  • 1
  • 1
Andrew Mairose
  • 10,615
  • 12
  • 60
  • 102
  • 1
    You won't be able to add model attributes through the controller registry. Instead, configure your `InternalResourceViewResolver` to expose beans to the JSP (through request attributes, which is equivalent to what happens to model attributes). – Sotirios Delimanolis Oct 28 '15 at 16:04
  • @Boann and OP, the answer is that you need to configure the `InternalResourceViewResolver`. Whether you do it in XML or Java makes no difference. – Sotirios Delimanolis Oct 29 '15 at 00:08

1 Answers1

3

Here is how I was able to configure the InternalResourceViewResolver in the Java Config. You can pass the name of the beans you need access to on the jsp to the setExposedContextBeanNames method of the InternalResourceViewResolver.

@Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/pages/");
    resolver.setSuffix(".jsp");
    resolver.setExposedContextBeanNames("myBean");
    return resolver;
}
Andrew Mairose
  • 10,615
  • 12
  • 60
  • 102