似乎dispatcher-servlet无法使用。
执行组件扫描 <context:component-scan base-package="abc" />
在 abc 包下的控制器文件( HelloController.java )中。代码编写如下:
@Controller
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello"; //I have already made hello.jsp in web-inf/jsp/
}
}
我的应用程序名称是 SpringMiddle 。当试试网址为:
http://localhost:8080/SpringMiddle/hello.htm
我在web.xml中有以下url模式
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
它显示错误HTTP 404未找到。
编辑::它显示警告
WARNING: No mapping found for HTTP request with URI [/SpringMiddle/hello.htm] in DispatcherServlet with name 'dispatcher'
答案 0 :(得分:6)
你必须在Spring中启用MVC。在xml配置中,您可以这样做:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
</beans>
并在JavaConfig中:
@Configuration
@EnableWebMvc
public class WebConfig {
}
答案 1 :(得分:3)
如果您指的是一个mkyong教程,我没有使用注释:@Configuration @EnableWebMvc,问题是你正在使用注释和xml声明。
用于设置网址的注释:
@Controller
@RequestMapping("/hello")
你应该删除这部分:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
您将能够访问网址:
http://localhost:8080/SpringMiddle/hello
还要确保在web.xml中有这个:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
dispatcher-servlet.xml是声明组件扫描的地方