Developing spring MVC with annotations

Posted by birdie on Tue, 01 Feb 2022 19:33:09 +0100

Developing spring MVC with annotations

Statement: This article is a study note, written according to spring MVC of madness theory
SpringMVC 4.2.4.RELEASE Chinese document

I. Development with annotations

1. We conduct POM Dependency injection of XML:

    <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>

In POM XML file introduces related dependencies: mainly Spring framework core library, Spring MVC, servlet, JSTL, etc. We have already introduced in parent dependency! So we don't have to inject into sub dependencies anymore.

2. Web Configuration of XML file:

<?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>

/Difference between and / *: < URL pattern > / < / url pattern > will not match jsp, only for the requests we write; Namely: jsp will not enter the DispatcherServlet class of spring< URL pattern > / * < / url pattern > will match * jsp, when returning to the jsp view, it will enter the DispatcherServlet class of spring again, resulting in a 404 error because the corresponding controller cannot be found.

Here we can see that we can find the path of the xml file through calsspath. So we want to create this xml file.

3. Spring MVC servlet Configuration of XML file

<?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 comments under the specified package effective,from IOC Unified container management -->
    <context:component-scan base-package="com.kdy.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
        Must register with 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>

This step is a fixed writing method, and it is also the most important step in developing spring MVC with annotations: as we all know, there are three major components that must be configured to use spring MVC: processor mapper, processor adapter and 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.

In other words, this configuration file configures these three major pieces!

4. Create Controller

package com.kdy.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;

return "hello" is to return / / Web inf / JSP / Hello JSP page.

5. View layer

<%--
  Created by IntelliJ IDEA.
  User: a
  Date: 2021/6/14
  Time: 14:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

The path of the view layer we created is: / Web inf / JSP / Hello jsp. Because the client cannot directly access / Web inf /, our creation is relatively safe.

Operation results:

Topics: Spring MVC SSM