java HTTP请求未委派给根WebApplicationContext的控制器
我遵循这个Spring Docs并将web.xml
和applicatioinContext.xml
配置为在Spring Web MVC中使用功能单根上下文,即没有Servlet WebApplicationContext;所有请求都将由根WebApplicationContext提供
但问题是HTTP请求并没有被委派给根WebApplicationContext的控制器
网络。xml:
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/root-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
根上下文。xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean id="PostController" class="org.my.controllers.PostController">
</bean>
</beans>
控制器:
@Controller
public class PostController {
@RequestMapping(value= "/controller", method = RequestMethod.GET)
@ResponseBody
public String foo() {
return "Response!";
}
}
所以当我在浏览器中点击URLhttp://localhost:8080/PracticeJavaWeb/controller时,它显示的是404
服务器日志显示:
WARNING: No mapping found for HTTP request with URI [/PracticeJavaWeb/controller] in DispatcherServlet with name 'dispatcher'
It is also possible to have just one root context for single DispatcherServlet scenarios.
# 1 楼答案
您需要在根上下文中添加
<mvc:annotation-driven />
标记。xml<mvc:annotation-driven />
标记确保您的请求被发送到控制器不要忘记在根上下文中添加mvc名称空间。xml
# 2 楼答案
只需对根上下文进行一个小更改。xml文件,添加以下内容:
mvc:annotation-driven
启用上下文路径来识别spring mvc注释,以便将请求分派给控制器这里还有一个根上下文的完整示例。xml