How can I create a Spring controller without the use of the annotations?

Deadly 提交于 2019-12-21 05:39:06

问题


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


回答1:


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>



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/29410179/how-can-i-create-a-spring-controller-without-the-use-of-the-annotations

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