找不到spring 404控制器

时间:2015-05-08 11:03:51

标签: java spring spring-mvc

我遇到弹簧问题,因为我收不到404错误。

我的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
     version="3.0">


<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/PROJECT_NAME/*</url-pattern>
</servlet-mapping>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/mvc-dispatcher-servlet.xml
    </param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


</web-app>

我还有mvc-dispatcher.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"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<context:annotation-config/>
<mvc:annotation-driven/>
<context:component-scan
        base-package="com.PROJECT_NAME.web.controllers"/>


</beans>

和我的控制器

@Controller
public class TestController {

@RequestMapping(value="/test", method = RequestMethod.GET)
public @ResponseBody
ResponseEntity<Boolean> create() {
    return new ResponseEntity<>(true, HttpStatus.OK);
}

}

当我像localhost:8080 / PROJECT_NAME / test一样查询时,我找不到404错误。 localhost:8080 / PROJECT_NAME返回20​​0状态代码 有什么问题?

1 个答案:

答案 0 :(得分:2)

您不需要在url-pattern中提及上下文根。 url-pattern应为/,这意味着调度程序servlet将为任何/每个URL /请求提供服务。

<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

正如您提到的url-pattern为/PROJECT_NAME/*,这意味着http://localhost:8080/PROJECT_NAME(Context_Root)/PROJECT_NAME/Anything形式的任何网址都会被转发到调度程序servlet,这就是localhost:8080/PROJECT_NAME/PROJECT_NAME/test工作正常的原因。