4

Spring3 MVC - Controller class is getting called but not the controller method.

Controller:

package com.quizat.controller;

@Controller
public class QuizatController {
    public QuizatController(){
        System.out.println("in controller");
    }
    @RequestMapping("/")    
    @ResponseBody
    public String home(Model model) throws Exception {
        System.out.println("home is running");
        return "success";
    }
}

My web.xml

<display-name>Spring3Example</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
  </init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>

My dispatcher-servlet.xml

<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.quizat" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
  <value>org.springframework.web.servlet.view.JstlView</value>
  </property>
<property name="prefix">
<value>/view/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

Constructor of my controller runs. But my method inside the Controller is not getting called. What could be the error that I have made?

Prasanna
  • 2,593
  • 7
  • 39
  • 53

1 Answers1

4

You are mapping / to your controller's method. Instead of that you should map a string like /home or /*.

@RequestMapping("/home") 
@ResponseBody
public String home(Model model) throws Exception {
} 

Also in the Controller you can use @RequestMapping(value = "/*") for the home() method.

Note: you should also be using Spring >= v3.0.3 due to SPR-7064

Reference: How do I map Spring MVC controller to a uri with and without trailing slash?

Community
  • 1
  • 1
Viral Patel
  • 8,506
  • 3
  • 32
  • 29