springmvc cannot call controller's method

1.1k Views Asked by At

Currently I got a problem when I configure my springmvc web project.

Below is my web.xml

 <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/api/*</url-pattern>
</servlet-mapping>

And I defined my dispatcher-servlet.xml like this

<context:component-scan base-package="xxx.controller"

<mvc:annotation-driven />

And in package xxx.controller I define a class TestController

@Controller
@RequestMapping(value="/api")
public class TestController {


    @RequestMapping(value = "/hello")
    @ResponseBody
    public String hello(){
        System.out.println("comming hello");
        return "hello world";
    }

} 

Now when I start tomcat, and want to access to localhost:8080/testproject/api/hello, The spring informs me

[10:10:58|WARN |(org.springframework.web.servlet.PageNotFound)]=[No mapping found for HTTP request with URI [/testproject/api/hello] in DispatcherServlet with name 'dispatcher']

But if I modify the url-pattern in web.xml to

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

It is ok to access to localhost:8080/testproject/api/hello. I do not know why this happens. I do want to use /api/* rather than /.

Could anyone helps me configure the controller path mapping? Many thanks!

1

There are 1 best solutions below

3
On BEST ANSWER

You are telling your application to run in /api context when you define the following:

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/api/*</url-pattern>
</servlet-mapping>

so to access your controller the URL would have to be localhost:8080/api/api/hello

Just get rid of the /api from your dispatcher as you have and then your mapping should automatically default to localhost:8080/api/hello and work.

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

Otherwise if you want to run your application in /api context always you have the option of removing @RequestMapping(value="/api") from your controller. That way it only recognises the mapping on method.