我试图让我的 JSP 文件使用我的 servlet 传递的 ModelMap,但得到一个空字符串。已经尝试调试了一段时间,但没有取得任何进展。有人知道这个问题吗?我正在使用最新的 SpringWebInitializer
课程。index.jsp打印Hello
而不是Hello Bob
为我打印。
索引.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 文件夹树