RESTful specific case – based on RESTful page data interaction

Based on RESTful page data interaction

Needs Analysis

(Note: The focus of this case is how to use RESTful in SpringMVC to achieve front-end and back-end interaction, so this case does not interact with the database, and all data uses fake data to complete the development.)

Requirement 1: The “Add” picture is as follows, and the data of the newly added book is passed to the background and printed on the console.

Requirement 2: Image list query, return data from the background, and display the data on the page

Step Analysis

  • Build project import jar package

[Step 1: Create a Web Maven project]
[Step 2: add Spring dependencies to pom.xml]:

<?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_07_rest_case</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>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</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>

[Step 3: Create the corresponding configuration class]:

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};
   }
}
 
@Configuration
@ComponentScan("com. itheima. controller")
//Enable json data type automatic conversion
@EnableWebMvc
public class SpringMvcConfig {<!-- -->
}

[Step 4: Write the model class Book]:

public class Book {<!-- -->
    private Integer id;
    private String type;
    private String name;
    private String description;
    //setter...getter...toString slightly
}

[Step 5: Write BookController]:

@Controller
public class BookController {<!-- -->
}

【Final directory】:

  • Write the Controller class and provide two methods, one for list query and one for new addition
@RestController
@RequestMapping("/books")
public class BookController {<!-- -->
//Requirement 1, add book data to the background
    @PostMapping
    public String save(@RequestBody Book book){<!-- -->//RequestBody receives JSON data
        System.out.println("book save ==> " + book);
        return "{'module':'book save success'}";
   }
   //Requirement 2, display the background data to the page
 @GetMapping
    public List<Book> getAll(){<!-- -->
        System.out.println("book getAll is running...");
        //Put the background data book object into the collection List
        List<Book> bookList = new ArrayList<Book>();
        Book book1 = new Book();
        book1.setType("Computer");
        book1.setName("SpringMVC Introductory Course");
        book1.setDescription("Small test");
        bookList.add(book1);
        
        Book book2 = new Book();
        book2.setType("Computer");
        book2.setName("SpringMVC Practical Course");
        book2.setDescription("Grandmaster");
        bookList. add(book2);
        
        Book book3 = new Book();
        book3.setType("Computer");
        book3.setName("SpringMVC practical tutorial advanced");
        book3.setDescription("A generation of masters worked hard");
        bookList. add(book3);
        
        return bookList;
        }
}
  • Testing with PostMan

【Add to test】:

{<!-- -->
"type": "Computer From Book",
"name": "SpringMVC Ultimate Development",
"description":"This is a good book"
}


[Test Query]:

  • Copy the front-end page to the project
    [Step 1: Copy the static page]: Copy all the content under the front-end page to the webapp directory of the project:

    [Step 2: Visit books.html in the pages directory]: Open the browser and enter http://localhost/pages/books.html

    (1) What is the reason for the error?

    SpringMVC intercepts static resources, and finds the corresponding method in the controller according to /pages/books.html. If it cannot find it, it will report a 404 error.
    (2), Why does SpringMVC intercept static resources?

    (3), solution?
    SpringMVC needs to release static resources.
@Configuration

public class SpringMvcSupport extends WebMvcConfigurationSupport {<!-- -->
    //Set static resource access filtering, the current class needs to be set as a configuration class, and be scanned and loaded
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {<!-- -->
        //When accessing /pages/, look for content from the /pages directory
 registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/")
;
   }
}

The configuration class is in the config directory. SpringMVC scans the controller package, so the configuration class has not yet taken effect. To take effect, the SpringMvcConfig configuration class needs to be modified

@Configuration
@ComponentScan({<!-- -->"com.itheima.controller","com.itheima.config"})
@EnableWebMvc
public class SpringMvcConfig {<!-- -->
}
or
@Configuration
@ComponentScan("com.itheima")
@EnableWebMvc
public class SpringMvcConfig {<!-- -->
}
  • The page sends an ajax request



  • Complete the display of page data