An overview of the

After spending a lot of time with SpringBoot and being poisoned by its convenience of convention over configuration, I wanted to go back to SpringMVC and see how users were involved in the Development model. This article will give you a taste of the process developed in the SpringMVC era.

Note: This article was published on My public account CodeSheep. You can subscribe by holding down or scanning the heart below ↓ ↓ ↓


The SpringMVC architectural pattern

A typical SpringMVC request flow is shown in 12 steps:

  1. The user initiates a request, which is processed by the front-end controller DispatcherServlet
  2. The front-end controller looks up the Hander through the processor mapper, either based on XML or annotations
  3. The processor mapper returns the chain of execution
  4. The front-end controller requests the processor adapter to execute the Hander
  5. Processor adapter to execute handler
  6. When the processing is complete, the processor adapter is returned with a ModeAndView object containing the view name and model data
  7. The processor adapter returns the view name and model data to the front controller
  8. The front controller parses the view through the view parser
  9. The view resolver returns the real view to the front controller
  10. The front-end controller renders through the returned view and data
  11. Returns the rendered view
  12. The final view is returned to the user, generating a response

The whole process is clear and clear, and we will understand the whole process based on actual experiments.


SpringMVC project construction

The experimental environment is as follows:

  • IntelliJ IDEA 2018.1 (Ultimate Edition)
  • For SpringMVC v4.3.9. RELEASE
  • Maven 3.3.9

Here I used IDEA to build a Maven-based SpringMVC project. The construction process will not be described again. Various clicks and next steps will finally create the project architecture as follows:


Add front-end controller configurations

With SpringMVC, all requests should be managed by SpingMVC, which intercepts all eligible requests on SpringMVC’s proprietary Servlet.

To do this we need to add SpringMVC’s front-end controller DispatcherServlet to web.xml:

<! -- SpringMvc front-end controller --> <servlet> <servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:mvc-dispatcher.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping>Copy the code

This configuration indicates that all urls that match. Action are handled by the MVC-Dispatcher Servlet


Write the SpringMVC core XML configuration file

As you can see from the previous configuration, the MVC-Dispatcher Servlet we define relies on the configuration file MVC-Dispatcher.xml, to which we need to add three aspects of configuration in this step

  • 0x01. Add processor mapper
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
Copy the code

For SpringMVC processor mapper has a variety of, here the use of BeanNameUrlHandlerMapping the mapping rules is to the bean’s name as a url for processing

  • 0x02. Add processor adapter
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
Copy the code

For SpringMVC processor adapter has a variety of, here the use of SimpleControllerHandlerAdapter is Controller implementation class adapter class, its essence is to perform the handleRequest method in the Controller.

  • 0x03. Add attempt resolver
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" />
Copy the code

After configure the parser InternalResourceViewResolver view here, it can be carried according to the method of the controller after the return to the location of the view of the ModelAndView, to load the corresponding interface and binding data


Writing controller

The simulation here is a Service to print the list of students. The controller we write needs to render the query of the list of students to the specified JSP page through ModelAndView

public class TestController implements Controller {

    private StudentService studentService = new StudentService();

    @Override
    public ModelAndView handleRequest( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        List<Student> studentList = studentService.queryStudents();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("studentList",studentList);
        modelAndView.setViewName("/WEB-INF/views/studentList.jsp");
        return modelAndView;
    }
}

class StudentService {
    public List<Student> queryStudents() {
        List<Student> studentList = new ArrayList<Student>();

        Student hansonwang = new Student();
        hansonwang.setName("hansonwang99");
        hansonwang.setID("123456");

        Student codesheep = new Student();
        codesheep.setName("codesheep");
        codesheep.setID("654321");

        studentList.add(hansonwang);
        studentList.add(codesheep);

        returnstudentList; }}Copy the code

Writing a view file

The view file here is a JSP file, the path as: / WEB – INF/views/studentList. JSP

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> < HTML > <head> <title> </head> <body> <h3> <table width="300px;"Border =1> <tr> < TD > Name </ TD > < TD > Student number </ TD > </tr> <c:forEach items="${studentList}" var="student" >
            <tr>
                <td>${student.name}</td>
                <td>${student.ID}</td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>
Copy the code

Combining this step with the previous step, the view and controller are written, since the processor mapper we configured earlier is: BeanNameUrlHandlerMapping, so now we need the MVC – the dispatcher. One can be configured in the XML file url mapping controller bean, For the processor mapper BeanNameUrlHandlerMapping search:

<bean name="/test.action" class="cn.codesheep.controller.TestController" />
Copy the code

The experimental test

Start the Tomcat server and type in your browser:

http://localhost:8080/test.action
Copy the code

Data rendering OK.

Note: Of course, this article uses a non-annotated configuration approach that requires configuration in XML and follows various implementation principles. The more general, mainstream annotation-based configuration approach will be detailed in a future article.

Shout, long sigh of relief, such a small Demo with SpringMVC completed, various XML configuration for a long time, really troublesome ah, forget, or back to SpringBoot!


Afterword.

  • The author’s more original articles are here, welcome to watch

  • My Personal Blog

The author has more SpringBt practice articles here:

  • Spring Boot application monitoring actual combat
  • The SpringBoot application is deployed in an external Tomcat container
  • ElasticSearch in SpringBt practice
  • A preliminary study on Kotlin+SpringBoot joint programming
  • Spring Boot Logging framework practices
  • SpringBoot elegant coding: Lombok plus

If you are interested, take some time to read some of the author’s articles on containerization and microservitization:

  • Use K8S technology stack to create personal private cloud serial articles
  • Nginx server configuration from a detailed configuration list
  • Docker container visual monitoring center was built
  • Use ELK to build Docker containerized application log center
  • RPC framework practice: Apache Thrift
  • RPC framework practice: Google gRPC
  • Establishment of microservice call chain tracking center
  • Docker containers communicate across hosts
  • Preliminary study on Docker Swarm cluster
  • Several guidelines for writing dockerFiles efficiently