Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use @ controllerstereotype for Spring MVC

Shulou Source: shulou.com Published: 2022-06-01 04:49:46 09月17日 Update

This article mainly introduces how Spring MVC uses @ controllerstereotype, which has a certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let's take a look at it.

Use @ controllerstereotype

The easiest way to create a controller class that can handle single or multiple requests is to annotate a class with @ controllerstereotype, such as:

Import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @ Controller publicclassHomeController {@ RequestMapping ("/") publicString visitHome () {/ / do something before returning view name return "home";}}

As shown above, the visitHome () method handles requests received by the application content path (/) by redirecting to the view name home.

Note: @ controllerstereotype can only be used if the annotation driver is enabled in the Spring configuration file.

When annotation driver is enabled, Spring's container (container) automatically scans for classes in the following packages:

Classes with @ controller annotations are marked as controllers. This method is very practical because it is simple and convenient, and there is no need to declare beans to the controller in the configuration file.

Note: use the @ controller annotation to create a multi-action controller class that can handle multiple different requests at the same time. Such as:

Controller publicclassMultiActionController {@ RequestMapping ("/ listUsers") public ModelAndView listUsers () {} @ RequestMapping ("/ saveUser") public ModelAndView saveUser (User user) {} @ RequestMapping ("/ deleteUser") public ModelAndView deleteUser (User user) {}}

As shown above, there are three processors (handler) processing three requests, / listUsers,/saveUser, and / deleteUser, respectively.

Thank you for reading this article carefully. I hope the article "how to use Spring MVC @ controllerstereotype" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Tags: Comments controllers articles processing control methods three or more such as above file configuration driver different practical value interest content single only simultaneously Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology MariaDB Docker Shulou Tech Info NVidia