Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

hardcore! This article gives you an in-depth understanding of SpringMVC


Jun 01, 2021 Article blog


Table of contents


First, SpringMVC overview

  • Spring's excellent Web framework based on MVC design concepts for the presentation layer is one of the most mainstream MVC frameworks available today
  • Spring3.0 went 超越 Struts2 to become the best MVC framework
  • Spring MVC uses a set of MVC annotations to make POJO the controller that processes requests without implementing any interfaces.
  • REST URL requests are supported
  • The 松散耦合可插拔 component structure is more scalable and flexible than other MVC frameworks

Second, SpringMVC simple to use

1) Configure DispatcherServlet in the web .xml:

<!-- 配置 DispatcherServlet -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 配置 DispatcherServlet 的一个初始化参数: 配置 SpringMVC 配置文件的位置和名称 -->
        <!-- 
            实际上也可以不通过 contextConfigLocation 来配置 SpringMVC 的配置文件, 而使用默认的.
            默认的配置文件为: /WEB-INF/<servlet-name>-servlet.xml
        -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

2) Join The Profile Of Spring MVC

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


    <!-- 配置自定扫描的包 -->
    <context:component-scan base-package="cbuc.life.springmvc"></context:component-scan>


    <!-- 配置视图解析器: 如何把 handler 方法返回值解析为实际的物理视图 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>


</beans>

3) Write the processor that processes the request and identify it as the processor using @Controller annotations

@Controller
public class HelloWorldController {
    /**
       1. 使用 @RequestMapping 注解来映射请求的 URL
       2. 返回值会通过视图解析器解析为实际的物理视图, 对于 InternalResourceViewResolver 视图解析器, 会做如下的解析:
          通过 prefix + returnVal + 后缀 这样的方式得到实际的物理视图, 然会做转发操作
          ==> /WEB-INF/views/success.jsp
     */
    @RequestMapping("/helloworld")
    public String hello(){
        System.out.println("hello world");
        return "success";
    }
}

4) Write a view JSP

Create a suces .jsp under/WEB-INF/views/directory

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>成功跳转页面</h1>
</body>
</html>

5) Run the project access: localhost:8080/helloworld

 hardcore! This article gives you an in-depth understanding of SpringMVC1

(Recommended course: Spring tutorial)

Third, use @RequestMapping map request

  • Spring MVC uses @RequestMapping annotations to specify to the controller which URL requests can be processed

  • Both the definition and the 方法 definition can be labeled

  • Class definition: Provides preliminary request mapping information. Relative to the root of the WEB app
  • Method: Provides further segmentation mapping information. T he URL relative to the definition of the class. If the class definition is not labeled @RequestMapping, the URL tagged at the method is relative to WEB 应用的根目录

  • After DispatcherServlet intercepts the request, the mapping information provided by @RequestMapping on the controller determines how the request is handled.

1) Standard request header

 hardcore! This article gives you an in-depth understanding of SpringMVC2

2)@RequestMapping

value, method, params, and heads of the @RequestMapping represent the mapping criteria for the request URL, the request method, the request parameters, and the request header, respectively, and they are the relationship with , using multiple conditions to make the request map more precise.

/**
     * 可以使用 params 和 headers 来更加精确的映射请求. params 和 headers 支持简单的表达式.
     * 
     * @return
     */
    @RequestMapping(value = "testParamsAndHeaders",
                    params = { "username","age!=10" },
                    headers = { "Accept-Language=en-US,zh;q=0.8" },
                    method = RequestMethod.POST)
    public String test() {
        System.out.println("test...");
        return "success";
    }

3) Support for Ant style

  • ? : Matches a character in the file name

/user/createUser?

Matches URLs such as /user/createUser a or user/createUser b

  • * : Matches any character in the file name

/user/*/createUser

Matches URLs such as /user/aaa/createUser or /user/bbb/createUser

  • ** : Matches multi-tier paths

/user/\ /createUser**

Matches URLs such as /user/createUser or /user/aaa/bbb/createUser

Four, @PathVariable

A placeholder that maps URL bindings

  • The URL with placeholder is a new feature of Spring3.0 that is a milestone in SpringMVC's progress toward rest goals
  • @PathVariable you can bind placeholder parameters in a URL to the parameters of the controller's processing method: {xxx} in the URL can be bound to the parameters of the action method by @PathVariable("xxx")

/**
 * @PathVariable 可以来映射 URL 中的占位符到目标方法的参数中.
 */
@RequestMapping("/testPathVariable/{id}")
public String test(@PathVariable("id") Integer id) {
    System.out.println("id: " + id);
    return "success";
}
复制代码

V. REST style

REST The Representation State Transfer. ( Resource) performance layer state transformation. I t is one of the most popular Internet software architectures. It is well structured, standard-compliant, easy to understand, easy to expand, so it is getting more and more website adoption

Example:

  • /order/1 HTTP GET Gets the order record for id s 1
  • /order/1 HTTP DELETE Delete the order record for id s 1
  • /order/1 HTTP PUT Update the order record for id s 1
  • /order HTTP POST A new order record has been added

Six, @RequestParam binding request parameter values

  • Use @RequestParam at the entry of the processing method to pass the request parameters to the request method
  • value The parameter name
  • required Whether it is necessary;

/**
 * @RequestParam 来映射请求参数. value 值即请求参数的参数名 required 该参数是否必须. 默认为 true
 *               defaultValue 请求参数的默认值
 */
@RequestMapping(value = "/testRequestParam")
public String testRequestParam(
        @RequestParam(value = "username") String username,
        @RequestParam(value = "age", required = false, defaultValue = "0") int age) {
    System.out.println("testRequestParam, username: " + username + ", age: " + age);
    return "success";
}

7. @RequestHeader the property value of the binding request header

/**
 *   映射请求头信息 用法同 @RequestParam
 */
@RequestMapping("/testRequestHeader")
public String testRequestHeader(
        @RequestHeader(value = "Accept-Language") String al) {
    System.out.println("testRequestHeader, Accept-Language: " + al);
    return "success";
}

Eight, @CookieValue the cookie value in the binding request

/**
 * @CookieValue: 映射一个 Cookie 值. 属性同 @RequestParam
 */
@RequestMapping("/testCookieValue")
public String testCookieValue(@CookieValue("JSESSIONID") String sessionId) {
    System.out.println("testCookieValue: sessionId: " + sessionId);
    return "success";
}

Nine, POJO object binding request parameter values

/**
 * Spring MVC 会按请求参数名和 POJO 属性名进行自动匹配, 自动为该对象填充属性值。支持级联属性。
 * 如:dept.deptId、dept.address.tel 等
 */
@RequestMapping("/testPojo")
public String testPojo(User user) {
    System.out.println("testPojo: " + user);
    return "success";
}

Ten, the parameters of the Servlet API type that theHandler method can receive in MVC

  • HttpServletRequest
  • HttpServletResponse
  • HttpSession
  • Writer
  • java.security.Principal
  • Locale
  • InputStream
  • OutputStream
  • Reader

(Recommended micro-class: Spring micro-class.) )

XI, processing model data

1) ModelAndView

When the processing method returns a value type of ModelAndView, the method body can add model data through the object, which contains both view information and model data information.

2) Map 及 Model

When you enter org.springframework.ui.Model, org.springframework.ui.ModelMap, or java.uti.Map, the data in the map is automatically added to the model when the processing method returns.

3) @SessionAttributes:

Staging a property in the model to HttpSession so that it can be shared between multiple requests (from the session domain)

  • If you want to share a model property data across multiple requests, you can label a @SessionAttributes on the Controller class, and Spring MVC staging the corresponding properties in the model to HttpSession

  • @SessionAttributes In addition to specifying the properties that need to be placed in a session through the property name, you can specify which model properties need to be placed in the session through the object type of the model property

1) @SessionAttributes (types-user.class): All properties in the implied model that are user-.class are added to the session

2) @SessionAttributes (value s"user1", "user2"): the property of the object in the implied model named user1, user2, is added to the session

3) @SessionAttributes (types," user.class, Dept.class): All properties in the implied model that are User .class, Dept .class, are added to the session

4) @SessionAttributes (value," "user1," "user2", types, "Dept.class"): the properties of the implied model named user1, user2, and all properties of type Dept .class are added to the session

4) @ModelAttribute

When the method is labeled with the annotation, the object in the parameter is placed in the data model

Twelve, @ModelAttribute

  • Use @ModelAttribute note on method definitions: Spring MVC calls methods labeled @ModelAttribute at the method level one by one before calling the target processing method.
  • Use @ModelAttribute annotations before entering the method:
  • You can get the implied model data from the implied object, bind the request parameters to the object, and pass in the parameters
  • Add method entry objects to the model

Example:

 hardcore! This article gives you an in-depth understanding of SpringMVC3

Thirteen, views and view parsers

  • When the request processing method is complete, a ModelAndView object is eventually returned. For processing methods that return types such as String, View, or ModeMap, Spring MVC also internally assembles them into a ModelAndView object that contains views of logical names and model objects.
  • Spring MVC gets the final view object with ViewResolver View can be a JSP or a view in various forms of expression, such as Excel JFreeChart and so on.
  • Processors don't care what view objects are ultimately used to render model data, and the processor focuses on the work of producing model data to fully decouple MVC.

1) View

We only need to implement the View interface to customize the view

Example:

@Component
public class HelloView implements View{
    @Override
    public String getContentType() {
        return "text/html";
    }
    @Override
    public void render(Map<String, ?> model, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        response.getWriter().print("hello view, time: " + new Date());
    }
}
@RequestMapping("/testView")
    public String testView(){
        System.out.println("testView");
        return "helloView"; //这里返回的就是我们自定义的视图
    }

 hardcore! This article gives you an in-depth understanding of SpringMVC4

2) View parser

  • SpringMVC provides different policies for parsing logical view names, and you can configure one or more resolution policies in the Spring WEB context and specify the order between them. Each mapping strategy corresponds to a specific view parser implementation class.
  • The view parser has a single effect, parsing the logical view into a specific view object.
  • All view parsers must implement the ViewResolver interface.
  • Programmers can choose one view parser or mix multiple view parsers.
  • Each view parser implements an Ordered interface and opens up an order property that specifies the order's priority through the order property, and the smaller the order, the higher the priority.
  • SpringMVC parses the logical view name in the order of view parser order until the resolution is successful and the view object is returned, otherwise ServletException exception is thrown

Configurations in the SpringMVC .xml:

<!-- 配置视图解析器: 如何把 handler 方法返回值解析为实际的物理视图 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"></property>
    <property name="suffix" value=".jsp"></property>
</bean>


<!-- 配置视图  BeanNameViewResolver 解析器: 使用视图的名字来解析视图 -->
<!-- 通过 order 属性来定义视图解析器的优先级, order 值越小优先级越高 -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
    <property name="order" value="100"></property>
</bean>

 hardcore! This article gives you an in-depth understanding of SpringMVC5

Source: Public No. -- A Good Book of Small Dishes Author: Cai Wei

Above is W3Cschool编程狮 about (hard core!) This article gives you an in-depth understanding of SpringMVC) related to the introduction, I hope to help you.