我试图让我的 JSP 文件使用我的 servlet 传递的 ModelMap,但得到一个空字符串。已经尝试调试了一段时间,但尚未取得任何进展。有人知道这个问题吗?我正在使用最新的 Spring WebInitializer
类。 index.jsp 为我打印 Hello
而不是 Hello Bob
。
index.jsp
<!DOCTYPE html>
<html>
<body>
Hello ${test}
</body>
</html>
我的 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/*");
}
}
在 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 文件夹树
最佳答案
尝试返回“forward:index”。
您还可以将处理程序的返回类型更改为“ModelAndView”,并在返回 modelAndView 对象时设置 View 名称和模型。
关于java - Spring:JSP 未读取传递的 ModelMap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19288648/