問題:
最近在原有MVC的WEB應用中添加一個REST服務,結果始終報404錯誤。把 Spring debug 日志打開,發現處理REST請求的Controller已經正確進入
[org.springframework.web.servlet.DispatcherServlet]DispatcherServlet with name 'springMvc' processing GET request for [/sm-web/rest/loanOper/110002/pieces] [org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping]Mapping [/loanOper/110002/pieces] to HandlerExecutionChain with handler [com.sm.controller.in.IntoPiecesRestController@30630dd] and 1 interceptor [org.springframework.web.servlet.DispatcherServlet]Last-Modified value for [/sm-web/rest/loanOper/110002/pieces] is: -1 [org.springframework.web.bind.annotation.support.HandlerMethodInvoker]Invoking request handler method: public java.util.List com.sm.controller.in.IntoPiecesRestController.getIntoPieceList()
然而, 從Controller調用結束后, 卻並沒有直接返回我需要的json數據, 而是被MVC繼續當作一個view處理, 被交jsp的視圖解析器,我的REST URL請求被繼續處理, 自動添加了/WEB-INF/view前綴和.jsp后綴。導致404錯誤。
[org.springframework.web.servlet.DispatcherServlet]Rendering view [org.springframework.web.servlet.view.JstlView: name 'loanOper/110002/pieces'; URL [/WEB-INF/view/loanOper/110002/pieces.jsp]] in DispatcherServlet with name 'springMvc'
[org.springframework.web.servlet.view.JstlView]Added model object 'mapList' of type [java.util.ArrayList] to request in view with name 'loanOper/110002/pieces'
[org.springframework.web.servlet.view.JstlView]Forwarding to resource [/WEB-INF/view/loanOper/110002/pieces.jsp] in InternalResourceView 'loanOper/110002/pieces'
[org.springframework.web.servlet.DispatcherServlet]Successfully completed request
分析:
有人說是需要新添加視圖解析器, 但我始終覺得不對, 因為我的REST請求在進入視圖解析器之前,已經被處理,我只需要通過@RestController將其自動轉換為JSON。而且我之前的項目都是這么做的,完全沒有問題。
解決辦法:
最后, 我另外寫了一個新的工程, 一個簡單的HelloWorld。正確, 我一一對比了web.xml和spring配置。 最中發現是現有項目的spring配置上有問題。沒有添加<mvc:annotation-driving/>配置 !加上后就沒有問題了。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 《》 xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <context:component-scan base-package="com.test" /> <mvc:annotation-driven />
<mvc:annotation-driving/>的作用
<mvc:annotation-driven/>相當於注冊了DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter兩個bean,配置一些messageconverter。即解決了@Controller注解的使用前提配置。
<context:annotation-config/>是對包進行掃描,實現注釋驅動Bean定義,同時將bean自動注入容器中使用。即解決了@Controller標識的類的bean的注入和使用。