【发布时间】:2014-06-19 20:15:33
【问题描述】:
我是 SPring 3 MVC 的新手,正在尝试配置基于 java 的 Spring 3 MVC 应用程序。我正在为我的应用程序使用 servlet 2.5 容器。以下是我尝试过的。
以下是我基于 Maven 的项目结构:
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_2_5.xsd"
version="2.5">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.sprmvc.init.WebAppConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
</web-app>
WebAppConfig.java
@Configuration //Specifies the class as configuration
@ComponentScan("com.sprmvc") //Specifies which package to scan
@EnableWebMvc //Enables to use Spring's annotations in the code
public class WebAppConfig {
@Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
LinkController.java
@Controller
public class LinkController {
@RequestMapping(value="/hello")
public ModelAndView goToHelloPage() {
ModelAndView view = new ModelAndView();
view.setViewName("hello"); //name of the jsp-file in the "page" folder
String str = "MVC Spring is here!";
view.addObject("message", str); //adding of str object as "message" parameter
return view;
}
}
index.jsp
<html>
<body>
<h1>Home page</h1>
<p>This is a Home Page.</p>
<p><a href="hello.html">Hello world link</a></p>
</body>
</html>
hello.jsp
<html>
<body>
<p>Hello world: ${message}</p>
<p>Well done!</p>
</body>
</html>
当我运行应用程序时,index.jsp 会正确显示。但是在点击index.jsp 页面中的link 时,我得到了一个404。
点击index.jsp页面的link触发的URL是http://localhost:8055/SpringMVCConfig/hello.html,由于资源不可用,因此出现404错误。
由于prefix 和suffix 无法正常工作,我的基于java 的配置中有一些错误。请指教。
【问题讨论】:
-
URL 映射是
*.htm吗?你用hello.html打电话给控制器,这是正确的吗?请检查 URL 映射
标签: java spring jsp spring-mvc web-applications