Spring MVC Quick Start

Introduction

Yesterday, some fans asked me what I should learn in the later stage of Java. I told them that they should learn frameworks. However, for a large number of frameworks, most people don't know which one to start with. My personal learning suggestion is: first learn SSH (Struts 2, Hibernate, Spring), then learn Spring MVC, Spring Data, Mybatis, Spring Boot, Sp. Ring Cloud, finally completes some comprehensive cases. Of course, it's just my personal advice, and it doesn't necessarily apply to everyone, but the basic learning route should be like this.
For the javaee framework part of the article, I also follow this line. So, after learning the ssh framework, we should continue to learn Spring MVC.
This article is a quick introduction to Spring MVC.

Framework Introduction

Spring MVC is a follow-up product of Spring FrameWork and has been integrated into Spring Web Flow. The Spring framework provides a full-featured MVC module for building Web applications. Using Spring pluggable MVC architecture, when using Spring for WEB development, you can choose to use Spring's Spring MVC framework or integrate other MVC development frameworks, such as Struts 1 (now generally not used), Struts 2 (commonly used in old projects), etc.
Spring is an excellent Web framework based on MVC design concept for presentation layer. It is one of the most mainstream MVC frameworks at present. After Spring 3.0, it surpassed Struts 2 to become the best MVC framework. Spring MVC makes POJO the controller of processing requests without any interfaces through a set of MVC annotations.
Some people will question why we should learn Struts 2, since Spring MVC is better and better than Struts 2 framework. First of all, there's no harm in learning more. Secondly, some companies'old projects should still use Struts 2, so if you don't know Struts 2, you can't say it. Finally, if you learn Struts 2, you will be more proficient when you learn Spring MVC.

HelloWorld

There is no doubt that Hello World is the first entry project.
Implementation steps:

  1. Join the jar package
  2. Configure Dispatcher Servlet in web.xml
  3. Add Spring MVC configuration file
  4. Write a processor that handles requests and identify it as a processor
  5. Writing Views

1. Add jar packages

2. Configure Dispatcher Servlet in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
    <display-name>SpringMVC</display-name>

    <!-- To configure DispatcherServlet -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- Configuration initialization parameters -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

This is a fixed configuration, and if your development tool has Spring plug-ins, it's easy to type this code out.

Click on the blank to use the shortcut key, then select dispatcher servlet and return.
The init-param tag configures initialization parameters. The parameters it needs to configure are the location and name of the Spring MVC configuration file. If you have studied Struts 2, you will know that load-on-startup is set to 1, that is, the Servlet is created when the web container is loaded, and the others are similar to Struts 2.

3. Add Spring MVC configuration file
Create the Spring MVC configuration file in the src directory:

<?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- Configuring Packages for Automatic Scanning -->
    <context:component-scan base-package="com.itcast.spring"></context:component-scan>
    
    <!-- Configuration view parser -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
</beans>

These configurations have been mentioned in Spring, and will not be repeated. If you really don't understand them, you can refer to my previous articles.
This is the view parser provided by Spring MVC, which parses the return value of the control layer method into the actual physical view. I will elaborate on the details of the view parser in later articles, but I will not elaborate on it here.

4. Write a processor that handles requests and identify it as a processor

package com.itcast.spring.handler;

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

@Controller
public class HelloWorld {

    /**
     * Use the @RequestMapping annotation to map the requested URL
     * The return value is resolved to the actual physical view through the view parser
     * 
     * @return
     */
    @RequestMapping("/helloworld")
    public String hello() {
        System.out.println("hello world");
        return "success";
    }
}

This class is marked as a controller by @Controller and managed by the Spring IOC container.

5. Writing Views

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <a href="helloworld">Hello World</a>
</body>
</html>

Here, a basic case is completed. Let's analyze the execution process in detail.
First we visit index.jsp, which has a hyperlink. By clicking on the hyperlink, we issue a request for / helloworld. At this point, the spring Dispatcher Servlet configured in web.xml intercepts the request. Then the Spring IOC container matches the relevant controller, because it is on the hello() method in the HelloWorld class. Face annotates the mapping request path @RequestMapping("/helloworld"), so if the hyperlink requests match the method successfully, the method will be executed and the "success" string returned. The return value is resolved to the actual physical view through the view parser, while the resolution rule of the Internal ResourceViewResolver parser is prefix + return Val + suffix. That is to say, the / WEB-INF/views/ we configured in the parser with the return value "success" +suffix ".jsp" will point to the physical view (/WEB-INF/views/success.jsp).
So we create a new views folder under the WEB-INF directory, and then create a new success.jsp file:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h4>Success Page</h4>
</body>
</html>

After this series of process processing, when we click on the hyperlink, the page will jump to the success.jsp page. Is that true? The operation is clear:

Other Contents

For configurations in web.xml files, you can actually use the default configuration file instead of configuring init-param initialization parameters. But the default configuration file has a few fastidious features:

  • Must be placed in WEB-INF directory
  • The file name must be <servlet-name> +-servlet.xml

What does that mean?

In this project, the name of the configuration file should be spring Dispatcher Servlet-servlet.xml, because servlet-name can be defined at will, so the name of the configuration file can follow at will.

Tags: Java Spring xml Struts JSP

Posted on Sun, 25 Aug 2019 20:59:32 -0700 by Crystal Dragon