Development of spring MVC using annotations and resolution of common errors

Spring MVC is developed using annotations

Since Maven may have the problem of resource filtering, we will XML configuration improvement

<build>
   <resources>
       <resource>
           <directory>src/main/java</directory>
           <includes>
               <include>**/*.properties</include>
               <include>**/*.xml</include>
           </includes>
           <filtering>false</filtering>
       </resource>
       <resource>
           <directory>src/main/resources</directory>
           <includes>
               <include>**/*.properties</include>
               <include>**/*.xml</include>
           </includes>
           <filtering>false</filtering>
       </resource>
   </resources>
</build>
  1. In POM XML file introduces related dependencies: mainly Spring framework core library, Spring MVC, servlet, JSTL, etc. We have already introduced in parent dependency!

    <dependencies>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1.3-b06</version>
    
        </dependency>
    
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
    
  2. On the web XML, which is fixed

    /Difference between and / *: < URL pattern > / < / url pattern > will not match jsp, only for the requests we write; Namely: jsp does not enter the DispatcherServlet class of spring< URL pattern > / * < / url pattern > will match * jsp, when the jsp view is returned, the dispatcher servlet class of spring will be entered again, resulting in no corresponding controller, so a 404 error will be reported.

      • Note web XML version problem, to 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]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--1.register servlet-->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--Specified by initialization parameters SpringMVC The location of the configuration file is associated-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!-- Start sequence: the smaller the number, the earlier the start -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!--All requests will be rejected springmvc intercept -->
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

  1. Configure spring MVC servlet in the resources directory XML, fixed

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/mvc
           https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <!-- Automatically scan the package to make the annotations under the specified package effective,from IOC Unified container management -->
        <context:component-scan base-package="com.yang.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"
              id="internalResourceViewResolver">
            <!-- prefix -->
            <property name="prefix" value="/WEB-INF/jsp/" />
            <!-- suffix -->
            <property name="suffix" value=".jsp" />
        </bean>
    
    </beans>
    
  2. Create Controller

    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    @RequestMapping("/HelloController")
    public class HelloController {
    
       //Real access address: project name / HelloController/hello
       @RequestMapping("/hello")
       public String sayHello(Model model){
           //Add attributes msg and values to the model, which can be taken out and rendered in the JSP page
           model.addAttribute("msg","hello,SpringMVC");
           //web-inf/jsp/hello.jsp
           return "hello";
      }
    }
    
    • @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 hello of the view, and the prefix and suffix in the configuration file become WEB-INF / JSP / hello jsp.
  3. Create view layer

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
       <title>SpringMVC</title>
    </head>
    <body>
    ${msg}
    </body>
    </html>
    
  4. Configure Tomcat run

Summary:

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

The schematic diagram is as follows:

Possible errors

  1. No configuration for resource filtering was imported

        <build>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
            </resources>
        </build>
    
  2. The package in lib directory is not imported into the project. This is because idea is not imported automatically. There will be 404 errors

    • Open the structure in idea
  • Check whether the project to be published has a lib directory

  • If not, import the lib directory

  • Import the corresponding jar package


Keywords: Spring MVC

Added by Toby on Sun, 19 Dec 2021 19:16:37 +0200