Share 14 top tips of Spring MVC!

Author: Nam Ha Minh https://dzone.com/articles/14-tips-for-writing-spring-mvc-controller

Blog.csdn.net/summer'lyf/article/details/102911215

Usually, in Spring MVC, we write a controller class to handle requests from clients. Then, the controller calls the business class to handle the business related tasks, and then redirects the client to the logical view name, which is parsed by Spring's scheduler Servlet to render the result or output.

This completes a typical request response cycle.

Today, I sorted out 14 tips for writing Spring MVC controller. Did you get them today?  \(≧▽≦)/

1. Use @ Controller modeling

This is the easiest way to create a Controller class that can handle one or more requests. Only annotate a class @ Controller with a 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 a view called home.

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

<annotation-driven />

When annotation driven is enabled, the Spring container automatically scans the classes under the package specified by the following statement:

<context:component-scan base-package="net.codejava.spring" />

The class annotated by the @ Controller annotation is configured as a Controller. This is preferable because it's simple: you don't need to declare bean s in the configuration file for the Controller.

Note: by using @ 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 from the above controller class, there are three processing methods for processing three different requests: listUsers, / saveUser, / UU and / deleteUser.

2. Implement controller interface

Another (perhaps Classic) way to create controllers in Spring MVC is to have classes 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 a matching request enters. The request URL pattern processed by this controller is defined in the context configuration file of Spring as follows:

<bean name="/main" class="net.codejava.spring.MainController" />

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

3. Extend AbstractController class

If you want easy control over supported HTTP methods, sessions, and content caching. Extending your controller AbstractController class is ideal. 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 configuration about supported methods, sessions, and caches, which can then be specified in the bean declaration of the controller. For example:

<bean name="/big" class="net.codejava.spring.BigController">  
    <property name="supportedMethods" value="POST"/>  
</bean>

This configuration indicates that POST only supports the handler method of this controller.

Spring MVC also provides several purpose specific controller classes, including:

  • AbstractUrlViewController

  • MultiActionController

  • ParameterizableViewController

  • ServletForwardingController

  • ServletWrappingController

  • UrlFilenameViewController

4. Specify URL mapping for handler methods

This is a mandatory task that must be performed when encoding 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 pattern / login is 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 patterns to be processed by a method. For example:

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

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

5. Specify HTTP request method for handler method

You can use the method attribute of the annotation to specify which HTTP method (GET, POST, PUT, etc.) the handler method supports @ RequestMapping. Here 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 pattern, but the former is for the GET method and the latter is for the POST method. For more information about using the @ RequestMapping annotation, see the @ RequestMapping annotation.

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 controller HttpServletRequest from the Servlet API interface.

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

Spring binds method parameter user names and passwords to HTTP request parameters with the same name. This means that you can call the URL as follows (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 an integer parameter of the following type:

@RequestParam int securityNumber

Spring will then automatically convert 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 properties, 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 will be null if such a parameter does not exist in the request.

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 if the method parameter is type, Spring also allows us to access map < string, string > as an object. For example:

doLogin(@RequestParam Map<String, String> params)

The mapping parameters then contain all the request parameters in the form of key value pairs. For more information about using the @ RequestParam annotation, see the @ RequestParam annotation. WeChat official account: Java technology stack, back in the background: spring, can get the latest Spring tutorial I have compiled N, all dry cargo.

7. Return to model and view

After processing the business logic, the handler method should return a view, which is then parsed by spring's scheduler servlet. Spring allows ModelAndView to return a String or object from the 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<User> listUser = new ArrayList<>();  
    // Get 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 where ModelAndView holds the view name UserList and a collection of objects that can be used in the view. Spring interview 7 questions, Recommend it.

Spring is also very flexible, because you can declare ModelAndView objects as parameters of handler methods without creating a new object. Therefore, the above example can be rewritten as follows:

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

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

8. put the object into the model

In an application that follows 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 Map parameters of type in handler methods. Spring uses this mapping to store objects for the model. Let's take another example:

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

This is simpler than using ModelAndView objects. Depending on your preference, you can use Map or use ModelAndView objects. Thanks to Spring's flexibility.

9. Redirection in handler methods

If you want to redirect the user to another URL when the conditions are met, please redirect: / append before the URL. The following code snippet shows an example:

// Check login status  
if (!isLogin) {  
    return new ModelAndView("redirect:/login");  
}  
// Return to user list

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

10. Handling 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 an interface for BindingResult to validate form fields. The following code snippet shows a typical handler method that handles 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 {  
            // No problem with form input  
        }  
        // Registration process  
        return "Success";  
    }  
}

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

  • Use @ ModelAttribute on method parameters

  • Use @ ModelAttribute on method

  • Interface binding results

11. Handling file upload

Spring also makes it easy to handle file uploads in handler methods by automatically binding the upload data to the CommonsMultipartFile object array. Spring uses Apache Commons FileUpload as the base 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 uploaded files  
        aFile.transferTo(new File(aFile.getOriginalFilename()));  
    }  
    return "Success";  
}

12. Automatic assembly of business class in the controller

The controller shall delegate the processing of business logic to the relevant business class. To do this, you can use the @ Autowired annotation to let spring automatically inject the actual implementation of the business class into the controller. WeChat official account: Java technology stack, back in the background: spring, can get the latest Spring Boot tutorial I have compiled, N dry cargo.

Consider the code snippet for the following controller classes:

@Controller  
public class UserController {  
    @Autowired  
    private UserDAO userDAO;  
    public String listUser() {  
        // List processing methods for all users  
        userDAO.list();  
    }  
    public String saveUser(User user) {  
        // How to save / update users  
        userDAO.save(user);  
    }  
    public String deleteUser(User user) {  
        // Delete 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<User> list();  
    void save(User user);  
    void checkLogin(User user);  
}

For more information about @ Autowired annotations, see annotation type autoassemble.

13. Access HttpServletRequest and HttpServletResponse

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

With Spring's flexibility, you just 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 methods. You can then access requests and responses such as get InputStream, OutputStream, or return a specific HTTP code.

14. Follow the principle of single responsibility

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

1) The controller class should not execute business logic. Instead, it should delegate business processing to the relevant business category. This keeps the controller focused on its design responsibility of controlling 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 individual controller for each business domain. For example, UserController is used to control the OrderController workflow of user management, the workflow of order processing, etc. For example:

@Controller  
public class UserController {  
}  
@Controller  
public class ProductController {  
}  
@Controller  
public class OrderController {  
}  
@Controller  
public class PaymentController {  
}

These 14 tips can help you write controller classes correctly and effectively in Spring MVC. If you have other tips or suggestions, please feel free to share your thoughts in the comments.

Recommend to my blog to read more:

1.Java JVM, collection, multithreading, new features series

2.Spring MVC, Spring Boot, Spring Cloud series tutorials

3.Maven, Git, Eclipse, Intellij IDEA series tools tutorial

4.Latest interview questions of Java, backend, architecture, Alibaba and other large factories

Life is beautiful. See you tomorrow

Tags: Programming Spring Java encoding Attribute

Posted on Tue, 17 Mar 2020 22:55:56 -0400 by Desdinova