SpringMVC super detailed explanation

Article directory

1 Introduction to Spring MVC

1.1 MVC model

The full name of MVC is Model View Controller, and each part performs its own duties.

  • Model : Data model, JavaBean class, used for data encapsulation.
  • View : refers to JSP and HTML used to display data to users
  • Controller : used to receive user requests and the controller of the entire process . Used for data verification, etc.

1.2 Spring MVC

Spring Web MVC is a lightweight Web framework based on Java that implements the request-driven type of Web MVC design pattern. It uses the idea of ​​​​the MVC architectural pattern to decouple the responsibilities of the web layer. Request-driven refers to the use of The purpose of the request-response model and framework is to help us simplify development, and Spring Web MVC also aims to simplify our daily web development.

Spring MVC is mainly composed of front-end mapper DispatcherServlet, processor mapper HandlerMapping, processor adapter HandlAdapter, processor Handler, view resolver View Resolver, and view View.

Two cores:
Processor mapper : chooses which controller to use to handle the request
View resolver : chooses how the results should be rendered

2 Spring MVC request processing process

2.1 Process introduction


Step 1: The user sends a request to the front-end controller (DispatcherServlet).
Step 2: The front-end controller requests the processor mapper HandlerMapping to search for Handler, which can be searched based on xml configuration and annotations.
Step 3: The processor mapper HandlerMapping returns the Handler to the front-end controller.
Step 4: The front-end controller calls the processor adapter to execute the Handler.
Step 5: The processor adapter executes the Handler.
Step 6: After the Handler execution is completed, it returns ModelAndView to the adapter.
Step 7: The processor adapter returns ModelAndView to the front-end controller.
ModelAndView is an underlying object of the SpringMVC framework, including Model and View.
Step 8: The front-end controller requests the view parser to perform view parsing
to parse the real view according to the logical view name. .
Step 9: The view resolver returns the view to the front-end controller.
Step 10: The front-end controller performs view rendering
, which is to fill the model data (in the ModelAndView object) into the request field.
Step 11: The front-end controller responds to the user with the result.

2.2 Component introduction

1. Front-end controller DispatcherServlet (no programmer development required).
Function: Receive requests and respond to results, equivalent to a forwarder and central processing unit. With DispatcherServlet, the coupling between other components is reduced.
2. Processor mapper HandlerMapping (no programmer development required).
Function: HandlerMapping is responsible for finding the Handler or processor according to the URL requested by the user. SpringMVC provides different mappers to implement different mapping methods, such as configuration file method, interface implementation method, annotation method, etc.
3. Processor adapter HandlerAdapter (no need for programmer development).
Function: Execute Handler according to specific rules (rules required by HandlerAdapter).
4. Processor Handler (requires programmer development).
Note: When writing Handler, follow the requirements of HandlerAdapter, so that the adapter can correctly execute Handler
5. View resolver ViewResolver (no programmer development required).
Function: Perform view parsing, and parse it into a real view (view) based on the logical view name.
6. View View (programmers need to develop jsp).
Note: View is an interface, and the implementation class supports different View types (jsp, freemarker, pdf...)

Note: It does not require a programmer to develop, and the programmer needs to configure it himself.
It can be concluded that the only work that needs to be developed by us is the writing of Handler and the writing of views such as JSP pages.

3 Getting started with SpringMVC

1. SpringMVC introductory program

1.1 WEB engineering structure

image.png

1.2 Create a WEB project and introduce dependencies

<?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">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.pikaqiu</groupId>
  <artifactId>SpringMVC_InitalCase</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>SpringMVC_InitalCase Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <spring.version>5.0.2.RELEASE</spring.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>SpringMVC_InitalCase</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

1.3 Configure the core controller (configure DispatcherServlet)

In the web.xml configuration file the core controller DispatcherServlet

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!--配置核心控制器DispatcherServle-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <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>

</web-app>

1.4 Write the configuration file of springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--开启注解扫描-->
    <context:component-scan base-package="com.pikaqiu"></context:component-scan>

    <!--视图解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--开启SpringMVC框架注解的支持-->
    <!--会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个Bean-->
    <mvc:annotation-driven/>
</beans>

Note: The role of mvc:annotation-driven/

它就相当于在 xml 中配置了:
<!-- 上面的标签相当于 如下配置-->
<!-- Begin -->
<!-- HandlerMapping --> 
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerM
apping"></bean> 
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
<!-- HandlerAdapter --> 
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerA
dapter"></bean> 
<bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"></bean> <bean
class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
<!-- HadnlerExceptionResolvers --> 
<bean class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExcept
ionResolver"></bean> 
<bean class="org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolv
er"></bean> 
<bean class="org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver"
></bean>
<!-- End -->

1.5 Write index.jsp and Controller class

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>Title</title>
  </head>
  <body>
    <h3>入门程序</h3>
    <a href="hello">入门程序</a>
  </body>
</html>

package com.pikaqiu;

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

/**
 * @author pikaqiu
 * @description: TODO 类描述
 * @date: 2022/3/26 14:49
 **/
@Controller
public class HelloController {
    
    
	@RequestMapping(path = "/hello")
	public String sayHello(){
    
    
		System.out.println("hello SpringMVC");
		return "success";
	}
}

1.6 Create the pages folder in the WEB-INF directory and write the success page of success.jsp

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

1.7 Tomcat configuration

image.png
image.png

1.8 Start Tomcat

image.png

1.9 Analysis of the execution process of the entry-level case

  1. When starting the Tomcat server, because the load-on-startup tag is configured, the DispatcherServlet object will be created and the springmvc.xml configuration file will be loaded.
  2. When annotation scanning is enabled, the HelloController object will be created.
  3. When sending a request from index.jsp, the request will first reach the DispatcherServlet core controller and find the specific method of execution according to the @RequestMapping annotation configured.
  4. According to the return value of the execution method, and based on the configured view parser, search for the JSP file with the specified name in the specified directory.
  5. Tomcat server renders the page and responds

4 Binding of request parameters

4.1 Binding instructions for request parameters

4.1.1 Binding mechanism

1️⃣ 表单提交的数据都是k=v格式的 username=haha&password=123 
2️⃣ SpringMVC的参数绑定过程是把表单提交的请求参数,作为控制器中方法的参数进行绑定的 
3️⃣ 要求:提交表单的name和参数的名称是相同的 

4.1.2 Supported data types

1️⃣ 基本数据类型和String类型 
2️⃣ POJO类型(包括实体类,以及关联的实体类) 
3️⃣ 数组和集合数据类型(List、map集合等)

4.2 Basic data types and String type

1️⃣ 提交表单的name和参数的**名称是相同**的 
2️⃣ 严格区分大小写 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="param/testBasicParamAndString?userName=zhangsan&age=23">基本类型和String类型请求参数绑定</a>
</body>
</html>
package com.pikaqiu;

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

/**
 * @description: TODO 类描述
 * @date: 2022/3/26 16:06
 **/
@Controller
@RequestMapping("/param")
public class ParamController {
    
    
	@RequestMapping("/testBasicParamAndString")
	public String testBasicParamAndString(String userName, Integer age){
    
    
		System.out.println("正常运行");
		System.out.println("userName: " + userName + " age: " + age);
		return "success";
	}
}

4.3 POJO type (JavaBean)

1️⃣ 提交表单的name和JavaBean中的**属性名称需要一致** 
2️⃣ 如果一个JavaBean类中包含其他的引用类型,那么表单的name属性需要编写成:对象.属性 例	如: address.name 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="param/testPoJO" method="post">
        姓名:<input type="text" name="userName"><br/>
        密码:<input type="text" name="passWord"><br/>
        工资:<input type="text" name="money"><br/>
        uName:<input type="text" name="user.uName"><br/>
        uAge:<input type="text" name="user.uAge"><br/>

        <input type="submit" value="提交">
    </form>
</body>
</html>

package com.pikaqiu.controller;

import com.pikaqiu.domain.Account;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @description: TODO 类描述
 * @date: 2022/3/26 16:06
 **/
@Controller
@RequestMapping("/param")
public class ParamController {
    
    
	@RequestMapping("/testPoJO")
	public String testPOJOParam(Account account){
    
    
		System.out.println("正常运行");
		System.out.println(account);
		return "success";
	}
}

4.4 Collection types

The first one:
request parameters of collection type must be in POJO. The name of the request parameter in the form must be the same as the name of the collection property in the POJO.
To assign values ​​to elements in the List collection, use subscripts.
Assign values ​​to elements in the Map collection, using key-value pairs.

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

    <form action="param/testListAndMap" method="post">
        姓名:<input type="text" name="userName"><br/>
        密码:<input type="text" name="passWord"><br/>
        工资:<input type="text" name="money"><br/>
        用户姓名:<input type="text" name="uList[0].uName"><br/>
        用户年龄:<input type="text" name="uList[0].uAge"><br/>
        用户姓名:<input type="text" name="uList[1].uName"><br/>
        用户年龄:<input type="text" name="uList[1].uAge"><br/>
        用户姓名:<input type="text" name="uMap['one'].uName"><br/>
        用户年龄:<input type="text" name="uMap['one'].uAge"><br/>
        用户姓名:<input type="text" name="uMap['two'].uName"><br/>
        用户年龄:<input type="text" name="uMap['two'].uAge"><br/>

        <input type="submit" value="提交">
    </form>

</body>
</html>

package com.pikaqiu.controller;

import com.pikaqiu.domain.Account;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @description: TODO 类描述
 * @date: 2022/3/26 16:06
 **/
@Controller
@RequestMapping("/param")
public class ParamController {
    
    

	@RequestMapping("/testListAndMap")
	public String test(Account account)
	{
    
    
		System.out.println("正常运行");
		System.out.println(account);
		return "success";
	}
}

Second type:
The received request parameters are json format data. It needs to be implemented with the help of an annotation. ( @ResponseBody )

4.5 Solution to Chinese garbled request parameters

Post request: Configure the filter class provided by Spring in web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!--配置中文乱码过滤器-->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!--配置核心控制器DispatcherServle-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <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>

</web-app>

**get request: tomacat handles GET and POST requests differently. The encoding of the GET request must be changed to tomcat's server.xml **
Configuration file

changed to:

If the ajax request is still garbled, please change:
useBodyEncodingForURI="true "Change to URIEncoding ="UTF-8"
.

4.6 Custom type converter

1. Any data type submitted by the form is all string type, but the Integer type is defined in the background, and the data can also be encapsulated, which means that the Spring framework will perform data type conversion by default.
2. If you want to customize data type conversion, you can implement the Converter interface

4.6.1 Custom type converter

package com.pikaqiu.util;

import org.springframework.core.convert.converter.Converter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 把字符串转换为日期
 **/
public class StringToDateConverter implements Converter<String, Date> {
    
    
	@Override
	public Date convert(String source) {
    
    
		if(source == null){
    
    
			throw new RuntimeException("请您传入数据");
		}
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		// 把字符串转为日期
		try {
    
    
			return df.parse(source);
		} catch (ParseException e) {
    
    
			throw new RuntimeException("数据类型转换出现错误");
		}
	}
}

4.6.2 Register a custom type converter and write the configuration in the springmvc.xml configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--开启注解扫描-->
    <context:component-scan base-package="com.pikaqiu"></context:component-scan>

    <!--视图解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--配置自定义类型转换器-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.pikaqiu.util.StringToDateConverter"></bean>
            </set>
        </property>
    </bean>

    <!--开启SpringMVC框架注解的支持-->
    <!--会自动注册RequestMappingHandlerMappingRequestMappingHandlerAdapter两个Bean-->
    <mvc:annotation-driven conversion-service="conversionService"/>
</beans>

4.6.3 param.jsp

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

    <form action="param/testSelfConverter" method="post">
        姓名:<input type="text" name="uName"><br/>
        年龄:<input type="text" name="uAge"><br/>
        生日:<input type="text" name="birthDay"><br/>

        <input type="submit" value="提交">
    </form>

</body>
</html>

4.6.4 Controller class

package com.pikaqiu.controller;

import com.pikaqiu.domain.Account;
import com.pikaqiu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @description: TODO 类描述
 * @date: 2022/3/26 16:06
 **/
@Controller
@RequestMapping("/param")
public class ParamController {
    
    
	
	@RequestMapping("/testSelfConverter")
	public String testSelfConverter(User user)
	{
    
    
		System.out.println("正常运行");
		System.out.println(user);
		return "success";
	}
}

4.7 The controller uses native ServletAPI objects

You only need to define HttpServletRequest and HttpServletResponse objects in the method parameters of the controller

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  
    <a href="param/testServlet?username=haha&password=123">Servlet原生的API</a>

</body>
</html>
package com.pikaqiu.controller;

import com.pikaqiu.domain.Account;
import com.pikaqiu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @description: TODO 类描述
 * @date: 2022/3/26 16:06
 **/
@Controller
@RequestMapping("/param")
public class ParamController {
    
    
	/**
	 * 使用Servlet原生的API
	 * @param
	 * @return
	 */
	@RequestMapping("/testServlet")
	public String testServlet(HttpServletRequest request, HttpServletResponse response){
    
    
		System.out.println("正常运行");
		System.out.println(request);

		HttpSession session = request.getSession();
		System.out.println(session);

		ServletContext servletContext = session.getServletContext();
		System.out.println(servletContext);

		System.out.println(response);
		return "success";
	}
}

5 Commonly used annotations

5.1 RequestParam annotation

1️⃣ Function: Pass the parameter with the specified name in the request to the formal parameter assignment in the controller
2️⃣ Attribute
value: The name in the request parameter
required: Whether this parameter must be provided in the request parameter, the default value is true, it must be provided

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

    <a href="param/testRequestParam?username=haha&password=123">RequestParam注解</a>

</body>
</html>
package com.pikaqiu.controller;

import com.pikaqiu.domain.Account;
import com.pikaqiu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @description: TODO 类描述
 * @date: 2022/3/26 16:06
 **/
@Controller
@RequestMapping("/param")
public class ParamController {
    
    
	/**
	 * @RequestParam注解
     */
	@RequestMapping("/testRequestParam")
	public String testRequestParam(@RequestParam(name = "username") String username, @RequestParam(name = "password") String password){
    
    
		System.out.println("正常运行");
		System.out.println(username);
		System.out.println(password);
		return "success";
	}
}

Note : In @RequestParam(name = " name ") in the AnnoController class , the value of name is consistent with the name value in href="anno/testRequestParam? name = haha".

5.2 RequestBody annotation

1️⃣ Function: used to obtain the content of the request body (note: the get method cannot be used )
2️⃣ Attribute
required: whether there must be a request body, the default value is true

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <form action="param/testRequestBody" method="post">
        用户姓名:<input type="text" name="uname"><br/>
        用户年龄:<input type="text" name="uage"><br/>
        <input type="submit" value="提交">
  </form>
</body>
</html>

package com.pikaqiu.controller;

import com.pikaqiu.domain.Account;
import com.pikaqiu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @description: TODO 类描述
 * @date: 2022/3/26 16:06
 **/
@Controller
@RequestMapping("/param")
public class ParamController {
    
    
	/**
	 * @RequestBody注解
	 */
	@RequestMapping("/testRequestBody")
	public String testRequestBody(@RequestBody(required=false) String body){
    
    
		System.out.println("正常运行");
		System.out.println(body);
		return "success";
	}
}

5.3 PathVariable annotation

1️⃣ Function: It has the placeholder in the bound url. For example: there is /delete/{id} in the url, {id} is the placeholder
2️⃣ Attribute
value: Specify the placeholder name in the url
3️⃣ Restful style URL
① The request path is the same, and the background can be executed according to different request methods Different methods
② Restful style URL advantages:
clear structure
, compliant with standards,
easy to understand,
easy to expand

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="param/testPathVariable/33">testPathVariable</a>
</body>
</html>
package com.pikaqiu.controller;

import com.pikaqiu.domain.Account;
import com.pikaqiu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @description: TODO 类描述
 * @date: 2022/3/26 16:06
 **/
@Controller
@RequestMapping("/param")
public class ParamController {
    
    
	/**
	 * @PathVariable注解
	 */
	@RequestMapping("/testPathVariable/{id}")
	public String testPathVariable(@PathVariable(name = "id") String id){
    
    
		System.out.println("正常运行");
		System.out.println(id);
		return "success";
	}
}

Note : The id in path = "/testPathVariable/{ id }" is consistent with the id in @PathVariable(name=" id "), and href="anno/testPathVariable/ 10 ", the value is written directly without parameters.

5.4 RequestHeader annotation

1️⃣ Function: Get the value of the specified request header
2️⃣ Attribute
value: The name of the request header

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

</body>
</html>
package com.pikaqiu.controller;

import com.pikaqiu.domain.Account;
import com.pikaqiu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @description: TODO 类描述
 * @date: 2022/3/26 16:06
 **/
@Controller
@RequestMapping("/param")
public class ParamController {
    
    
	/**
	 * @RequestHeader注解
	 */
	@RequestMapping("/testRequestHeader")
	public String testRequestHeader(@RequestHeader(value = "Accept") String header) {
    
    
		System.out.println("正常运行");
		System.out.println(header);
		return "success";

	}
}

5.5 CookieValue annotation

1️⃣ Function: used to obtain the value of the specified cookie name
2️⃣ Attribute
value: cookie name

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

    <a href="param/testCookieValue">testCookieValue</a>

</body>
</html>
package com.pikaqiu.controller;

import com.pikaqiu.domain.Account;
import com.pikaqiu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @description: TODO 类描述
 * @date: 2022/3/26 16:06
 **/
@Controller
@RequestMapping("/param")
public class ParamController {
    
    
	/**
	 * @CookieValue注解
	 */
	@RequestMapping("/testCookieValue")
	public String testCookieValue(@CookieValue(value = "JSESSIONID") String header) {
    
    
		System.out.println("正常运行");
		System.out.println(header);
		return "success";
	}
}

5.6 ModelAttribute annotation

1️⃣ Function
① Appears on the method: Indicates that the current method will be executed before the controller method is executed.
② Appears on the parameter: Gets the specified data and assigns it to the parameter.
2️⃣ Application scenarios
① When the submitted form data is not complete entity data, ensure that the original data of the database is used for the fields that are not submitted.

5.6.1 Appearing on methods

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

    <form action="param/testModelAttribute" method="post">
        用户姓名:<input type="text" name="uName"><br/>
        用户年龄:<input type="text" name="uAge"><br/>

        <input type="submit" value="提交">
    </form>

</body>
</html>
	package com.pikaqiu.controller;

	import com.pikaqiu.domain.Account;
	import com.pikaqiu.domain.User;
	import org.springframework.stereotype.Controller;
	import org.springframework.web.bind.annotation.*;

	import javax.servlet.ServletContext;
	import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletResponse;
	import javax.servlet.http.HttpSession;

	/**
	 * @description: TODO 类描述
	 * @date: 2022/3/26 16:06
	 **/
	@Controller
	@RequestMapping("/param")
	public class ParamController {
    
    
		/**
		 * @ModelAttribute注解
		 */
		@RequestMapping("/testModelAttribute")
		public String testModelAttribute() {
    
    
			System.out.println("testModelAttribute运行");
			return "success";

		}

		@ModelAttribute
		public void showUser(){
    
    
			System.out.println("showUser方法执行了");
		}
	}

operation result:
image.png

5.6.2 Map-based application scenario example: ModelAttribute modified method with return value

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

    <form action="param/testModelAttribute" method="post">
        用户姓名:<input type="text" name="uName"><br/>
        用户年龄:<input type="text" name="uAge"><br/>

        <input type="submit" value="提交">
    </form>

</body>
</html>
	package com.pikaqiu.controller;

	import com.pikaqiu.domain.Account;
	import com.pikaqiu.domain.User;
	import org.springframework.stereotype.Controller;
	import org.springframework.web.bind.annotation.*;

	import javax.servlet.ServletContext;
	import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletResponse;
	import javax.servlet.http.HttpSession;
	import java.util.Date;

	/**
	 * @description: TODO 类描述
	 * @date: 2022/3/26 16:06
	 **/
	@Controller
	@RequestMapping("/param")
	public class ParamController {
    
    
		/**
		 * @ModelAttribute注解
		 */
		@RequestMapping("/testModelAttribute")
		public String testModelAttribute(User user) {
    
    
			System.out.println("testModelAttribute运行");
			System.out.println(user);
			return "success";

		}


		/**
		 * 该方法会先执行
		 */
		@ModelAttribute
		public User showUser(String uName){
    
    
			System.out.println("showUser方法执行了");
			// 通过用户查询数据库(模拟)
			User user = new User();
			user.setuName(uName);
			user.setuAge(23);
			user.setBirthDay(new Date());
			return user;
		}

	}

result:
image.png

5.6.3 Map-based application scenario example: ModelAttribute modification method without return value

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

    <form action="param/testModelAttribute" method="post">
        用户姓名:<input type="text" name="uName"><br/>
        用户年龄:<input type="text" name="uAge"><br/>

        <input type="submit" value="提交">
    </form>

</body>
</html>
	package com.pikaqiu.controller;

	import com.pikaqiu.domain.Account;
	import com.pikaqiu.domain.User;
	import org.springframework.stereotype.Controller;
	import org.springframework.web.bind.annotation.*;

	import javax.servlet.ServletContext;
	import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletResponse;
	import javax.servlet.http.HttpSession;
	import java.util.Date;
	import java.util.Map;

	/**
	 * @description: TODO 类描述
	 * @date: 2022/3/26 16:06
	 **/
	@Controller
	@RequestMapping("/param")
	@SessionAttributes()
	public class ParamController {
    
    
		/**
		 * @ModelAttribute注解
		 */
		@RequestMapping("/testModelAttribute")
		public String testModelAttribute(@ModelAttribute("user") User user) {
    
    
			System.out.println("testModelAttribute运行");
			System.out.println(user);
			return "success";

		}

		/**
		 * 该方法会先执行
		 */
		@ModelAttribute
		public void showUser(String uName, Map<String, User> map){
    
    
			System.out.println("showUser方法执行了");
			// 通过用户查询数据库(模拟)
			User user = new User();
			user.setuName(uName);
			user.setuAge(23);
			user.setBirthDay(new Date());
			map.put("user", user);
		}
	}

image.png

5.7 SessionAttributes annotation

1️⃣ Function:
Used for parameter sharing between multiple executions of controller methods.
2️⃣ Attributes:
value: used to specify the attribute name to be stored
type: used to specify the data type to be stored.
No @SessionAttributes annotation

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>入门成功</h3>

    ${requestScope.name}
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    <a href="param/testSessionAttributes">testSessionAttributes</a>
    <br>

</body>
</html>
	package com.pikaqiu.controller;

	import com.pikaqiu.domain.Account;
	import com.pikaqiu.domain.User;
	import org.springframework.stereotype.Controller;
	import org.springframework.ui.Model;
	import org.springframework.web.bind.annotation.*;

	import javax.servlet.ServletContext;
	import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletResponse;
	import javax.servlet.http.HttpSession;
	import java.util.Date;
	import java.util.Map;

	/**
	 * @description: TODO 类描述
	 * @date: 2022/3/26 16:06
	 **/
	@Controller
	@RequestMapping("/param")
	public class ParamController {
    
    
		/**
		 * @SessionAttributes注解
		 */
		@RequestMapping("/testSessionAttributes")
		public String testSessionAttributes(Model model) {
    
    
			System.out.println("正常运行");
			//  底层会存储到request域对象中
			model.addAttribute("name", "zhangsan");
			return "success";
		}
	}

@SessionAttributes annotation

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>入门成功</h3>

    ${requestScope.name}
    ${sessionScope}
</body>
</html>
	package com.pikaqiu.controller;

	import com.pikaqiu.domain.Account;
	import com.pikaqiu.domain.User;
	import org.springframework.stereotype.Controller;
	import org.springframework.ui.Model;
	import org.springframework.web.bind.annotation.*;

	import javax.servlet.ServletContext;
	import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletResponse;
	import javax.servlet.http.HttpSession;
	import java.util.Date;
	import java.util.Map;

	/**
	 * @description: TODO 类描述
	 * @date: 2022/3/26 16:06
	 **/
	@Controller
	@RequestMapping("/param")
	@SessionAttributes(value = {
    
    "name"}) // 把name=zhangsan存入到session域中
	public class ParamController {
    
    
		/**
		 * @SessionAttributes注解
		 */
		@RequestMapping("/testSessionAttributes")
		public String testSessionAttributes(Model model) {
    
    
			System.out.println("正常运行");
			//  底层会存储到request域对象中
			model.addAttribute("name", "zhangsan");
			return "success";
		}
	}

@SessionAttributes annotation implements obtaining and deleting objects in the session domain

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>入门成功</h3>

    ${requestScope.name}
    ${sessionScope}
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    <a href="param/testSessionAttributes">testSessionAttributes</a>
    <br>
    <a href="param/getSessionAttributes">getSessionAttributes</a>
    <br>
    <a href="param/delSessionAttributes">delSessionAttributes</a>

</body>
</html>
	package com.pikaqiu.controller;

	import com.pikaqiu.domain.Account;
	import com.pikaqiu.domain.User;
	import org.springframework.stereotype.Controller;
	import org.springframework.ui.Model;
	import org.springframework.web.bind.annotation.*;

	import javax.servlet.ServletContext;
	import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletResponse;
	import javax.servlet.http.HttpSession;
	import java.util.Date;
	import java.util.Map;

	/**
	 * @description: TODO 类描述
	 * @date: 2022/3/26 16:06
	 **/
	@Controller
	@RequestMapping("/param")
	@SessionAttributes(value = {
    
    "name"}) // 把name=zhangsan存入到session域中
	public class ParamController {
    
    
		/**
		 * @SessionAttributes注解
		 */
		@RequestMapping("/testSessionAttributes")
		public String testSessionAttributes(Model model) {
    
    
			System.out.println("正常运行");
			//  底层会存储到request域对象中
			model.addAttribute("name", "zhangsan");
			return "success";
		}
         /**
		 * Session域获取值
		 * @param modelMap
		 * @return
		 */
		@RequestMapping(path = "/getSessionAttributes")
		public String getSessionAttributes(ModelMap modelMap){
    
    
			System.out.println("getSessionAttributes....");
			String msg = (String)modelMap.get("name");
			System.out.println(msg);
			return "success";
		}

		/**
		 * Session域清除
		 * @param status
		 * @return
		 */
		@RequestMapping(path = "/delSessionAttributes")
		public String delSessionAttributes(SessionStatus status){
    
    
			System.out.println("delSessionAttributes....");
			status.setComplete();
			return "success";
		}
	}

6 Response data and results views

6.1 Return value classification

6.1.1 Return string

The Controller method returns a string that specifies the name of the logical view, which is resolved to the address of the physical view according to the view resolver.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="returnValue/testString">testString</a>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>入门成功</h3>

    ${user.uName}
    ${user.birthDay}
</body>
</html>
package com.pikaqiu.controller;

import com.pikaqiu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;

/**
 * @description: TODO 类描述
 * @date: 2022/3/26 21:00
 **/
@Controller
@RequestMapping("/returnValue")
public class ReturnValueController {
    
    
	@RequestMapping("/testString")
	public String testString(Model model){
    
    
		System.out.println("testString方法执行了");
		// 模拟从数据库中查询user对象
		User user = new User();
		user.setuName("haha");
		user.setuAge(23);
		user.setBirthDay(new Date());
        //  底层会存储到request域对象中
		model.addAttribute("user", user);
		return "success";
	}
}

6.1.2 The return value is void

① 如果控制器的方法返回值编写成void,执行程序报404的异常,默认查找JSP页面没有找到。 
		默认会跳转到@RequestMapping(value="/initUpdate") initUpdate的页面。 
② 可以使用请求转发或者重定向跳转到指定的页面

Request forwarding, redirection, and direct responses

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="returnValue/testVoid">testVoid</a>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>请求转发</h3>
</body>
</html>
package com.pikaqiu.controller;

import com.pikaqiu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;

/**
 * @description: TODO 类描述
 * @date: 2022/3/26 21:00
 **/
@Controller
@RequestMapping("/returnValue")
public class ReturnValueController {
    
    
	/**
	 * 请求转发
	 */
	@RequestMapping("/testVoid")
	public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
		System.out.println("testVoid方法执行了");
		// 1. 请求转发
		//request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request, response);
		// 2. 重定向
		//response.sendRedirect(request.getContextPath() + "/response.jsp");

		// 设置中文乱码
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		// 3. 直接会进行响应
		response.getWriter().print("你好");
		return;
	}
}

6.1.3 The return value is a ModelAndView object

The ModelAndView object is an object provided by Spring and can be used to adjust specific JSP views.

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

package com.pikaqiu.controller;

import com.pikaqiu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * @description: TODO 类描述
 * @date: 2022/3/26 21:00
 **/
@Controller
@RequestMapping("/returnValue")
public class ReturnValueController {
    
    
	/**
	 * 返回值是 ModelAndView
	 */
	@RequestMapping("/testModelAndView")
	public ModelAndView testModelAndView(){
    
    
		System.out.println("testModelAndView方法执行了");
		// 创建ModelAndView对象
		ModelAndView modelAndView = new ModelAndView();
		// 模拟从数据库中查询User对象
		User user = new User();
		user.setuName("haha");
		user.setuAge(23);
		user.setBirthDay(new Date());
		// 把user对象存储到mv对象中,也会把user对象存入到request对象
		modelAndView.addObject("user", user);
		// 跳转到哪个页面
		modelAndView.setViewName("success");
		return modelAndView;
	}
}

6.2 Forwarding and redirection provided by the SpringMVC framework

6.2.1 forward request forwarding

After the controller method provides a return value of String type, the default is to forward the request . It can also be written as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="returnValue/testForward">testForward</a>
</body>
</html>
package com.pikaqiu.controller;

import com.pikaqiu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * @description: TODO 类描述
 * @date: 2022/3/26 21:00
 **/
@Controller
@RequestMapping("/returnValue")
public class ReturnValueController {
    
    
	@RequestMapping("/testForward")
	public String testForward(){
    
    
		System.out.println("testForward方法执行了");
		// 请求转发
		return "forward:/WEB-INF/pages/success.jsp";
	}
}

6.2.2 redirect redirect

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="returnValue/testRedirect">testRedirect</a>
</body>
</html>
package com.pikaqiu.controller;

import com.pikaqiu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * @description: TODO 类描述
 * @date: 2022/3/26 21:00
 **/
@Controller
@RequestMapping("/returnValue")
public class ReturnValueController {
    
    
	@RequestMapping("/testRedirect")
	public String testRedirect(){
    
    
		System.out.println("testRedirect方法执行了");
		// 重定向
		return "redirect:/response.jsp";
	}
}

6.3 ResponseBody responds to json data

DispatcherServlet will intercept all resources, which leads to a problem that static resources (img, css, js) will also be intercepted and cannot be used. To solve the problem, you need to configure static resources not to intercept. Add the following configuration to the springmvc.xml configuration file.

  • mvc:resources tag configuration does not filter
  • The location element represents all files under the package in the webapp directory
  • The mapping element represents all request paths starting with /static, such as /static/a or /static/a/b
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--开启注解扫描-->
    <context:component-scan base-package="com.pikaqiu"></context:component-scan>

    <!--视图解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--配置自定义类型转换器-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.pikaqiu.util.StringToDateConverter"></bean>
            </set>
        </property>
    </bean>

    <!--前端控制器,哪些静态资源不拦截-->
    <mvc:resources mapping="/css/**" location="/css/"/>
    <mvc:resources mapping="/images/**" location="/images/"/>
    <mvc:resources mapping="/js/**" location="/js/" />

    <!--开启SpringMVC框架注解的支持-->
    <!--会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个Bean-->
    <mvc:annotation-driven conversion-service="conversionService"/>
</beans>

The @RequestBody annotation is used to convert the object returned by the Controller method into data in a specified format through the HttpMessageConverter interface, such as json, xml, etc., and respond to the client through Response.

  • Use @RequestBody to get request body data
  • Use @RequestBody annotation to convert json string into JavaBean object
  • Use @ResponseBody annotation to convert JavaBean object into json string and respond directly
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery.min.js"></script>
    <script>
        //页面加载,绑定单击事件
        $(function () {
      
      
            $("#btn").click(function(){
      
      
                // alert("hello btn");
                // 发送ajax请求
                $.ajax({
      
      
                    // 编写json格式,设置属性和值
                    url:"user/testAjax",
                    contentType:"application/json;charset=UTF-8",
                    data:'{"username":"hehe", "password":"123", "age":"30"}',
                    dataType:"json",
                    type:"post",
                    success:function (data) {
      
      
                        // data服务器端响应的json的数据,进行解析
                        alert(data);
                        alert(data.username);
                        alert(data.password);
                    }
                })
            });
        });
     </script>
</head>
<body>
        <button id="btn">发送ajax的请求</button>
</body>
</html>

In the process of converting json strings and JavaBean objects, you need to use the jackson jar package.

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.0</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.9.0</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>2.9.0</version>
</dependency>
package com.pikaqiu.controller;

import com.pikaqiu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * @description: TODO 类描述
 * @date: 2022/3/26 21:00
 **/
@Controller
@RequestMapping("/returnValue")
public class ReturnValueController {
    
    
	/**
	 * 模拟异步请求响应
	 */
	public @ResponseBody User testAjax(@RequestBody User user){
    
    
		System.out.println("testAjax方法执行了");
		// 客户端发送ajax请求,传的是json字符串,后端把json字符串封装到user对象中
		System.out.println(user);
		// 做响应后,模拟查询数据库
		user.setuName("lisi");
		user.setuAge(66);
		// 作响应,@ResponseBody会将user对象转成json格式
		return user;
	}
}

7 SpringMVC implements file upload

7.1 Necessary prerequisites for file upload

  • The enctype value of the form form must be: multipart/form-data

    (Default value is: application/x-www-form-urlencoded) enctype: is the type of form request body

  • The value of the method attribute must be Post

  • Provide a file selection field

7.2 Traditional file upload method

Import the jar package of the file

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.1</version>
</dependency>
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.4</version>
</dependency>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
        <h3>文件上传</h3>

        <form action="user/testFileUpload" method="post" enctype="multipart/form-data">
            选择文件:<input type="file" name="upload" /><br/>
            <input type="submit" value="上传"/>
        </form>
</body>
</html>
package com.pikaqiu.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.UUID;

/**
 * @description: TODO 类描述
 * @date: 2022/3/27 16:21
 **/
@Controller
@RequestMapping("/file")
public class FileUploadController {
    
    
	@RequestMapping("/testFileUpload")
	public String testFileUpload(HttpServletRequest request) throws Exception {
    
    
		System.out.println("文件上传");
		// 使用功能fileupload组件完成文件上传
		// 上传的位置
		String path = request.getSession().getServletContext().getRealPath("/uploads/");
		File file = new File(path);
		if(!file.exists()){
    
    
			// 创建该文件夹
			file.mkdirs();
		}
		// 实现步骤
		// 1、创建DiskFileItemFactory对象,设置缓冲区大小和临时文件目录
		// 2、使用DiskFileItemFactory 对象创建ServletFileUpload对象,并设置上传文件的大小限制。
		// 3、调用ServletFileUpload.parseRequest方法解析request对象,得到一个保存了所有上传内容的List对象。
		// 4、对list进行迭代,每迭代一个FileItem对象,调用其isFormField方法判断是否是上传文件
		//    True 为普通表单字段,则调用getFieldName、getString方法得到字段名和字段值
		//    False 为上传文件

		// 解析request对象,获取上传文件项
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 创建一个上传工具,指定使用缓存区与临时文件存储位置
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 解析request
		// 它是用于解析request对象,得到所有上传项.每一个FileItem就相当于一个上传项
		List<FileItem> fileItems = upload.parseRequest(request);
		// 遍历
		for(FileItem item:fileItems){
    
    
			// 进行判断,当前item是否是上传文件对象
			if(item.isFormField()){
    
    
				// true,说明是普通表单相
			}else{
    
    
				// 说明是上传文件项
				// 获取上传文件的名称
				String filename = item.getName();
				// 把文件的名称设置为唯一值,uuid
				String uuid = UUID.randomUUID().toString().replace("-", "");
				filename = uuid + "_" + filename;
				// 完成文件上传
				item.write(new File(path, filename));
				item.delete();
			}
		}
		return "success";
	}
}

7.3 SpringMVC traditional method file upload

The SpringMVC framework provides the MultipartFile object, which represents the uploaded file. The variable name must be the same as the name attribute of the form file tag.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>文件上传</h3>
    <form action="file/testFileUploadBySpringMVC" method="post" enctype="multipart/form-data">
        选择文件:<input type="file" name="upload"><br/>
        <input type="submit" value="上传">
    </form>
</body>
</html>

Configuration file parser object in springmvc.xml

<!-- 配置文件解析器对象,要求id名称必须是multipartResolver -->
<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10485760"/>
</bean>

Note: the id name must be multipartResolver , select file: consistent with upload in MultipartFile upload

package com.pikaqiu.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @description: TODO 类描述
 * @date: 2022/3/27 16:21
 **/
@Controller
@RequestMapping("/file")
public class FileUploadController {
    
    
	/**
	 * SpringMVC文件上传
	 */
	@RequestMapping("/testFileUploadBySpringMVC")
	public String testFileUploadBySpringMVC(HttpServletRequest request, MultipartFile upload) throws Exception {
    
    
		System.out.println("springMVC文件上传");
		// 使用功能fileupload组件完成文件上传
		// 上传的位置
		String path = request.getSession().getServletContext().getRealPath("/uploads/");
		// System.out.println(path);
		// 判断,该路径是否存在
		File file = new File(path);
		if(!file.exists()){
    
    
			// 创建该文件夹
			file.mkdirs();
		}
		// 获取到上传文件的名称
		String fileName = upload.getOriginalFilename();
		String uuid = UUID.randomUUID().toString().replace("-", "");
		// 把文件的名称唯一化
		fileName = uuid + "-" + fileName;
		// 完成文件上传
		upload.transferTo(new File(path, fileName));
		return "success";
	}
}

7.4 SpringMVC cross-server file upload

Import the jar packages needed for development

<dependency>
  <groupId>com.sun.jersey</groupId>
  <artifactId>jersey-core</artifactId>
  <version>1.18.1</version>
</dependency>
<dependency>
  <groupId>com.sun.jersey</groupId>
  <artifactId>jersey-client</artifactId>
  <version>1.18.1</version>
</dependency>

reference:

  1. https://www.cnblogs.com/ysocean/p/7375405.html
  2. https://tyshawnlee.blog.csdn.net/article/details/79169148

Guess you like

Origin blog.csdn.net/hansome_hong/article/details/131322184