Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the tips on Spring MVC?

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the tips about Spring MVC". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the tips about Spring MVC"?

1. Use @ Controller stereotype

This is the easiest way to create a controller class that can handle one or more requests. Simply annotate a class @ Controller with stereotype, for example:

Import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @ Controller public class HomeController {@ RequestMapping ("/") public String visitHome () {return "home";}}

As you can see, the visitHome () method handles requests from the application context path (/) by redirecting to the view named home.

Note: the @ Controller prototype can only be used when annotation driver is enabled in the configuration file of Spring:

When the annotation driver is enabled, the Spring container automatically scans the class under the package specified in the following statement:

Classes annotated by @ Controller are configured as controllers. This is preferable because it is simple: there is no need to declare bean for the controller in the configuration file.

Note: by using the @ Controller annotation, you can have a multi-action controller class that can handle multiple different requests. For example:

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

As you can see in the controller class above, there are three different processing methods / listUsers,/saveUser and / deleteUser for handling requests.

two。 Implement the controller interface

Another (perhaps classic) way to create a controller in Spring MVC is to have the class implement the Controller interface. For example:

Import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; public class MainController implements Controller {@ Override public ModelAndView handleRequest (HttpServletRequest request, HttpServletResponse response) throws Exception {System.out.println ("Welcome main"); return new ModelAndView ("main");}}

The implementation class must override the handleRequest () method, which will be called by the Spring scheduler Servlet when the matching request comes in. The request URL pattern handled by this controller is defined in the context profile of Spring as follows:

However, the disadvantage of this approach is that the controller class cannot handle multiple request URL.

3. Extend the AbstractController class

If you want to easily control supported HTTP methods, sessions, and content caching. Extending your controller AbstractController class is an ideal choice. Consider the following example:

Import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class BigController extends AbstractController {@ Override protected ModelAndView handleRequestInternal (HttpServletRequest request, HttpServletResponse response) throws Exception {System.out.println ("You're big!"); return new ModelAndView ("big");}}

This creates a single-action controller with configurations about supported methods, sessions, and caches, which can then be specified in the controller's bean declaration. For example:

This configuration instructs POST that the hander method of this controller only supports this method.

Spring MVC also provides several controller classes designed for specific purposes, including:

AbstractUrlViewController

MultiActionController

ParameterizableViewController

ServletForwardingController

ServletWrappingController

UrlFilenameViewController

4. Specify the URL mapping for the handler method

This is a mandatory task that must be performed when coding a controller class designed to handle one or more specific requests. Spring MVC provides the @ RequestMapping annotation, which specifies the URL mapping. For example:

@ RequestMapping ("/ login")

This maps the URL schema of / login to be handled by annotated methods or classes. When this annotation is used at the class level, the class becomes a single-action controller. For example:

Import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @ Controller @ RequestMapping ("/ hello") public class SingleActionController {@ RequestMapping (method = RequestMethod.GET) public String sayHello () {return "hello";}}

When the @ RequestMapping annotation is used at the method level, you can have a multi-action controller. For example:

Import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @ Controller public class UserController {@ RequestMapping ("/ listUsers") public String listUsers () {return "ListUsers";} @ RequestMapping ("/ saveUser") public String saveUser () {return "EditUser";} @ RequestMapping ("/ deleteUser") public String deleteUser () {return "DeleteUser" }}

The @ RequestMapping annotation can also be used to specify multiple URL schemas to be processed by a method. For example:

@ RequestMapping ({"/ hello", "/ hi", "/ greetings"})

In addition, this annotation has other attributes that may be useful in some cases, such as method.

5. Specify the HTTP request method for the handler method

You can use the annotated method attribute to specify which HTTP method (GET,POST,PUT, etc.) @ RequestMapping is supported by the handler method. This is an example:

Import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @ Controller public class LoginController {@ RequestMapping (value = "/ login", method = RequestMethod.GET) public String viewLogin () {return "LoginForm";} @ RequestMapping (value = "/ login", method = RequestMethod.POST) public String doLogin () {return "Home";}}

This controller has two methods / login that handle the same URL mode, but the former is used for the GET method and the latter is used for the POST method. For more information about using @ RequestMapping annotations, see @ RequestMapping annotations.

6. Map request parameters to handler methods

One of the cool features of Spring MVC is that you can use the @ RequestParam annotation to retrieve request parameters as regular parameters of handler methods. This is a good way to separate the interface of the controller HttpServletRequest from the Servlet API.

@ RequestMapping (value = "/ login", method = RequestMethod.POST) public String doLogin (@ RequestParam String username, @ RequestParam String password) {}

Spring binds the method parameter username and password to the HTTP request parameter with the same name. This means that you can call URL in the following ways (if the request method is GET):

Http:// localhost:8080 / spring / login? Username = scott&password = tiger

Type conversion is also done automatically. For example, if you declare parameters of the following types of integer:

@ RequestParam int securityNumber

Spring then automatically converts the value of the request parameter (string) to the specified type (integer) in the handler method.

If the parameter name is different from the variable name, you can specify the actual name of the parameter as follows:

@ RequestParam ("SSN") int securityNumber

The @ RequestParam annotation also has two additional attributes, which may be useful in some cases. This property specifies whether the parameter is required. For example: required

@ RequestParam (required = false) String country

This means that the parameter country is optional; therefore, it may be lost from the request. In the above example, country, if such a parameter does not exist in the request, the variable will be null.

The other property is defaultValue, which can be used as a fallback value when the request parameter is empty. For example:

@ RequestParam (defaultValue = "18") int age

Map also allows us to access Map with all parameters as objects if the method parameter is type,Spring. For example:

DoLogin (@ RequestParam Map params)

The mapping parameter then contains all request parameters in the form of key-value pairs. For more information about using @ RequestParam annotations, see the @ RequestParam annotations. Follow Wechat official account: Java technology stack, reply: spring in the background, you can get N of the latest Spring tutorials that I have sorted out, all of which are practical information.

7. Return to models and views

After processing the business logic, the handler method should return a view, which is then parsed by Spring's scheduler servlet. Spring allows us to ModelAndView to return a String or object from a handler method.

In the following example, the handler method returns a String and represents a view named LoginForm:

@ RequestMapping (value = "/ login", method = RequestMethod.GET) public String viewLogin () {return "LoginForm";}

This is the easiest way to return the view name. However, if you want to send additional data to the view, you must return a ModelAndView object. Consider the following handler methods:

@ RequestMapping ("/ listUsers") public ModelAndView listUsers () {List listUser = new ArrayList (); / / get the user list from DAO. ModelAndView modelView = new ModelAndView ("UserList"); modelView.addObject ("listUser", listUser); return modelView;}

As you can see, this handler method returns a User object that ModelAndView saves the view name UserList and a collection of objects that can be used in the view. Spring interview 7 big questions, recommend take a look.

Spring is also very flexible because you can declare a ModelAndView object as a parameter to a handler method without creating a new object. Therefore, the above example can be rewritten as follows:

@ RequestMapping ("/ listUsers") public ModelAndView listUsers (ModelAndView modelView) {List listUser = new ArrayList (); / / get the user list from DAO. ModelView.setViewName ("UserList"); modelView.addObject ("listUser", listUser); return modelView;}

For more information about this class, see: ModelAndView class.

8. Put objects into the model

In applications that follow the MVC architecture, the controller (C) should pass the data to the model (M) and then use the model in the view (V). As we saw in the previous example, the addObject () method ModelAndView of this class puts objects into the model in the form of name-value pairs:

ModelView.addObject ("listUser", listUser); modelView.addObject ("siteName", new String ("CodeJava.net")); modelView.addObject ("users", 1200000)

Again, Spring is very flexible. You can declare the parameters of the type in the handler method by Map. Spring uses this mapping to store objects for the model. Let's look at another example:

@ RequestMapping (method = RequestMethod.GET) public String viewStats (Map model) {model.put ("siteName", "CodeJava.net"); model.put ("pageviews", 320000); return "Stats";}

This is even simpler than using the ModelAndView object. Depending on your preference, you can use Map or ModelAndView objects. Thanks to the flexibility of Spring here.

9. Redirection in handler methods

If you want to redirect the user to another URL if the condition is met, ask redirect:/ to append it before the URL. The following code snippet gives an example:

/ / check login status. If (! isLogin) {return new ModelAndView ("redirect:/login");} / / returns the user list

In the above code, if / login is not logged in, the user will be redirected to that URL.

10. Handle form submission and form validation

Spring makes it easy to process form submissions by providing @ ModelAttribute annotations for binding form fields to form support objects and BindingResult's interface for validating form fields. The following code snippet shows a typical handler method that processes and validates form data:

@ Controller public class RegistrationController {@ RequestMapping (value = "/ doRegister", method = RequestMethod.POST) public String doRegister (@ ModelAttribute ("userForm") User user, BindingResult bindingResult) {if (bindingResult.hasErrors ()) {/ / form validation error} else {/ / form input is fine} / / registration process. Return "Success";}}

Learn more about the @ ModelAttribute annotation and the BindingResult interface from the official documentation of Spring:

Use @ ModelAttribute on method parameters

Use @ ModelAttribute on methods

Result of API binding

11. Handle file upload

Spring also makes it easy to handle file uploads in handler methods by automatically binding upload data to an array of CommonsMultipartFile objects. Spring uses Apache Commons FileUpload as the underlying multipart parser.

The following code snippet shows how easy it is to upload files from the client

@ RequestMapping (value = "/ uploadFiles", method = RequestMethod.POST) public String handleFileUpload (@ RequestParam CommonsMultipartFile [] fileUpload) throws Exception {for (CommonsMultipartFile aFile: fileUpload) {/ / store the uploaded file aFile.transferTo (new File (aFile.getOriginalFilename ();} return "Success";}

twelve。 Automatically assemble business classes in the controller

The controller should delegate the processing of the business logic to the relevant business class. To do this, you can use the @ Autowired annotation to have Spring automatically inject the actual implementation of the business class into the controller. Follow Wechat official account: Java technology stack, reply: sp in the background, you can get N of the latest Spring Boot tutorials that I have sorted out, all of which are practical information.

Consider the code snippets for the following controller classes:

@ Controller public class UserController {@ Autowired private UserDAO userDAO; public String listUser () {/ / list all user processing methods userDAO.list ();} public String saveUser (User user) {/ / save / update user processing methods userDAO.save (user) } public String deleteUser (User user) {/ / delete the user's processing method userDAO.delete (user);} public String getUser (int userId) {/ / get the user's processing method userDAO.get (userId);}}

Here, all business logic related to user management is provided by the implementation of the UserDAO interface. For example:

Interface UserDAO {List list (); void save (User user); void checkLogin (User user);}

For more information about the @ Autowired annotation, see Annotation Type Autoassembly.

13. Access HttpServletRequest and HttpServletResponse

In some cases, you need to access the HttpServletRequest or HttpServletResponse object directly in the handler method.

With the flexibility of Spring, you only need to add relevant parameters to the processing method. For example:

@ RequestMapping ("/ download") public String doDownloadFile (HttpServletRequest request, HttpServletResponse response) {/ / access request / / access response return "DownloadPage";}

Spring detects and automatically injects HttpServletRequest and HttpServletResponse objects into the method. You can then access requests and responses such as getting InputStream, OutputStream or returning a specific HTTP code.

14. Follow the principle of single responsibility

Finally, when designing and writing Spring MVC controllers, there are two good practices that you should follow:

1) the controller class should not perform business logic. Instead, it should delegate business processing to the relevant business category. This keeps the controller focused on its design responsibility to control the workflow of the application. For example:

@ Controller public class UserController {@ Autowired private UserDAO userDAO; public String listUser () {userDAO.list ();} public String saveUser (User user) {userDAO.save (user);} public String deleteUser (User user) {userDAO.delete (user);} public String getUser (int userId) {userDAO.get (userId);}}

2) create each separate controller for each business domain. For example, UserController is used to control the OrderController workflow managed by users, to control the workflow of order processing, and so on. For example:

@ Controller public class UserController {} @ Controller public class ProductController {} @ Controller public class OrderController {} @ Controller public class PaymentController {} Thank you for your reading, this is the content of "what are the Spring MVC tips?" after the study of this article, I believe you have a deeper understanding of what the Spring MVC tips are, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report