简体   繁体   中英

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

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM