views:

347

answers:

3

in my applicationContext.xml, i put this

<bean id="something" class="com.to.theController"/>

in com.to.theController

i have this method like

@Controller
public theController{
 @RequestMapping(value="/api/add", method= RequestMethod.GET)
  public String apiAddHandler(Model model){
      model.addAttribute("api", new Api());
      return "apiForm";

  }
}

when jetty startup, i can see defining beans [something,...

but when i go to http://localhost:8080/api/add , i get 404 error. what did i miss out? i already debug apiAddHandler method, this method is not called when i call the URL

+1  A: 

Do you have a <servlet-mapping> element in your web.xml to map URLs that look like /api/add to DispatcherServlet?

If not, then it doesn't matter how Spring MVC maps URLs to controllers if the request never makes it to Spring MVC in the first place.

matt b
+3  A: 

You need to do some setups.

  1. In your web.xml you have add a mapping for DispatcherServlet. Something like

    <servlet>
        <servlet-name>springapp</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    
    <servlet-mapping>
        <servlet-name>springapp</servlet-name>
        <url-pattern>*/api/add</url-pattern>
    </servlet-mapping>
    
  2. You have to add annotation handler to the spring configuration

    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
    <context:component-scan base-package="learn.web.controller" />
    

    Where learn.web.controller is the package where you have the annoted components

Arun P Johny
+1  A: 

Make sure Spring is finding your annotations. You should see something like "INFO DefaultAnnotationHandlerMapping:343 - Mapped URL path [/api/add] onto handler [com.example.ExampleController@6f3588ca]" in the logs.

Also, as mentioned already, you need to make sure that you have the correct url mapping in web.xml.

I'd use

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

to map all urls to the dispatcher servlet if using annotations.

If you want to serve some content outside of the dispatcher servlet add the folowing aswell

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.jpg</url-pattern>
</servlet-mapping>
NA