Can't get Spring MVC dispatcher to work properly when url pattern is a path

限于喜欢 提交于 2019-12-20 14:13:02

问题


I have a web app that we're applying spring MVC just for REST services at the moment. We want our rest services to appear under ${contextPath}/rest/**, however when I set this we get:

No mapping found for HTTP request with URI [/myapp/rest/testSvc/message] in DispatcherServlet with name 'Spring MVC Dispatcher Servlet'

My web.xml has:

<servlet>
  <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      /WEB-INF/spring/servlet-context.xml
    </param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
  <url-pattern>/rest</url-pattern>
</servlet-mapping>

servlet-context.xml, which is fine and is registering services as they get registered at startup.

<context:component-scan base-package="com.mycompany.myapp.rest" />
<mvc:annotation-driven />

My controller looks as follows:

@Controller
@RequestMapping(value = "/rest/testService")
public class TestREST {
    @RequestMapping(value="message", method=RequestMethod.GET)
    public @ResponseBody String getMessage() {
        return "REST working";
    }

If I cahnge the url-pattern in web.xml to *.rest and my request-mapping for message to message.rest it works.


回答1:


The problem is likely that you have repeated the /rest prefix in both web.xml and @RequestMapping. It should be in one or the either, but not both, e.g.

<url-pattern>/rest</url-pattern>

and

@RequestMapping(value = "/testService")

The paths upon which @RequestMapping operates are the parts of the path that follows the servlet part, and your web.xml defines the servlet part as /path, so @RequestMapping matches against whatever is left, i.e. /testService.

In its current form, your @RequestMapping is actually matching against {contextPath}/rest/rest/testService.




回答2:


Perhaps you could try changing to <url-pattern>/rest/*</url-pattern> or <url-pattern>/rest*</url-pattern> and see if that helps.



来源:https://stackoverflow.com/questions/5367309/cant-get-spring-mvc-dispatcher-to-work-properly-when-url-pattern-is-a-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!