Popcorn
Popcorn

Reputation: 5348

Spring: JSP not reading passed ModelMap?

I'm trying to get my JSP file to use the ModelMap passed by my servlet, but am getting an empty string. Been trying to debug this for a while now, but haven't made any progress. Anyone know of the problem? I'm using the latest Spring WebInitializer class. index.jsp prints Hello instead of Hello Bob for me.

index.jsp

<!DOCTYPE html>
<html>
<body>
Hello ${test}
</body>
</html>

My controller HomeController.java

@Controller
@RequestMapping("/")
public class HomeController {
    @RequestMapping(method = RequestMethod.GET)
    public String foo(ModelMap modelMap) throws Exception {
        modelMap.addAttribute("test", "Bob");
        return "index";
    }
}

WebInitializer.java

public class WebInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
        // Create the dispatcher servlet's Spring application context
        AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
        dispatcherContext.scan("com.myProject.bootstrap");

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(dispatcherContext));

        //Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher =
        container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));

        dispatcher.setLoadOnStartup(1);
        Set<String> mappingConflicts = dispatcher.addMapping("/views/*");
    }
}

Inside com.myProject.boostrap, I have AppConfiguration.java

@Configuration
@ComponentScan(basePackages = {"com.myProject"})
@EnableWebMvc
public class AppConfiguration {
    @Bean
    public InternalResourceViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
        internalResourceViewResolver.setPrefix("/WEB-INF/views/");
        internalResourceViewResolver.setSuffix(".jsp");
        return internalResourceViewResolver;
    }
}

web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

</web-app>

My webapp folder tree

enter image description here

Upvotes: 1

Views: 2482

Answers (1)

Kumar Sambhav
Kumar Sambhav

Reputation: 7765

Try returning "forward:index" instead.

You can also change return type of your handler to 'ModelAndView' and set view name and model while returning the modelAndView object.

Upvotes: 1

Related Questions