Spring mvc-part02 first MVC program

Keywords: Java Spring mvc

2. First MVC program


2.1 configuration version

1. Create a new Moudle, springmvc-02-hello, and add web support!

2. Confirm that the dependency of spring MVC is imported!

3. Configure web.xml and register dispatcher Servlet

<?xml version="1.0" encoding="UTF-8"?>
   <!--1.register DispatcherServlet-->   
    <!--Associate a springmvc Configuration file for:[servlet-name]-servlet.xml-->       
    <!--Startup level-1-->       
   <!--/ Match all requests; (excluding.jsp)-->  
    <!--/* Match all requests; (including.jsp)-->

4. Write the spring MVC configuration file! Name: SpringMVC-servlet.xml: [servletname] - servlet.xml

Note that the name requirements here are in accordance with the official

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xsi:schemaLocation="http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/spring-beans.xsd">

5. Add process mapper

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

6. Add processor adapter

<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

7. Add view parser

<!--view resolver :DispatcherServlet Give it to him ModelAndView-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">   
    <property name="prefix" value="/WEB-INF/jsp/"/>   
    <property name="suffix" value=".jsp"/>

8. Write the business Controller that we want to operate, either implement the Controller interface or add annotations; we need to return a ModelAndView, load data and seal the view;

package com.kuang.controller;
import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;
//Note: let's import the Controller interface first
public class HelloController implements Controller {
   public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {       //ModelAndView models and views       
       ModelAndView mv = new ModelAndView();
       //Encapsulate the object and place it in ModelAndView       
       //Encapsulate the view to jump to and put it in ModelAndView      
       //: /WEB-INF/jsp/hello.jsp       
       return mv;  

9. Give your class to the spring IOC container and register the bean

<!--Handler--><bean id="/hello" class="com.kuang.controller.HelloController"/>

10. Write the jsp page to jump to, display the data stored in ModelandView, and our normal page;

<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>   <title>Kuangshen</title></head><body>${msg}</body></html>

11. Configure Tomcat startup test!

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-48nykbzx-163869362110) (E: \ desktop \ document \ javaweb\SpringMVC.assets\image-20211205175708225.png)]

Possible problems: visit 404, troubleshooting steps:

  1. Check the console output to see if there is any missing jar package.
  2. If the jar package exists and the display cannot be output, add lib dependency in the project release of IDEA!
  3. Restart Tomcat to solve the problem!

Summary: looking at this, it is estimated that most students can understand the principle, but we won't write it in actual development, otherwise we will be crazy. Why do we learn this thing? Let's look at an annotation version implementation, which is the essence of spring MVC. Just look at this figure.

2.2 annotated version

1. Create a new Moudle, springmvc-03-hello-annotation. Add web support!

2. Since Maven may have the problem of resource filtering, we will improve the configuration


3. Introduce relevant dependencies in pom.xml file: mainly Spring framework core library, Spring MVC, servlet, JSTL, etc. we have introduced them in parent dependencies!

4. Configure web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    <!--1.register servlet-->
        <!--Specified by initialization parameters SpringMVC The location of the configuration file is associated-->
        <!-- Start sequence: the smaller the number, the earlier the start -->
    <!--All requests will be rejected springmvc intercept -->

/Difference from / *: < URL pattern > / < / url pattern > will not match. jsp, but only for the request we write; that is:. jsp will not enter the DispatcherServlet class of spring. < URL pattern > / * < / url pattern > will match *. jsp, and will enter the DispatcherServlet class of spring again when returning to the jsp view, resulting in no corresponding controller, so a 404 error is reported.

  • Pay attention to the version of web.xml. Keep the latest version!

  • Register DispatcherServlet

  • Associated spring MVC configuration file

  • The startup level is 1

  • The mapping path is / [do not use / *, it will 404]

5. Add Spring MVC configuration file

Add the springmvc-servlet.xml configuration file in the resource directory. The configuration form is basically similar to the Spring container configuration. In order to support annotation based IOC, the function of automatic package scanning is set. The specific configuration information is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    <!-- Automatically scan the package to make the annotations under the specified package effective,from IOC Unified container management -->
    <context:component-scan base-package="com.shuang.controller"/>
    <!-- Give Way Spring MVC Do not process static resources -->
    <mvc:default-servlet-handler />
    support mvc Annotation driven
        stay spring Generally used in@RequestMapping Annotation to complete the mapping relationship
        To make@RequestMapping Note effective
        You must register with the context DefaultAnnotationHandlerMapping
        And one AnnotationMethodHandlerAdapter example
        These two instances are handled at the class level and method level, respectively.
        and annotation-driven Configuration helps us automatically complete the injection of the above two instances.
    <mvc:annotation-driven />

    <!-- view resolver  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        <!-- prefix -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- suffix -->
        <property name="suffix" value=".jsp" />


In the view parser, we store all views in the / WEB-INF / directory, which can ensure the view security, because the files in this directory cannot be accessed directly by the client.

  • Make IOC comments effective

  • Static resource filtering: HTML. JS. CSS. Pictures, videos

  • Annotation driven MVC

  • Configure view parser

6. Create Controller

Write a Java control class: com.kuang.controller.HelloController. Pay attention to the coding specification

package com.shuang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

public class HelloController {
    //Real access address: project name / HelloController/hello
    public String hello(Model model){
        //Encapsulate data
        //Add attributes msg and values to the model, which can be taken out and rendered in the JSP page

        return "hello";//Will be processed by the view parser
  • @The Controller is used to automatically scan the Spring IOC container during initialization;

  • @RequestMapping is to map the request path. Here, because there are mappings on classes and methods, the access should be / HelloController/hello;

  • The purpose of declaring Model type parameters in the method is to bring the data in the Action to the view;

  • The result returned by the method is the name of the view Hello, plus the prefix and suffix in the configuration file to become WEB-INF/jsp/hello.jsp.

7. Create view layer

Create hello.jsp in the WEB-INF/ jsp directory. The view can directly take out and display the information brought back from the Controller;

The value or object stored in the Model can be retrieved through EL representation;

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

8. Configure Tomcat run

Configure Tomcat, start the server and access the corresponding request path!

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-vgguz7si-163869362112) (E: \ desktop \ document \ JavaWeb \ springmvc. Assets \ image-202112051758170. PNG)]

OK, run successfully!

2.3 summary

The implementation steps are actually very simple:

  1. Create a new web project
  2. Import related jar packages
  3. Write web.xml and register DispatcherServlet
  4. Writing spring MVC configuration files
  5. The next step is to create the corresponding control class, controller
  6. Finally, improve the correspondence between the front-end view and the controller
  7. Test run commissioning

Three major components that must be configured to use spring MVC:

Processor mapper, processor adapter, view parser

Usually, we only need to manually configure the view parser, while the processor mapper and processor adapter only need to turn on the annotation driver, eliminating a large section of xml configuration

Let's review the principle~

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-uijjb4lw-163869362112) (E: \ desktop \ document \ javaweb\SpringMVC.assets\image-20211205175858987.png)]

Spring MVC execution principle

  1. DispatcherServlet represents the front controller and is the control center of the whole spring MVC. When the user sends a request, the DispatcherServlet receives the request and intercepts the request.
    1. We assume that the requested url is: http://localhost:8080/SpringMVC/hello ·
    2. As above, the url is divided into three parts:
    3. http://localhost:8080 Server domain name
    4. Spring MVC is a web site deployed on the server. hello represents the controller
    5. Through analysis, the above url is expressed as: request the hello controller of the spring MVC site located on the server localhost:8080.
  2. HandlerMapping is processor mapping. Dispatcher servlet call
  3. HandlerMapping,HandlerMapping finds HandIxr according to the request url.
  4. HandlerExecution refers to a specific Handler. Its main function is to find the controller according to the url. The controller found by the url above is: hello.
  5. HandlerExecution passes the parsed information to DispatcherServlet, such as parsing controller mapping. The HandlerAdapter represents a processor adapter that executes the Handler according to specific rules.
  6. The Handler lets the specific Controller execute.
  7. The Controller returns the specific execution information to the HandlerAdapter, such as ModelAndView. The HandlerAdapter passes the view logical name or model to the dispatcher servlet.
  8. DispatcherServlet calls the view resolver to resolve the logical view name passed by the HandlerAdapter.
    The view parser passes the parsed logical view name to the dispatcher servlet.

1-4 servlet-mapping

5-8 servlet

10-12 servlet request forwarding and redirection

This article comes from Bili Bili Madness theory Study notes

Posted by moyse on Sun, 05 Dec 2021 17:21:12 -0800