Spring MVC

Overview:

Same as servlet technology, both belong to web development

more concise code

Case

1. Create a maven project

2. Complete the directory structure

3. Import the jar package

<?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.itheima</groupId>
  <artifactId>springmvc_01_quickstart</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.10.RELEASE</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.1</version>
        <configuration>
          <port>80</port>
          <path>/</path>
        </configuration>
      </plugin>
    </plugins>
  </build>


</project>

4. Create a configuration class

package com.itheima.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

//springmvc configuration class, essentially a spring configuration class
@Configuration
@ComponentScan("com. itheima. controller")
public class SpringMvcConfig {
}

5. Create a controller class

package com.itheima.controller;

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

//Define the presentation layer controller bean
@Controller
public class UserController {

    //Set the mapping path to /save, which is the external access path
    @RequestMapping("/save1")
    //Set the return result of the current operation to the specified json data (essentially a string information)
    @ResponseBody
    public String save1(){
        System.out.println("user save...");
        return "{'info':'springmvc'}";
    }

    //Set the mapping path to /delete, which is the external access path
    @RequestMapping("/delete1")
    @ResponseBody
    public String delete1(){
        System.out.println("user save...");
        return "{'info':'springmvc'}";
    }
}

6. Replace web.xml with configuration class and delete the file

package com.itheima.config;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;

//web container configuration class
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
    //Load the springmvc configuration class to generate the springmvc container (the essence is still the spring container)
    protected WebApplicationContext createServletApplicationContext() {
        //Initialize the WebApplicationContext object
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        //Load the specified configuration class
        ctx.register(SpringMvcConfig.class);
        return ctx;
    }

    //Set the request mapping path handled by the springmvc controller
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    //Load the spring configuration class
    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }
}

7. Configure tomcat environment: tomcat7.run

8. Start and run the project. If there is another 404, you need to check whether there is any redundant task manager that needs to be closed, as shown in the figure below

Notes

SpringMVC is based on Spring. The reason why only the spring-webmvcjar package is imported in pom.xml is that it will automatically rely on spring-related coordinates

The AbstractDispatcherServletInitializer class is an abstract class provided by SpringMVC to quickly initialize the Web3.0 container. AbstractDispatcherServletInitializer provides three interface methods for users to implement

createServletApplicationContext method: When creating a Servlet container, load the bean corresponding to SpringMVC and put it in

In the scope of the WebApplicationContext object: the scope of the WebApplicationContext is the ServletContext scope, that is, the getServletMappings method of the entire web container scope, and the request mapping path corresponding to SpringMVC is set, that is, which requests SpringMVC intercepts. bean, use the current method, and use the same method as createServletApplicationContext. createServletApplicationContext: used to load the SpringMVC environment createRootApplicationContext is used to load the Spring environment

Summarize:

One time job:

Create a project, set up the server, load the project import coordinates, create a web container startup class, load the SpringMVC configuration, and set the SpringMVC request interception path SpringMVC core configuration class (set the configuration class, scan the controller package, load the Controller controller bean)

Works multiple times:

Define the controller class that handles the request Define the controller method that handles the request, and configure the mapping path (@RequestMapping) and return json data (@ResponseBody)

bean-load

The bean scope of spring loading and springMVC loading is different and needs to be avoided

springMvc related bean bean presentation layer bean

Bean controlled by spring business bean (service), functional bean (datasource)

Spring MVC-related bean control: the packages corresponding to the beans loaded by spring MVC are all in the controller package class

Spring-related bean control loading:

Method 1: Load the scanning range and exclude the controller

@Configuration
//@ComponentScan({"com.itheima.service","com.itheima.dao"})
//Set the filtering rules when the spring configuration class loads beans, and currently require to exclude the beans corresponding to the presentation layer
//excludeFilters attribute: set the exclusion filtering rules when scanning and loading beans
//type attribute: set the exclusion rules, currently use the annotation type when the bean is defined to exclude
//classes attribute: set the specific annotation class to be excluded, and the current setting excludes the bean defined by @Controller
@ComponentScan(value="com.itheima",
    excludeFilters = @ComponentScan. Filter(
        type = FilterType. ANNOTATION,
        classes = Controller. class
    )
)
public class SpringConfig {
}

Method 2: spring accurate loading

@Configuration
//@ComponentScan("com.iheima.controller") Comment out this sentence in method 1
public class SpringMvcConfig {
}

Simplify development

package com.itheima.config;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
//web configuration class simplifies development, just set the class name of the configuration class
public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {

    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig. class};
    }

    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig. class};
    }

    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}
/*

public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(SpringMvcConfig.class);
        return ctx;
    }
    protected WebApplicationContext createRootApplicationContext() {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(SpringConfig.class);
        return ctx;
    }
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

}
*/

Introduction to postman tools

for interface testing

It is a powerful Google plug-in for webpage debugging and sending webpage HTTP requests

post request:

Request and Response

Request mapping path

@requestMapping method annotation class annotation

Above springmvc controller method definition

Set the access path for the current controller method request, if the setting is set on the class, the current controller method request access path prefix is uniformly set

@Controller
public class BookController {
    //Request path mapping
    @RequestMapping("/book/save")
    @ResponseBody
    public String save(){
        System.out.println("book save...");
        return "{'module':'book save'}";
    }
}

Request parameters

get request

Ordinary parameters: url address pass parameter The address parameter is the same as the variable name of the formal parameter, and the parameter can be accepted by defining the formal parameter

@RequestMapping("/commonParam")
    @ResponseBody
    public String commonParam(String name ,int age){
        System.out.println("Ordinary parameter passing name ==> " + name);
        System.out.println("Ordinary parameter passing age ==> " + age);
        return "{'module':'common param'}";

post request

The form form post requests to pass parameters, the form parameter name is the same as the formal parameter variable name, and the parameter can be accepted by defining the formal parameter

 @RequestMapping("/commonParamDifferentName")
    @ResponseBody
    public String commonParamDifferentName(@RequestParam("name") String userName , int age){
        System.out.println("Ordinary parameter passing userName ==> " + userName);
        System.out.println("Ordinary parameter passing age ==> " + age);
        return "{'module':'common param different name'}";

post request Chinese garbled processing

Add a filter to the web container and specify a character set The spring-web package provides a dedicated character filter

public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    protected Class<?>[] getRootConfigClasses() {
        return new Class[0];
    }

    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig. class};
    }

    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    // Garbled code processing
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        return new Filter[]{filter};
    }
}

pojo parameters

 //POJO parameter: The request parameter corresponds to the attribute in the formal parameter object to complete the parameter transfer
    @RequestMapping("/pojoParam")
    @ResponseBody
    public String pojoParam(User user){
        System.out.println("pojo parameter passing user ==> " + user);
        return "{'module':'pojo param'}";
    }

Nested pojo parameters

 //Nested POJO parameters: nested attributes set names according to the hierarchy to complete parameter passing
    @RequestMapping("/pojoContainPojoParam")
    @ResponseBody
    public String pojoContainPojoParam(User user){
        System.out.println("pojo nested pojo parameter passing user ==> " + user);
        return "{'module':'pojo contain pojo param'}";
    }

//Array parameters: Request parameters with the same name can be directly mapped to the formal parameter group object with the corresponding name

@RequestMapping("/arrayParam")
    @ResponseBody
    public String arrayParam(String[] likes){
        System.out.println("Array parameter passing likes ==> " + Arrays.toString(likes));
        return "{'module':'array param'}";
    }

//Collection parameters: Request parameters with the same name can use the @RequestParam annotation to map to a collection object with the corresponding name as data

 //Collection parameters: Request parameters with the same name can be mapped to collection objects with corresponding names as data using the @RequestParam annotation
    @RequestMapping("/listParam")
    @ResponseBody
    public String listParam(@RequestParam List<String> likes){
        System.out.println("Collection parameter passing likes ==> " + likes);
        return "{'module':'list param'}";
    }

@RequestParam:

Formal parameter annotation The relationship between binding request parameters and processor method formal parameters

Response json data

//Collection parameters: json format

add coordinates

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

//1. Turn on the automatic conversion of the json data format, and turn on @EnableWebMvc in the configuration class

//2. Use the @RequestBody annotation to map the externally passed json array data to the collection object of the formal parameter as data

 @RequestMapping("/listParamForJson")
    @ResponseBody
    public String listParamForJson(@RequestBody List<String> likes){
        System.out.println("list common(json) parameter passing list ==> " + likes);
        return "{'module':'list common for json param'}";
    }

    //POJO parameter: json format
    //1. Turn on the automatic conversion of the json data format, and turn on @EnableWebMvc in the configuration class
    //2. Use the @RequestBody annotation to map the externally passed json data to the entity class object of the formal parameter, requiring a one-to-one correspondence between the attribute names
    @RequestMapping("/pojoParamForJson")
    @ResponseBody
    public String pojoParamForJson(@RequestBody User user){
        System.out.println("pojo(json) parameter passing user ==> " + user);
        return "{'module':'pojo for json param'}";
    }

    //Collection parameters: json format
    //1. Turn on the automatic conversion of the json data format, and turn on @EnableWebMvc in the configuration class
    //2. Use the @RequestBody annotation to map the externally passed json array data to the collection object of the saved entity class object of the formal parameter, requiring a one-to-one correspondence between the attribute names
    @RequestMapping("/listPojoParamForJson")
    @ResponseBody
    public String listPojoParamForJson(@RequestBody List<User> list){
        System.out.println("list pojo(json) parameter passing list ==> " + list);
        return "{'module':'list pojo for json param'}";
    }

@RequestBody and @RequestParam

@RequestBody is used to accept json data

@RequestParam is used to receive url address parameters and form parameters

Date type parameter passing

Use the @DateTimeFormat annotation to set the date type data format, the default format is yyyy/MM/dd

The date type is also different based on different formats of the system. The accepted parameter is to set different acceptance methods according to different date formats

 @RequestMapping("/dataParam")
    @ResponseBody
    public String dataParam(Date date,
                            @DateTimeFormat(pattern="yyyy-MM-dd") Date date1,
                            @DateTimeFormat(pattern="yyyy/MM/dd HH:mm:ss") Date date2){
        System.out.println("parameter passing date ==> " + date);
        System.out.println("parameter passing date1(yyyy-MM-dd) ==> " + date1);
        System.out.println("parameter passing date2(yyyy/MM/dd HH:mm:ss) ==> " + date2);
        return "{'module':'data param'}";
    }

Convert interface Convert format, request parameter age data from string to integer date format conversion string to date

Response

@Controller
public class UserController {

    //response page/jump page
    //The return value is String type, set the return value to the page name, and the page jump can be realized
    @RequestMapping("/toJumpPage")
    public String toJumpPage(){
        System.out.println("jump page");
        return "page.jsp";
    }

    //response text data
    //The return value is String type, set the return value to any string information, you can return the specified string information, you need to rely on the @ResponseBody annotation
    @RequestMapping("/toText")
    @ResponseBody
    public String toText(){
        System.out.println("Return plain text data");
        return "response text";
    }

    //response POJO object
    //The return value is an entity class object. Set the return value to the entity class type to return the json data of the corresponding object. It needs to rely on @ResponseBody annotation and @EnableWebMvc annotation
    @RequestMapping("/toJsonPOJO")
    @ResponseBody
    public User toJsonPOJO(){
        System.out.println("Return json object data");
        User user = new User();
        user.setName("itcast");
        user.setAge(15);
        return user;
    }

    //Response POJO collection object
    //The return value is a collection object. Set the return value to the collection type to return the json array data of the corresponding collection. It needs to rely on @ResponseBody annotation and @EnableWebMvc annotation
    @RequestMapping("/toJsonList")
    @ResponseBody
    public List<User> toJsonList(){
        System.out.println("Return json collection data");
        User user1 = new User();
        user1.setName("Chuanzhi Podcast");
        user1. setAge(15);

        User user2 = new User();
        user2.setName("Dark Horse Programmer");
        user2.setAge(12);

        List<User> userList = new ArrayList<User>();
        userList. add(user1);
        userList. add(user2);

        return userList;
    }
}

@ResponseBody to json return

rest style

Representational State Transitions

Format for accessing web resources

When accessing resources according to the rest style, use behavior actions to distinguish operations on resources: query get add post modify put delete delete

Quick start:

//@Controller
//@ResponseBody configuration can simplify the configuration on the class, indicating that the return value of each current method is set as the response body
//@ResponseBody
@RestController //Use the @RestController annotation to replace the @Controller and @ResponseBody annotations to simplify writing
@RequestMapping("/books")
public class BookController {

// @RequestMapping( method = RequestMethod. POST)
    @PostMapping //Use @PostMapping to simplify the mapping configuration corresponding to the Post request method
    public String save(@RequestBody Book book){
        System.out.println("book save..." + book);
        return "{'module':'book save'}";
    }

// @RequestMapping(value = "/{id}" ,method = RequestMethod.DELETE)
    @DeleteMapping("/{id}") //Use @DeleteMapping to simplify the mapping configuration corresponding to the DELETE request method
    public String delete(@PathVariable Integer id){
        System.out.println("book delete..." + id);
        return "{'module':'book delete'}";
    }

// @RequestMapping(method = RequestMethod.PUT)
    @PutMapping //Use @PutMapping to simplify the mapping configuration corresponding to the Put request method
    public String update(@RequestBody Book book){
        System.out.println("book update..." + book);
        return "{'module':'book update'}";
    }

// @RequestMapping(value = "/{id}" ,method = RequestMethod.GET)
    @GetMapping("/{id}") //Use @GetMapping to simplify the mapping configuration corresponding to the GET request method
    public String getById(@PathVariable Integer id){
        System.out.println("book getById..." + id);
        return "{'module':'book getById'}";
    }

// @RequestMapping(method = RequestMethod.GET)
    @GetMapping //Use @GetMapping to simplify the mapping configuration corresponding to the GET request method
    public String getAll(){
        System.out.println("book getAll...");
        return "{'module':'book getAll'}";
    }
}

ssm integration

Interceptor