Spring MVC – get started

01-Servlet

  • MVC is a shorthand for Model, View and Controller. It is a software design specification.
  • Is a way to organize code by separating business logic, data, and presentation.
  • The main function of MVC is to reduce the two-way coupling between view and business logic.
  • MVC is not a design pattern. MVC is an architectural pattern. Of course there are differences between MVC’s.

**Model: ** Data Model, which provides the data to be presented and therefore contains the data and behavior, can be thought of as a domain Model or JavaBean component (containing the data and behavior), but is now generally separated: Value Object (data Dao) and behavior Service layer (behavior Service). That is, the model provides model data query and model data status update functions, including data and business.

**View: ** is responsible for presenting the model, which is generally the user interface we see, what the customer wants to see.

**Controller (Controller) : ** Receives user requests, delegates them to the model for processing (state changes), and returns the returned model data to the view, which is responsible for displaying it. So the controller is doing the job of a dispatcher.

1. Create project Spring-MVC (Maven)

Parent project dependencies

<? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > The < modelVersion > 4.0.0 < / modelVersion > < groupId > org. Example < / groupId > < artifactId > Spring Mvc - < / artifactId > <packaging> POM </packaging> <version> 1.0-snapshot </version> <modules> <module>01-servlet</module> </modules> <properties>  <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> < version > 5.1.9. RELEASE < / version > < / dependency > < the dependency > < groupId > javax.mail. Servlet < / groupId > < < artifactId > servlet - API/artifactId > < version > 2.5 < / version > < / dependency > < the dependency > <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency> <! Servlet </groupId> <artifactId> JSTL </artifactId> <version>1.2</version> </dependency> </dependencies> </project>Copy the code

Subprojects also need to import dependencies.

<dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet. JSP </groupId> <artifactId>jsp-api</artifactId> <version>2.2</version>  </dependency>Copy the code

After creating the package com.gip. Servlet, create a class HelloServlet that inherits HttpServlet

package com.gip.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // get parameters
        String method = req.getParameter("method");
        if (method.equals("add")){
            req.getSession().setAttribute("msg"."Execute add method");
        }
        if (method.equals("delete")){
            req.getSession().setAttribute("msg"."Delete method executed");
        }

        req.getRequestDispatcher("WEB-INF/jsp/hello.jsp").forward(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code

Tip: ALT+Ins in idea editor, select override parent methods doGet, doPost

Create hello.jsp after creating the JSP folder

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

${msg}


</body>
</html>

Copy the code

Configure web.xml, register servlets, and match paths

<? The 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" > <! < Servlet > <servlet-name>HelloServlet</servlet-name> <servlet-class>com.gip.servlet.HelloServlet</servlet-class> </servlet> <! <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern> </servlet-mapping> </web-app>Copy the code

Configure Tomcat

02-hellomvc

Add web framework dependencies after the project is created

Configure web. XML

<? The 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" > <! <servlet> < servletname > Springmvc </ servletname > <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! XML --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <! - start level 1 - > < the load - on - startup > 1 < / load - on - startup > < / servlet > <! --/ Match all requests; (not including.jsp) --> <! --/* Match all requests; --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>Copy the code

Create HelloController class, implement Controller interface, override method

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; public class HelloController implements Controller { public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse Response) throws Exception {//ModelAndView mv = new ModelAndView(); // Encapsulate the object and place it in ModelAndView. Model mv.addObject("msg","HelloSpringMVC!" ); // Encapsulate the view to jump to and place it in ModelAndView mv.setViewName("hello"); //: /WEB-INF/jsp/hello.jsp return mv; }}Copy the code

Creating a JSP file

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

Creating a Lib folder

Adding dependencies

After all ok

Package run project

http://localhost:8080/hello

03-annotation

1, Create a new Moudle, SpringMVC-03-hello-annotation. Add Web support!

2. Since Maven may have problems with resource filtering, we will complete the configuration

<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>
Copy the code

3. Introduce related dependencies in the POP. XML file: mainly Spring framework core library, Spring MVC, Servlet, JSTL, etc. We already introduced parent dependencies!

4. Configure web.xml

Note:

<? The 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" > <! <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! Specify the location of the SpringMVC configuration file with the initialization parameter. > <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <! <load-on-startup>1</load-on-startup> </servlet> <! -- All requests will be blocked by springMVC --> <servlet-mapping> <servlet-name> springmvc </servlet-name> <url-pattern> </servlet-mapping> </web-app>Copy the code

The difference between/and /* : < url-pattern > /
does not match.jsp, only for requests we wrote; That is,.jsp does not enter Spring’s DispatcherServlet class. < url-pattern > /*
will match *.jsp, and the DispatcherServlet class will be entered again when the JSP view is returned.

    • Watch out for web.xml versioning issues, keep it up to date!

    • Registered DispatcherServlet

    • Associate the SpringMVC configuration file

    • The boot level is 1

    • The mapping path is /

  1. Add the Spring MVC configuration file

  2. Add the springMVC-servlet.xml configuration file to the resource directory. The configuration form is basically similar to the Spring container configuration. In order to support annotation based IOC, the automatic package scanning function is configured as follows:

<? The 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"> <! <context:component-scan base-package="com.kuang. Controller "/> <! Let Spring MVC not handle static resources --> < MVC :default-servlet-handler /> <! - support the MVC annotation driven @ RequestMapping commonly used in spring annotations to complete the mapping relationship To make the @ RequestMapping annotations to take effect Must be registered DefaultAnnotationHandlerMapping with the context And a AnnotationMethodHandlerAdapter instance this two instances in class level and treatment level. The annotation-driven configuration helps us to automate the injection of the above two instances. --> <mvc:annotation-driven /> <! - view the parser - > < bean class = "org. Springframework. Web. Servlet. The InternalResourceViewResolver" id="internalResourceViewResolver"> <! Prefix -- - > < property name = "prefix" value = "/ WEB - INF/JSP/" / > <! -- suffix - > < property name = "suffix" value = "JSP" / > < / bean > < / beans >Copy the code
  1. In the view resolver we store all views in the /WEB-INF/ directory. This keeps the view safe because the files in this directory cannot be accessed directly by clients.

    • Let the IOC’s annotations stand
    • Static resource filtering: html.js.css. images, videos…..
    • Annotation-driven MVC
    • Configure the view resolver
  2. 6. Create Controller

  3. Write a Java control class: com. Kuang. Controller. The HelloController, pay attention to the coding standards

package com.kuang.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 retrieved and rendered in a JSP page
       model.addAttribute("msg"."hello,SpringMVC");
       //web-inf/jsp/hello.jsp
       return "hello"; }}Copy the code
  • The @Controller is intended to be scanned automatically when the Spring IOC container is initialized;
  • @requestMapping = /HelloController/hello; @requestMapping = /HelloController/hello;
  • Methods declare parameters of type Model to bring the Action data to the view;
  • Method returns the view’s name hello, changed to web-INF/JSP /hello.jsp with the prefix and suffix in the configuration file.

Create a view layer

  1. Create hello.jsp in the WEB-INF/ JSP directory. The view can directly fetch and display the information brought back from the Controller.

  2. You can use EL to fetch values or objects stored in the Model;

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

8. Configure Tomcat to run

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

summary

The implementation steps are actually quite simple:

  1. Create a New Web project
  2. Import related JAR packages
  3. Write web.xml and register DispatcherServlet
  4. Write the SpringMVC configuration file
  5. The next step is to create the corresponding control class, Controller
  6. Finally, improve the correspondence between the front view and controller
  7. Tests run debugging.

There are three things you must configure to use springMVC:

Processor mapper, processor adapter, view resolver

Typically, you only need to configure the view parser manually, while the processor mapper and processor adapter just need to turn on the annotation driver, eliminating a large chunk of XML configuration

Let’s review the principle again

The Controller summary

Controller is the Controller

  • Controller complexity provides access to the behavior of the application, usually through interface definition or annotation definition.

  • The controller is responsible for parsing the user’s request and transforming it into a model.

  • A controller class can contain multiple methods in Spring MVC

  • In Spring MVC, there are many ways to configure controllers

Implementing the Controller interface

Controller is an interface in the org. Springframework. Web. Servlet. MVC package, the interface is only one way;

Public interface Controller {// handle the request and return a ModelAndView object ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception; }Copy the code

test

  1. Create a new Moudle, SpringMVC-04-Controller. Make a copy of 03 just now and let’s operate!

    • Delete the HelloController
    • The MVC configuration file only leaves the view parser!
  2. Write a Controller class, ControllerTest1

    // Define Controller // note: do not error package, implement Controller interface, rewrite method; public class ControllerTest1 implements Controller { public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse HttpServletResponse) throws Exception {// Return a ModelAndView mv = new ModelAndView(); mv.addObject("msg","Test1Controller"); mv.setViewName("test"); return mv; }}Copy the code
  3. Once written, register the requested bean in the Spring configuration file; Name corresponds to the request path, and class corresponds to the class that processes the request

    <bean name="/t1" class="com.kuang.controller.ControllerTest1"/>
    Copy the code
  4. Write the front-end test.jsp in the web-INF/JSP directory corresponding to our view parser

    <%@ page contentType="text/html; charset=UTF-8" language="java" %> <html> <head> <title>Kuangshen</title> </head> <body> ${msg} </body> </html>Copy the code
  5. Configure Tomcat to run the test, I do not have the project release name configured here is a /, so the request does not need to add the project name, OK!

Description:

  • The older approach is to define a Controller

  • Disadvantages: There is only one method in a Controller. If you want multiple methods, you need to define multiple controllers. The way it’s defined is tricky;

Use the annotation @controller

  • The @Controller annotation type is used to declare that an instance of a Spring class is a Controller (there are three other annotations mentioned in IOC);

  • Spring can use a scanning mechanism to find all annotated controller classes in your application. To ensure that Spring can find your controller, declare component scanning in your configuration file.

    <! <context:component-scan base-package="com.kuang. Controller "/>Copy the code
  • Add a ControllerTest2 class, implemented using annotations;

    // @controller annotated classes are automatically added to the Spring context @Controller Public Class ControllerTest2{// @requestMapping ("/t2") public String index(Model Model){//Spring MVC automatically instantiates a Model object that passes the value model.addattribute (" MSG ", "ControllerTest2"); Return "test"; }}Copy the code
  • Running tomcat tests

As you can see, both of our requests can point to a view, but the results of the page results are different. From this, you can see that the view is reused, and there is a weak coupling between the controller and the view.

Annotation mode is usually used the most way!

RequestMapping

@RequestMapping

  • The @requestMapping annotation is used to map a URL to a controller class or to a specific handler method. Can be used on classes or methods. Used on a class, this address is used as the parent path for all methods in the class that respond to requests.

  • To test the results more accurately, we can add a project name to test myWeb

  • Comment only on methods

    @Controller public class TestController { @RequestMapping("/h1") public String test(){ return "test"; }}Copy the code

    Access path: http://localhost:8080 / Project name/h1

  • Annotate both classes and methods

    @Controller @RequestMapping("/admin") public class TestController { @RequestMapping("/h1") public String test(){ return "test"; }}Copy the code

    Access path: http://localhost:8080 / project name/admin /h1. Specify the path of the class and then the path of the method.