5

I am studying for the Spring Core certification and I have some doubts related this question:

What is the @Controller annotation used for? How can you create a controller without an annotation?

So I know that the @Controller annotation indicates that a particular class serves the role of a controller. The @Controller annotation acts as a stereotype for the annotated class, indicating its role. The dispatcher scans such annotated classes for mapped methods and detects @RequestMapping annotations.

So a controller class is something like this:

@Controller
public class AccountController {

    @RequestMapping("/listAccounts")
        public String list(Model model) {...}
    }
}

Ok, this is pretty clear for me but what exactly means create a controller without an annotation? How can I do it? By XML configuration or how?

Tnx

AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • Add bean in your Spring configuration file – Nimesh Apr 02 '15 at 10:14
  • possible duplicate of [Spring MVC 3.1 without annotations?](http://stackoverflow.com/questions/9991519/spring-mvc-3-1-without-annotations) – OO7 Apr 02 '15 at 12:11

3 Answers3

5
public class AccountController extends MultiActionController {
    public ModelAndView listAccounts() {
        // your code
        return new ModelAndView("listAccounts.bean", "msg", "As you  want")
    }
}

web.xml

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.bean</url-pattern>
</servlet-mapping>

dispatcher-servlet.xml

<bean name="/listAccounts.bean" class="p1.AccountController"></bean>
Saakshi Aggarwal
  • 528
  • 1
  • 11
  • 26
1

I've come across this: Spring MVC 3.1 without annotations?

It would seem that you can actually create a controller without annotations (I've been working with Spring for little over a year and haven't encountered such a scenario, I don't know why one would want to do this, apart from certification questions of course) and the way to do it is by using a special configuration in the dispatcher-servlet XML file.

Community
  • 1
  • 1
  • It's not that special, considered that annotation config only exists since Spring 3. Before that, the only way to configure Spring was using the XML configuration. – dunni Apr 02 '15 at 11:46
0

Just to comment the reasons why someone would like to configure Spring programatically or throuth XML, it is because it takes some to scan all the files looking for the annotations during runtime, so if we disable the scan and configure it manually the application will be available to service requests much faster and that is very important on high demand sceneraios.