In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
In this issue, the editor will bring you what are the practical tips for writing SpringMVC controllers. The article is rich in content and analyzed and described from a professional point of view. I hope you can get something after reading this article.
After writing, the controller invokes a business class to handle business-related tasks, and then redirects the customer to the logical view name. Springdispatcher servlet parses the logical view name and renders the result or output. This is a typical complete "request-response" process.
1. 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.
two。 Implement the controller interface
Another classic way to create a controller in Spring MVC is to implement the Controller interface for a class. Such as:
Import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; publicclassMainControllerimplements Controller {@ Override public ModelAndView handleRequest (HttpServletRequest request, HttpServletResponse response) throws Exception {System.out.println ("Welcome main"); returnnew ModelAndView ("main");}}
The implementation class must override the handleRequest () method (Spring dispatcher servlet calls handleRequest when a matching request is received). The request URL pattern handled by the controller is defined in the content configuration file of Spring as follows:
The disadvantage of this approach is that its control class cannot handle multiple request URL at the same time.
3. Inherit the AbstractController class
If you want to easily control the supported HTTP methods, sessions, and content caches, it is ideal to have the control class inherit the AbstractController class. Such as:
Import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; publicclassBigControllerextends AbstractController {@ Override protected ModelAndView handleRequestInternal (HttpServletRequest request, HttpServletResponse response) throws Exception {System.out.println ("You're big!"); returnnew ModelAndView ("big");}}
The above example creates a single-action controller configured with supported methods, sessions, and caches that can be indicated in the controller's bean declaration. Such as:
This configuration indicates that the controller handler method only supports the POST method. For more configuration (such as sessions, caching), see AbstractController.
SpringMVC also provides several controller classes that support specific purposes, including:
AbstractUrlViewController MultiActionController ParameterizableViewController ServletForwardingController ServletWrappingController UrlFilenameViewController
4. Specify the URL mapping for the processor
This is an essential step in writing a controller class designed to handle one or more specific requests. Spring MVC provides the @ RequestMapping annotation to specify the URL mapping. Such as:
This step maps the URL schema / login and processes it with annotations or annotation classes. When the @ RequestMapping annotation is used on a class, the class becomes a single-action controller. Such as:
Import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @ Controller @ RequestMapping ("/ hello") publicclassSingleActionController {@ RequestMapping (method = RequestMethod.GET) publicString sayHello () {return "hello";}}
When the @ RequestMapping annotation is used on a method, a multi-action controller can be generated. Such as:
Import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @ Controller publicclassUserController {@ RequestMapping ("/ listUsers") publicString listUsers () {return "ListUsers";} @ RequestMapping ("/ saveUser") publicString saveUser () {return "EditUser";} @ RequestMapping ("/ deleteUser") publicString deleteUser () {return "DeleteUser";}}
The @ RequestMapping annotation can also be used to specify multiple URL schemas and process them in a single way. Such as:
In addition, this annotation has other attributes that work in some cases, such as the method attribute that will be discussed in the following section.
5. Specify the HTTP request method for the processor method
Using the method attribute of the @ RequestMapping annotation, you can specify which HTTP methods (including GET, POST, PUT, and so on) are supported by the processor method. Such as:
Import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod; @ Controller publicclassLoginController {@ RequestMapping (value = "/ login", method = RequestMethod.GET) publicString viewLogin () {return "LoginForm";} @ RequestMapping (value = "/ login", method = RequestMethod.POST) publicString doLogin () {return "Home";}}
As shown above, the controller has two processing methods for the same URL mode / login. The first method is for the GET method, and the second method is for the POST method.
To learn more about the @ RequestMapping annotation, see the @ RequestMapping annotation.
6. Map request parameters to processor methods
One of the features of SpringMVC is that the request parameters can be retrieved as regular parameters of the processor method using the @ RequestParam annotation. This is a good way to decouple the controller from the HttpServletRequest interface of ServletAPI.
Such as:
@ RequestMapping (value = "/ login", method = RequestMethod.POSTpublic String doLogin (@ RequestParamString username @ RequestParamString password) {}
Spring binds the method parameter username and password to the HTTP request parameter with the same name. This means that a URL can be called as follows (take the GET request method as an example):
Http://localhost:8080/spring/login?username=scott&password=tiger
The type conversion is also done automatically. If you declare a parameter of type integer as follows:
Then Spring automatically converts the value of the request parameter (String type) to the specified type (integer) in the processing method.
To prevent the parameter name from being different from the variable name, specify the parameter real name as follows:
The @ RequestParam annotation has two other attributes that can work in some cases. One of the properties is required, which specifies whether a parameter is mandatory or optional. Such as:
This means that the parameter country is optional and can be omitted from the request. When there is no parameter country in the request, the variable country is null.
The other property is defaultValue, which acts as a fallbackvalue when the request parameter is empty. Such as:
Spring also supports all parameters as Map objects when the method parameter type is Map. Such as:
The mapping parameter contains all request parameters in the form of key-value pairs. To learn more about the @ RequestParam annotation, see the @ RequestParam annotation.
7. Return to models and views
After processing the business logic, the processor method returns a view, which is then parsed by Springdispatcher servlet. Spring supports the handler method to return a String object or a ModelAndView object. As shown below, the handler method returns a String object and represents the view name LoginForm:
@ RequestMapping (value = "/ login", method = RequestMethod.GET) public String viewLogin () {return "LoginForm";}
This is the easiest way to return the view name. But if you want to send additional data to the view, you must return the ModelAndView object. Such as:
@ RequestMapping ("/ listUsers") public ModelAndView listUsers () {List listUser = new ArrayList (); / / get user list from DAO... ModelAndView modelView = new ModelAndView ("UserList"); modelView.addObject ("listUser", listUser); return modelView;}
As shown above, the handler method returns a ModelAndView object whose view name is UserList and has a set of User objects available in the view.
Spring is a very flexible framework that allows ModelAndView objects to be declared as parameters of handler methods without having to recreate one. Therefore, the above example can be rewritten as follows:
@ RequestMapping ("/ listUsers") public ModelAndView listUsers (ModelAndView modelView) {List listUser = new ArrayList (); / / get user list from DAO... ModelView.setViewName ("UserList"); modelView.addObject ("listUser", listUser); return modelView;}
To learn more about the ModelAndView class, see the ModelAndView class.
8. Put objects into the model
In the application of the MVC architecture, the controller inputs data into the model, which is used in the view. As you can see from the example in the previous section, the addObject () of the ModelAndView class is used to put objects into the model in the form of name-value pairs:
ModelView.addObject ("listUser", listUser); modelView.addObject ("siteName", newString ("CodeJava.net")); modelView.addObject ("users", 1200000)
Spring also supports declaring Map type parameters in processor methods. Spring uses this mapping to store objects that will be put into the model. Such as:
@ RequestMapping (method = RequestMethod.GET) publicStringviewStats (Map model) {model.put ("siteName", "CodeJava.net"); model.put ("pageviews", 320000); return "Stats";}
This approach is simpler than using the ModelAndView object. Spring allows users to choose Map objects and ModelAndView objects flexibly.
9. Redirection in processor method
When conditions permit, you can simply add redirect:/ before the URL to redirect the user to another URL. Such as:
/ / check login status.... If (! isLogin) {returnnew ModelAndView ("redirect:/login");} / return a list of Users
In the above code, users who have not logged in will jump to / loginURL.
10. Handle form submission and form validation
The @ ModelAttribute annotation in Spring supports binding form fields to form return objects, and the BingingRequest interface supports validation of form fields. This makes it very easy to handle form submissions. The code for a typical processor method that processes and validates form data is as follows:
Controller publicclassRegistrationController {@ RequestMapping (value = "/ doRegister", method = RequestMethod.POST) publicString doRegister (@ ModelAttribute ("userForm") User user, BindingResult bindingResult) {if (bindingResult.hasErrors ()) {/ / form validation error} else {/ / form input is OK} / / process registration... Return "Success";}}
To learn more about @ ModelAttribute annotations and BindingResult APIs, please see the official Spring documentation:
Using @ ModelAttribute on a method argument Using @ ModelAttribute on a method Interface BindingResult
11. Handle file upload
Spring supports automatic binding of uploaded data to CommonsMultiparFile array objects, which makes it easy to handle file uploads in processor methods. Spring uses Apache CommonsFileUpload as the deep multipart parser (underlyingmultipart resolver).
The code for simply uploading a user file is as follows:
@ RequestMapping (value = "/ uploadFiles", method = RequestMethod.POST) publicStringhandleFileUpload (@ RequestParam CommonsMultipartFile [] fileUpload) throws Exception {for (CommonsMultipartFile aFile: fileUpload) {/ / stores the uploaded file aFile.transferTo (new File (aFile.getOriginalFilename ();} return "Success";}
To learn about Spring MVC's complete method of handling file uploads, see the Spring MVC file upload tutorial.
twelve。 Automatically inject business classes into the processor
In order for the controller to delegate business logic processing to the relevant business class, you can use the @ Autowired annotation to have Spring automatically inject the actual implementation of the business class into the controller. Such as:
@ Controller publicclassUserController {@ Autowired private UserDAO userDAO; publicString listUser () {/ / handler method to list all users userDAO.list ();} publicString saveUser (User user) {/ / handler method to save/update a user userDAO.save (user);} publicString deleteUser (User user) {/ / handler method to delete a user userDAO.delete (user);} publicString getUser (int userId) {/ / handler method to get a user userDAO.get (userId);}}
In this example, all the business logic related to user management is provided by the implementation of the UserDAO interface. Such as:
InterfaceUserDAO {List list (); void save (User user); void checkLogin (User user);}
As shown above, the @ Autowired annotation enables the processor method to delegate tasks to the business class:
To learn more about the @ Autowired annotation, see Annotation TypeAutowired.
13. Get HttpServletRequest and HttpServletResponse
In some cases, you need to get the HttpServletRequest or HttpServletResponse object directly in the processor method. In Spring's flexible framework, you only need to add a relevant parameter to the processor method to accomplish this task. Such as:
RequestMapping ("/ download") publicStringdoDownloadFile (HttpServletRequest request, HttpServletResponse response) {/ / access the request / / access the response return "DownloadPage";}
Spring supports detection and automatic injection of HttpServletRequest and HttpServletResponse objects into methods. This allows you to get the request and response directly, such as getting InputStream, OutputStream, or returning a specific HTTP code.
14. Abide by the principle of single responsibility
When designing and writing controllers in Spring MVC, you should follow the following two very practical operations:
Instead of using the controller class to execute the business logic, you should use the controller class to delegate the business processing to the relevant business class. This ensures that the controller focuses on its assigned responsibility, that is, to control the workflow of the application. Such as:
@ Controller publicclassUserController {@ Autowired private UserDAO userDAO; publicString listUser () {/ / handler method to list all users userDAO.list ();} publicString saveUser (User user) {/ / handler method to save/update a user userDAO.save (user);} publicString deleteUser (User user) {/ / handler method to delete a user userDAO.delete (user);} publicString getUser (int userId) {/ / handler method to get a user userDAO.get (userId);}}
Create a separate controller for each business area. For example, use UserController to control user-managed workflows, OrderController to control order processing workflows, and so on:
Controller publicclassUserController {} @ Controller publicclassProductController {} @ Controller publicclassOrderController {} @ Controller publicclassPaymentController {}
These are the practical tips for writing SpringMVC controllers shared by the editor. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.