【问题标题】:Spring: JSP not reading passed ModelMap?Spring:JSP 不读取传递的 ModelMap?
【发布时间】:2013-10-17 19:01:53
【问题描述】:

我正在尝试让我的 JSP 文件使用我的 servlet 传递的 ModelMap,但我得到一个空字符串。已经尝试调试了一段时间,但没有取得任何进展。有人知道这个问题吗?我正在使用最新的 Spring WebInitializer 类。 index.jsp 为我打印 Hello 而不是 Hello Bob

index.jsp

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

我的控制器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/*");
    }
}

在 com.myProject.boostrap 中,我有 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>

我的 webapp 文件夹树

【问题讨论】:

标签: java xml spring servlets spring-mvc


【解决方案1】:

尝试返回“forward:index”。

您还可以将处理程序的返回类型更改为“ModelAndView”,并在返回 modelAndView 对象时设置视图名称和模型。

【讨论】:

  • 感谢您的帮助,实际上我在 JSP 页面中使用了错误的属性名称......所以我现在可以使用 ModelMap 了。它也适用于 ModelAndView。
猜你喜欢
  • 2011-10-21
  • 1970-01-01
  • 1970-01-01
  • 2020-11-04
  • 2015-01-27
  • 1970-01-01
  • 1970-01-01
  • 2015-05-17
  • 2021-07-22
相关资源
最近更新 更多