Spring MVC operation introduction

Posted by jiayanhuang on Mon, 07 Mar 2022 15:37:33 +0100

Chapter 1 Introduction to spring MVC

Spring Framework version 4.3.29 RELEASE

  • What is spring MVC
1. Spring Part of the family
2. yes JavaWeb Solution of controller layer in three-tier architecture
3. Is based on MVC Ideological framework
    -- Model
    -- View
    -- Controller
  • Spring MVC knowledge point outline
  • Spring MVC function overview
1. As spring Part of the framework is born with spring Framework integration
2. support restful style
3. Flexible requests URL/controller/Mapping of pages
4. Data binding is in the model and easy to transfer,The front end can well support other views
5. Simple data binding,Data validation can bind multiple data structures
6. Powerful exception handling function
7. Support of static resources
8. File upload/download
9. internationalization
...
  • Spring MVC common components
-- Front end controller: DispatcherServlet
-- view resolver : ViewResolver
-- controller/Action processor: controller
-- internationalization: LocalResolver
-- File upload: MultipartResolver
-- Exception handler: HandlerExceptionResolver

Chapter 2 spring MVC quick start

Preparation steps section 1

  • Create index jsp/result. JSP page
index.jsp

<a href="${pageContext.request.contextPath }/hello">Hello SpringMVC</a>

result.jsp

result.jsp Page to be placed springmvc Under the resolution directory specified by the configuration file
  • Create the spring MVC configuration file spring MVC xml
<!-- Configure packages to scan -->
<context:component-scan base-package="cn.ukoko"/>

<!-- Configuring a common view parser -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<!-- Configure prefix -->
	<property name="prefix" value="/WEB-INF/views/"></property>
	<!-- Configuration suffix -->
	<property name="suffix" value=".jsp"></property>
</bean>
  • On the web Configure the spring MVC core servlet [DispatcherServlet] in the XML configuration file
<servlet>
	<servlet-name>springDispatcherServlet</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-mvc.xml</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
	<servlet-name>springDispatcherServlet</servlet-name>
	<!--SpringMVC The official website emphasizes the use of request address interception/,Intercept JSP All requests except-->
	<url-pattern>/</url-pattern>
</servlet-mapping>
  • Write a controller to handle the core business logic code [controller]
/*Add to IOC container*/
@Controller
public class HelloController {
	/*Mapping request address*/
	@RequestMapping("/hello")
	public String helloWorld() {
		System.out.println("HelloWorld");
		//Return to the specified result page result jsp
		return "result";
	}
}

Section 2 operation process

Briefly describe the operation process
1.Client initiated request to DispatcherServlet
2.from DispatcherServlet Find one or more HandlerMapping The requested was found handler(controller)
3.DispatcherServlet Submit request to handler(controller)
4.Controller Return after calling the business logic layer for processing ModelAndView Specified view
5.The view returns the results to the client

Section 3 another configuration file method of spring MVC framework

Put the configuration file in WEB-INF The directory is named springDispatcherServlet-servlet.xml No need to web.xml Separate configuration in

Section 4 cross controller page Jump

<!--
    Skip controller,Jump directly to view
    path: Set request address
    view-name: Jump view name
-->
<mvc:view-controller path="/hello1" view-name="hello1"></mvc:view-controller>

<!--be careful: When used view-controller Will invalidate all annotations,Report 404,So you need to add annotation driven tags-->
<mvc:annotation-driven></mvc:annotation-driven>

Chapter 3 spring MVC data binding

Section 1 Introduction to common notes

@Controller     : Add the identified class to IOC Manage in container
@RequestMapping : Configure the mapping address of the front-end request and the settings of the request parameters
 - method=RequestMethod.GET
 - method=RequestMethod.POST
 - params:Qualified request parameters
    - params Is an array
    - params={"name","no!=100","age=10"}  :  Indicates that the request parameter contains name and no attribute,also no Cannot be equal to 100,age It must be equal to 10
    - params={"!name"} :  Indicates that the request parameter cannot have name parameter
@PathVariable   : Data binding
@RequestParam   : be similar to servlet of request.getParameter("key");
 - value        : To get parameters from the request field key value
 - required     : Is the parameter required
 - defaultValue : If there are no parameters,Then go to the default value

Section 2 Introduction to GET request data binding style

2.1 style I

use?Splicing method  hello?name=lilei&age=18

/**
 * Match by name
 */
@GetMapping(value = "/hello")
public String hello02(String name,int age){
    System.out.println(name);
    System.out.println(age);
    return "result";
}

2.2 style II

hello/lilei/18

/**
 * Using placeholders with PathVariable annotation
 */
@GetMapping(value = "/hello/{name}/{age}")
public String hello03(@PathVariable("name") String name,@PathVariable("age") int age){
    System.out.println(name);
    System.out.println(age);
    return "result";
}

Section 3 other data type object binding

3.1 data binding of native Java Web

  • Front page
<a href="testJavaWeb">Native JavaWeb Data binding test</a>
  • Background controller
@RequestMapping(value = "/testJavaWeb",method = RequestMethod.GET)
public String testJavaWeb(HttpServletRequest request){
    String name = request.getParameter("name");
    System.out.println(name);
    return "result";
}

3.2 basic data type / character type

  • Front page
<a href="testBase?name=Tom&age=18">Basic data type/Character type data binding test</a>
  • Background controller
@RequestMapping(value = "/testBase",method = RequestMethod.GET)
public String testBase(String name,int age){
    System.out.println(name);
    System.out.println(age);
    return "result";
}

3.3 array

  • Front page
<a href="testArray?roleId=1001&roleId=1002">Array type data binding test</a>
  • Background controller
@RequestMapping(value = "/testArray",method = RequestMethod.GET)
public String testArray(int[] roleId){
    System.out.println(roleId);
    return "result";
}

3.4 custom type / nested type

  • Front page
<form action="testPOJO" method="post">
    <input type="text" name="bookName"/>
    <%--Nested submission--%>
    <input type="text" name="author.authorName"/>
    <input type="submit" value="Submit"/>
</form>
  • Model object
public class Book {
    private String bookName;
    /*nested object */
    private Author author;
}

public class Author {
    private String authorName;
}
  • @Datetimeformat (request time format processing)
If the front end input Spatial type Type is date type,The type of parameters received by the controller is Date Annotation is required for type
@DateTimeFormat(pattern = "yyyy-MM-dd")Convert
  • Background controller
@RequestMapping(value = "/testPOJO",method = RequestMethod.POST)
public String testPOJO(Book book){
    System.out.println(book);
    return "result";
}

3.5 spring MVC Chinese garbled code solution (web.xml)

<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>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Section 4 data type converter for spring MVC

Through traditional JavaWeb The request data types obtained by the data acquisition method are String type,In other words, the data transmitted from the front end will become String Type then our SpringMVC How will String What about automatic conversion from type to other data types?

4.1 common type converters provided inside spring MVC

nameeffect
StringToBooleanConverterString to boolean type conversion
StringToCharacterConverterString to Character type conversion
StringToEnumConverterFactoryString to Enum type conversion
StringToNumberConverterFactoryString to Number type conversion
StringToNumberConverterFactoryLocale to String type conversion
......

For details, see Spring's official website address:

https://docs.spring.io/spring-framework/docs/4.3.29.RELEASE/spring-framework-reference/htmlsingle/#core-convert

ninth.5 section Spring Type Conversion(Spring Type conversion for)

Introduction to Spring type converter

1,Type conversion is Spring3 Version introduction,The default is one SPI(Service Provider Interface[Service discovery mechanism])Mechanism help Spring Type conversion.
2,Provides common API Perform type conversion at run time(For example, the built-in type conversion and user-defined type conversion in the above table).
3,stay Spring The system in the container(Type conversion)Can be used as PropertyEditor Replacement of
4,take String Convert type to another type

4.2 custom type converter

Introduction to common custom type converter API s

  • Converter
package org.springframework.core.convert.converter;

public interface Converter<S, T> {
    T convert(S source);
}

Short answer type converter,take S Type conversion to T type,Convert simple types, such as String Turn into Integer
  • ConverterFactory
package org.springframework.core.convert.converter;

public interface ConverterFactory<S, R> {

    <T extends R> Converter<S, T> getConverter(Class<T> targetType);
}

Level type adapter, S Type is the parameter type to be converted,R Type is the base type of the target conversion type,T Type is R Subclass of type,such as String To enum type.
  • GenericConverter
Complex type converter,When conversion of complex types occurs,GenericConverter More flexible interface,Support conversion from multiple source types to target types,It also provides drivers that can annotate and generics in the conversion process,Like arrays Array To set Collection Conversion of.

Official tip: because GenericConverter is a complex SPI, it is used when it must be used. Otherwise, it is best to use Converter or ConverterFactory for conversion

  • ConversionService
ConversionService Is a unity that performs transformation logic at run time API Interface

Use the Converter interface to implement custom type Converter (time type conversion)

/**
 * @Author Fengqiao night park 1990
 * @BLOG https://hd1611756908.github.io/
 * @BSITE https://space.bilibili.com/514155929/
 * @DATE 2020/10/17
 */
public class StringToDateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        Date date =null;
        try {
            date = sdf.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}

Add a custom Converter to the IOC container

<!--Set the service of type converter-->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<!--Set type converter-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="cn.ukoko.controller.StringToDateConverter"></bean>
        </set>
    </property>
</bean>

Test type converter

  • Front page
<form action="testConverter" method="post">
    <label for="createTime">time:</label>
    <input id="createTime" type="text" name="createTime"/>
    <input type="submit" value="land">
</form>
  • controller
@RequestMapping(value = "/testConverter",method = RequestMethod.POST)
public String testConverter(Date createTime){
    System.out.println("createTime="+createTime);
    return "result";
}

Chapter 4 RESTFUL style of spring MVC

Section 1 restful style concept

Representational State Transfer :(Resource) presentation layer state transition
 It is the most popular idea of Internet software design architecture

resources(Resources): An entity on the network, or a specific information on the network. It can be a text, a picture, a song, a service, in short, it is a concrete existence. You can use one URI(Uniform resource locator) points to it, and each resource corresponds to a specific resource URI. To get this resource, access its URI You can, so URI It is the unique identifier of each resource.

Presentation layer(Representation) The concrete form of resources is called its presentation layer(Representation). For example, text can be txt Format representation can also be used HTML Format XML Format JSON Format representation, or even binary format.

State transformation(State Transfer): Each request represents an interactive process between the client and the server. HTTP Protocol is a stateless protocol, that is, all States are saved on the server side. Therefore, if the client wants to operate the server, it must use some means to make the server "state transition"(State Transfer). This transformation is based on the presentation layer, so it is "presentation layer state transformation". Specifically, it is HTTP In the agreement, there are four verbs indicating the mode of operation: GET,POST,PUT,DELETE. They correspond to four basic operations: GET To get resources, POST Used to create new resources, PUT To update resources, DELETE Used to delete resources

Section 2 restful style format

/book/1  HTTP  GET   : obtain id = 1 of book 
/book/1  HTTP DELETE: delete id = 1 of book 
/book/1  HTTP PUT   : to update id = 1 of book 
/book    HTTP POST  : newly added book

Section 3 restful configuration mode

HiddenHttpMethodFilter: browser form Form only supports GET And POST Request, and DELETE,PUT etc. method Not supported, Spring3.0 A filter has been added to convert these requests to standard http Method to enable support GET,POST,PUT And DELETE request.
web.xml Medium configuration

<filter>
	<filter-name>HiddenHttpMethodFilter</filter-name>
	<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
	<filter-name>HiddenHttpMethodFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

Section 4 use of result style

<form action="delete" method="post">
    <!-- For state transition -->
    <input type="hidden" name="_method" value="DELETE"/>
    <input type="submit" value="delete"/>
</form>

<form action="update" method="post">
    <!-- For state transition -->
    <input type="hidden" name="_method" value="PUT"/>
    <input type="submit" value="to update"/>
</form>
  • bug handling 405 error JSPS only allow get post or head
During resource state transition
POST --> DELETE
POST --> PUT 

because tomcat8 405 error caused by problem

Repair method: 
Mode 1: change tomcat 7 or 9
 Mode 2: stay jsp Settings in the page <% isErrorPage="true"%>

Chapter V model data of spring MVC

Section 1 Java Web native mode model data transfer

RequestMapping(value = "/testJavaWebModel")
public String testJavaWebModel(HttpServletRequest request){
    //Put the data in the request field in a native way
    request.setAttribute("userName","Li Lei");
    return "result";
}

Section 2 model data transfer of spring MVC

  • Using ModelAndView objects
@RequestMapping(value = "/testModelAndView")
public ModelAndView testModelAndView(){
    ModelAndView mv = new ModelAndView();
    //Specify the view name
    mv.setViewName("result");
    /*Save data to domain object*/
    mv.addObject("userName","Li Lei");
    return mv;
}
  • Transfer using Model objects
@RequestMapping(value = "/testModel")
public String testModel(Model model){
    /*Save data to domain object*/
    model.addAttribute("userName","Li Lei");
    return "result";
}
  • Pass using ModelMap objects
@RequestMapping(value = "/testModelMap")
public String testModelMap(ModelMap modelMap){
    /*Save data to domain object*/
    modelMap.addAttribute("userName","Li Lei");
    return "result";
}
  • Transfer using Map objects
@RequestMapping(value = "/testMap")
public String testMap(Map map){
    /*Save data to domain object*/
    map.put("userName","Li Lei");
    return "result";
}
  • Model/ModelMap/Map relationship

Chapter 6 forwarding and redirection of spring MVC

  • Explain the essence of forwarding and redirection in one sentence
Forwarding is the server behavior, and redirection is the client behavior
  • Spring MVC return value processing
Normally,The value of the string type returned by the controller method will be treated as the logical view name
 If the returned string contains forward:or redirect:Prefix time,SpringMVC Special treatment will be given to them:take forward: and redirect: As an indicator,The following string is used as URL To handle

redirect:ok: Will complete a to ok of @RequestMapping("/ok") Redirected operation   redirect:/ok
forward :ok: Will complete a to ok of @RequestMapping("/ok") Forwarding operation       forward:/ok

Chapter 7 spring MVC file upload / download

1. SpringMVC It provides direct support for file upload
2. Through plug and play MultipartResolver realization
3. Spring use Jakarta Commons FileUpload Technology implements a MultipartResolver Implementation class CommonsMultipartResovler
4. SpringMVC The upload function is not enabled by default,Use needs to be configured in context MultipartResolver
5. Write form settings enctype="multipart/form-data"Enable file upload function

Section 1 file upload

  • rely on
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
  • Configure in the spring MVC configuration file
<!-- id You can't name casually -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<property name="defaultEncoding" value="UTF-8"/>
	<property name="maxUploadSize" value="1048576"/><!--have access to SpEL Set upload file size-->
</bean>
  • Front page
<form action="${pageContext.request.contextPath }/uploadFile" method="post" enctype="multipart/form-data">
	<input type="file" name="file"><br>
	<input type="submit" value="Submit">
</form>
  • Controller implementation
@RequestMapping(value="/testUpload")
public String testUpload(@RequestParam("file") MultipartFile[] multipartFiles) throws IllegalStateException, IOException {
	for (MultipartFile multipartFile : multipartFiles) {
		if(!multipartFile.isEmpty()) {
			multipartFile.transferTo(new File("Path to save the file"+multipartFile.getOriginalFilename()));
		}
	}
	return "result";
}

Section 2 file download

  • Front page
<a href="${pageContext.request.contextPath }/downloadFile">downloadFile</a>
  • Back-end Control
@RequestMapping(value="/downloadFile",method=RequestMethod.GET)
public ResponseEntity<byte[]> downloadFile() throws IOException{
	BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\abc.txt")));
	byte[] body = new byte[in.available()];
	in.read(body); //Read input stream to buffer
	//file name
	String fileName="China.txt";
	//When the file name is Chinese, it needs to be encoded, otherwise Chinese garbled code will appear
	fileName=URLEncoder.encode(fileName, "UTF-8");
	HttpHeaders header = new HttpHeaders();
	//inline: direct display
	//header.add("Content-Disposition", "inline;filename="+fileName);
	//Attachment Download
	header.add("Content-Disposition", "attachment;filename=f.txt");
	ResponseEntity<byte[]> result = new ResponseEntity<byte[]>(body,header,HttpStatus.OK);
	in.close();
	return result;
}

Chapter 8 spring MVC exception handling

1. SpringMVC adopt HandlerExceptionResolver Exception handling
2. DispaterServlet Default assembly HandlerExceptionResolver Exception handler

Section 1 single exception handling

//Setting specifies which exceptions in the current class are caught. Exceptions currently set as Exception and their subclasses will be caught
@ExceptionHandler(value= {Exception.class})
public ModelAndView testException(Exception e){
	System.out.println("error--->"+e.getMessage());
	ModelAndView mv = new ModelAndView();
	mv.addObject("myException", e);
	mv.setViewName("error");
	return mv;
}

Section 2 unified exception handling

1. Create a unified exception handling class
2. Add on class@ControllerAdvice annotation
3. Define exception methods and add@ExceptionHandler annotation
4. The return value of the method is ModelAndView,Return the exception message to the exception page for display
5. Finally, don't forget to SpringMVC Configure annotation driven tags in the core configuration file of<mvc:annotation-driven/>
  • Unified exception handling class
/**
 * @Author Fengqiao night park 1990
 * @BLOG https://hd1611756908.github.io/
 * @BSITE https://space.bilibili.com/514155929/
 * @DATE 2020/10/17
 */
@ControllerAdvice
public class CommonException {

    @ExceptionHandler(value = {Exception.class})
    public ModelAndView testException(Exception e){
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg",e.getMessage());
        mv.setViewName("error");
        return mv;
    }
}
  • Priority of exception
Find the exception handling in the current class first,If there is no match in the de unified exception handling class

Chapter 9 spring MVC static resource processing

Section 1 static resource processing

  • Which resources are static
1. Used in the project jquery function library
2. Custom in project js file
3. Customization used in the project css file
...
  • How to solve the problem of importing static resources (static resources are under webapp instead of WEB-INF)
stay SpringMVC Add the following tags to the core configuration file of

<mvc:default-servlet-handler></mvc:default-servlet-handler>

Section 2 interceptors for spring MVC

SpringMVC Interceptors are provided to intercept requests. We can customize interceptors to achieve specific functions

Steps to implement a custom interceptor:
1. realization HandlerInterceptor Interface,Rewrite the method inside
    1.1 perHandle
        - Called before business processing request
        - If the program needs to continue to execute after calling this interceptor, return true Otherwise return false
    1.2 postHandle
        - After the service processor processes the request,But in DispatcherServlet It is called to process the user request before returning the response to the client
    1.3 afterCompletion
        - DispatcherServlet After returning the response to the client, it is called to clean up some resources

2. stay SpringMVC Register a custom interceptor in the core configuration file
    2.1 Global interceptor registration
        <mvc:interceptors>
        	<bean id="empInterctptor" class="cn.ukoko.EmpInterctptor"></bean>
        </mvc:interceptors>
    2.2 Intercept a specified request
        <mvc:interceptors>
        	<mvc:interceptor>
        		<!-- intercept emps Address request -->
        		<mvc:mapping path="/emps"/>
        		<bean class="cn.ukoko.EmpInterctptor"></bean>
        	</mvc:interceptor>
        </mvc:interceptors>

Chapter 10 JSON data interaction of spring MVC

Section 1 adding dependencies

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.9.8</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.8</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>2.9.8</version>
</dependency>

Section 2 @ ResponseBody/@RequestBody

  • @ResponseBody
    • @The return time format of the ResponseBody annotation is long
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    • @ResponseBody annotation return time default time zone modification
@JsonFormat(timezone = "GMT+8")
  • @RequestBody
When are the methods in the controller used@RequestBody annotation?

@requestBody Annotations are often used to handle content-type Not default application/x-www-form-urlcoded,for instance: application/json Or application/xml Wait. Generally speaking, it is often used to deal with it application/json type
    • Front page
//Get button object
$("#btn1").click(function(){
	
	var book={"bookId":1001,"bookName":"Brief history of time","authorName":"Hawking","price":12.12};
	
	$.ajax({
		url:"savebook",
		type:"post",
		data:JSON.stringify(book),
		contentType:"application/json;charset=utf-8",
		success:function(msg){
			alert(msg);
		},
		dataType:"json"
	});
});
    • controller
@ResponseBody
@RequestMapping(value="/savebook",method=RequestMethod.POST)
public String savebook(@RequestBody Book book) {
	System.out.println("book:==: "+book);
	return "200";
}

Chapter 11 spring MVC solves cross domain calls

Section 1 what is cross domain

When a request url Any one of the protocol, domain name and port of the current page url Different is cross domain
Current page urlRequested page urlCross domainreason
http://www.test.com/http://www.test.com/index.htmlnoHomology (same protocol, domain name and port number)
http://www.test.com/https://www.test.com/index.htmlCross domainDifferent protocols (http/https)
http://www.test.com/http://www.baidu.com/Cross domainDifferent primary domain names (test/baidu)
http://www.test.com/http://blog.test.com/Cross domainDifferent subdomains (www/blog)
http://www.test.com:8080/http://www.test.com:7001/Cross domainDifferent port numbers (8080 / 7001)

Section 2 Spring's cross domain approach

SpringMVC Of 4.2 Version provides@CrossOrigin Annotations can solve cross domain problems

Chapter 12 spring MVC mock test

Section 1 Introduction to Mock

  • What is the Mock test
Mock Testing is in the process of testing,For some objects that are not easy to construct or obtain,Use a virtual object to create a test method for testing
  • Why use the Mock test
use Mock Test,It is mainly used to simulate those that are not easy to construct in application(as HttpServletRequest Must be Servlet Can only be constructed in the container)Or more complex objects,So as to make the test go smoothly

  • Common annotations used in Mock test

WebAppConfiguratio

Use this annotation Will actually start one when running the unit test web service,Then start calling Controller of RestAPI,Wait until the unit test runs web Service stopped

ContextConfiguration

appoint Bean Profile information for,There can be many ways,This example uses the form of file path,If there are multiple profiles,The information in parentheses can be configured as an array of strings

RunWith

Specifies the test container to run

Section 2 installation of Mock test environment

Spring MVC The testing framework provides two ways,Independent installation and integration Web Environmental testing(This approach does not integrate real web environment,But through the corresponding Mock API Conduct simulation test,There is no need to start the server)
  • Add dependency
<dependency>
  <groupId>javax</groupId>
  <artifactId>javaee-api</artifactId>
  <version>7.0</version>
  <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

be careful: Current version spring Frame needs 3.0 Above version servlet-api Support unit testing
  • Create MockMvc object

Installation test environment mode I (independent installation mode)

/**
 * Independent installation test
 * Servlet API dependent
 */
public class BookControllerTest {
	
	private MockMvc mockMvc;

	@Before
	public void setUp() {
	    //Specify a set of controllers through parameters, so you don't need to get from the context
		this.mockMvc = MockMvcBuilders.standaloneSetup(new BookController()).build();
	}
	@Test
	public void testMockMvc() throws Exception {
		System.out.println(mockMvc);
	}
}

Installation test environment mode 2 (integrated Web environment mode)

/**
 * Integrated Web environment mode
 */
@RunWith(SpringRunner.class)
@ContextConfiguration(locations= {"classpath:spring-mvc.xml"})
//If the configuration file of spring MVC is written in the following way under WEB-INF
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/springDispatcherServlet-servlet.xml"})
@WebAppConfiguration
public class BookControllerTest2 {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }
    
    @Test
	public void testMockMvc() throws Exception {
		System.out.println(mockMvc);
	}
}

Section 3 use of Mock

3.1 test of method (the return value is JSON or string, and the method has no input parameters)

  • Model data entity class
public class User {
    private Integer userId;
    private String userName;
    private Date hireDate;
}
  • Controller method of test
@ResponseBody
@RequestMapping(value = "/getUserJson",method = RequestMethod.GET)
public User getUserJson(){
    User user = new User(1001, "Moor at night", new Date());
    return user;
}
  • Unit test code
@Test
public void getUserJson() throws Exception {
    ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.get("/getUserJson"));
    MvcResult mvcResult = resultActions.andReturn();
    MockHttpServletResponse response = mvcResult.getResponse();
    int status = response.getStatus();//Response status code
    String content = response.getContentAsString();//Response results
    System.out.println("Response status code:"+status);
    System.out.println("Response content:"+content);
}

3.2 traditional (?) [GET request] method setting input parameter

  • Controller method of test
@ResponseBody
@RequestMapping(value = "/getUser",method = RequestMethod.GET)
public User getUser(Integer userId,String userName){
    User user = new User();
    user.setUserId(userId);
    user.setUserName(userName);
    user.setHireDate(new Date());
    return user;
}
  • Unit test code
@Test
public void getUser() throws Exception {
    ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.get("/getUser?userId={xyz}&userName={userName}", 100,"Mei Mei Han"));
    MvcResult mvcResult = resultActions.andReturn();
    MockHttpServletResponse response = mvcResult.getResponse();
    int status = response.getStatus();//Response status code
    String content = response.getContentAsString();//Response results
    System.out.println("Response status code:"+status);
    System.out.println("Response content:"+content);
}

3.3 use placeholder {placeholder parameter} to set input parameter [GET request]

  • Controller method of test
@ResponseBody
@RequestMapping(value = "/getUser2/{userId}/{userName}",method = RequestMethod.GET)
public User getUser2(@PathVariable("userId") Integer userId,@PathVariable("userName") String userName){
    User user = new User();
    user.setUserId(userId);
    user.setUserName(userName);
    user.setHireDate(new Date());
    return user;
}
  • Unit test code
@Test
public void getUser2() throws Exception {
    ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.get("/getUser2/1000/Li Lei"));
    MvcResult mvcResult = resultActions.andReturn();
    MockHttpServletResponse response = mvcResult.getResponse();
    int status = response.getStatus();//Response status code
    String content = response.getContentAsString();//Response results
    System.out.println("Response status code:"+status);
    System.out.println("Response content:"+content);
}

3.4 setting JSON as input parameter

  • Controller method of test
@ResponseBody
@RequestMapping(value = "/getUserForRequestJson",method = RequestMethod.POST)
public String getUserForRequestJson(@RequestBody User user){
    System.out.println("Input parameter is: "+user);
    return "success";
}
  • Unit test code
@Test
public void getUserForRequestJson() throws Exception {
    String var="{\"userId\":1001,\"userName\":\"Li Lei\",\"hireDate\":\"2020-12-12 22:22:22\"}";
    /**
     * contentType:  Sets the type of parameter passed
     * content: Set the passed parameter content
     */
    ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.post("/getUserForRequestJson").contentType(MediaType.APPLICATION_JSON_UTF8).content(var));
    MvcResult mvcResult = resultActions.andReturn();
    MockHttpServletResponse response = mvcResult.getResponse();
    int status = response.getStatus();//Response status code
    String content = response.getContentAsString();//Response results
    System.out.println("Response status code:"+status);
    System.out.println("Response content:"+content);
}

3.5 test that the return value of controller method is view

  • Controller method of test
@RequestMapping(value = "/testView",method = RequestMethod.GET)
public String testView(Integer userId, Model model){
    System.out.println("Test View jump... userId="+userId);
    //Store data into the model
    model.addAttribute("userId",userId);
    //Return to view
    return "testview";
}
  • Unit test code
@Test
public void testView() throws Exception {
    ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.get("/testView?userId={userId}", 10000));
    //Verify whether the data of this key is stored in the model
    resultActions.andExpect(MockMvcResultMatchers.model().attributeExists("userId"));
    //Verify that this view exists for the model
    resultActions.andExpect(MockMvcResultMatchers.view().name("testview"));
    //Verify request status
    resultActions.andExpect(MockMvcResultMatchers.status().isOk());
    // Print it out for him
    resultActions.andDo(MockMvcResultHandlers.print());
    //Return results
    MvcResult result = resultActions.andReturn();

    //The above operations can be connected into a string for operation
    //MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/testView?userId={userId}", 10000)).andExpect(MockMvcResultMatchers.model().attributeExists("userId")).andExpect(MockMvcResultMatchers.view().name("testview")).andDo(MockMvcResultHandlers.print()).andReturn();
}


andExpect: Add validation assertion after execution
andDo    : Add a result processor
andReturn: Return the result of the response after execution

Chapter 13 spring MVC operation process

Topics: Java Spring Spring MVC