Initial Spring MVC [medium]

Posted by lee20 on Tue, 14 Dec 2021 02:09:50 +0100


ps: continued

5, Picture upload

5.1 general

  • spring mvc uses Commons fileUpload by default to upload files.

5.2 introduction cases

5.2. 1 import coordinates

<!--File upload-->
<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.4</version>
</dependency>

5.2. 2 configuration class

  • Use CommonsMultipartResolver to set parameters for uploaded files
package com.czxy.mvc.config;

        import org.springframework.context.annotation.Bean;
        import org.springframework.context.annotation.ComponentScan;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.format.FormatterRegistry;
        import org.springframework.format.datetime.DateFormatter;
        import org.springframework.web.multipart.commons.CommonsMultipartResolver;
        import org.springframework.web.servlet.config.annotation.EnableWebMvc;
        import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
        import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

        import java.util.Date;


/**
 * @Author: Xiaoxin
 * @Date: 2021-12-07 16:48
 */
@Configuration
@ComponentScan(basePackages = {"com.czxy.mvc.controller")
@EnableWebMvc
public class MvcConfiguration implements WebMvcConfigurer {
    /**
     * Upload file processor
     * @return
     */
    @Bean
    public CommonsMultipartResolver multipartResolver(){
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        //Set the total size of all uploaded files
        multipartResolver.setMaxInMemorySize(10 * 1024 * 1024);
        //Set the upload size of a single file 4m
        multipartResolver.setMaxUploadSize(4 * 1024 * 1024);
        multipartResolver.setDefaultEncoding("utf-8");
        return multipartResolver;
    }
}

5.2. 3. Single file upload

  • Requirements: select a picture to upload to the server and save it to the specified location
  • Write processing class Controller:
package com.czxy.mvc.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @Author: Xiaoxin
 * @Date: 2021-12-10 19:54
 */
@Controller
@RequestMapping("/demo05")
public class Demo05UploadController {

    /**
     * Single file upload
     * @param image
     * @return
     * @throws IOException
     */
    @RequestMapping("/upload")
    public String upload(MultipartFile image) throws IOException {
        System.out.println("Upload file name:" + image.getOriginalFilename());
        System.out.println("Upload file stream:" + image.getInputStream());

        File file = new File("D:\\image", image.getOriginalFilename());
        FileUtils.copyInputStreamToFile(image.getInputStream(), file);
        return "file";
    }
}
  • Access path + form:
<!--Single file upload-->
<form action="${pageContext.request.contextPath}/demo05/upload.action" method="post" enctype="multipart/form-data">
    Select file: <input type="file" name="image" /> <br/>
    <input type="submit" value="Single file upload"/> <br/>
</form>

5.2. 4 multi file upload

  • Requirements: select three pictures to upload to the server and save them to the specified location
  • Write processing class Controller:
package com.czxy.mvc.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @Author: Xiaoxin
 * @Date: 2021-12-10 19:54
 */
@Controller
@RequestMapping("/demo05")
public class Demo05UploadController {
    /**
     * Multi file upload
     * @param images
     * @return
     * @throws IOException
     */
    @RequestMapping("/upload2")
    public String upload2(List<MultipartFile> images) throws IOException {
        for (MultipartFile image : images) {
            System.out.println("Upload file name:" + image.getOriginalFilename());
            System.out.println("Upload file stream:" + image.getInputStream());

            File file = new File("D:\\image", image.getOriginalFilename());
            FileUtils.copyInputStreamToFile(image.getInputStream(), file);
        }
        return "file";
    }
}
  • Access path + form:
<form action="${pageContext.request.contextPath}/demo05/upload2.action" method="post" enctype="multipart/form-data">
    Select file: <input type="file" name="images" /> <br/>
    Select file: <input type="file" name="images" /> <br/>
    Select file: <input type="file" name="images" /> <br/>
    <input type="submit" value="Multi file upload"/> <br/>
</form>

6, JSON data exchange

6.1 json data format

6.1. 1 what is JSON data?

  • Is a lightweight data exchange format.
  • Lightweight, independent of any framework or language.

6.1. 2. Data classification: object and array

  • Object:
    • key must use double quotation marks.
    • Except for special types, value needs to use double quotation marks (special types: number, Boolean, true/false)
    • example:
{
    "k":"v",
    "k2":"v2",....
}
  • Array:
[
	element,Element 2,....
]

6.2 JSON usage process

6.3 introduction cases

6.3. 1 objectives

  • Target: request JSON data and respond to JSON data.
  • Requirement: user condition query.
  • Request: query criteria User.
  • Response: query result List

6.3. 2 implementation

  • Premise: the JSON data from the bottom jackson of spring mvc.
<!-- mvc json -->
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.10.2</version>
</dependency>
  • Write JavaBean User class
public class User {
    private Integer id;
    private String username;
    private String password;
    private Integer age;
    @JsonIgnore
    private List<String> hobbies;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    //@DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")
    private Date birthday;

    public User(Integer id, String username, String password, Date birthday) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.birthday = birthday;
    }

    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public User(String username, String password, Integer age) {
        this.username = username;
        this.password = password;
        this.age = age;
    }

    public User() {
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", hobbies=" + hobbies +
                ", birthday=" + birthday +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<String> getHobbies() {
        return hobbies;
    }

    public void setHobbies(List<String> hobbies) {
        this.hobbies = hobbies;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public User(Integer id, String username, String password, List<String> hobbies, Date birthday) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.hobbies = hobbies;
        this.birthday = birthday;
    }
}
  • Write controller to receive request data @ RequestBody
@Controller
@RequestMapping("/demo06")
public class Demo06JsonController {

    @RequestMapping("/list")
    public void list(@RequestBody User user) {
        System.out.println(user);
    }
}
  • Write the controller to respond to the data @ ResponseBody
package com.czxy.mvc.controller;

import com.czxy.mvc.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.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: Xiaoxin
 * @Date: 2021-12-10 20:14
 */
@Controller
@RequestMapping("/demo06")
public class Demo06JsonController {

    /**
     * Request JSON data and respond to JSON data
     * @param user
     * @return
     */
    @RequestMapping(/*value = "/list" , method = RequestMethod.POST*/"/list")
    @ResponseBody
    public List<User> list(@RequestBody User user){
        System.out.println(user);
        //Response data
        ArrayList<User> list = new ArrayList<>();
        list.add(new User(1,"Small bottle","54250",new Date()));
        list.add(new User(2,"Pangpang","6666"));
        list.add(new User(3,"Xiaoxin","Cow break"));

        return list;
    }
}
  • post Man test

6.4 common notes

annotationdescribe
@RequestBodyThe request data is a JSON string
@ResponseBodyThe response data is a JSON string
@@JsonIgnoreIgnore specified properties
@JsonFormatFormatting of JSON data date
  • @JsonIgnore is used to ignore some attributes in Java beans during json serialization
public class User {
    @JsonIgnore
    private List<String> hobby;
}
  • @JsonFormat format date
public class User {
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Date birthday;
}

7, RESTFul

7.1 what is RESTFul

  • RESTFul programming is a style, not a protocol
  • Interpretation of http protocol (landing scheme) and landing of request mode
    http There are seven protocols, four are common, and two are most commonly used
    get,post,put,delete
    
  • RESTFul specifies the server program operation:
    • Each operation consists of: request path + request mode. (the same path can complete different operations because of different request methods).

7.2 data transmission mode: JSON data

  • RESTFul style path:
Query: get    http://localhost:8080/user/
Details: get    http://localhost:8080/user/123
 add to: post   http://localhost:8080/user/
Modification: put    http://localhost:8080/user/
Delete: delete http://localhost:8080/user/123

7.3 notes

7.3. Class 1 level

  • @RestController: synthetic injection (@ Controller, @ ResponseBody)

7.3. 2 method level

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping

7.3. 3 parameters

  • @PathVariable: used to get path parameters

7.4 method return value

//According to the constraints and based on the RESTFul style, it is recommended to use the ResponseEntity type for the return value of the method
// ResponseEntity is used to encapsulate return value information, including status code
// Return 200 status code, responseentity OK ("added successfully");
// Other status codes, new responseentity < > ("added successfully", HttpStatus.UNAUTHORIZED)

7.5 introduction cases (addition, deletion, modification and query)

7.5. 1 implementation

  • Configure class WebInitializer:
package com.czxy.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * @Author: Xiaoxin
 * @Date: 2021-12-07 16:49
 */
public class WebInitializer  implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        //1 configure spring Factory
        AnnotationConfigWebApplicationContext application = new AnnotationConfigWebApplicationContext();
        // Register all configuration classes
        application.register(MvcConfiguration.class);

        //2 post Chinese garbled code
        FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encoding", new CharacterEncodingFilter("UTF-8"));
        encodingFilter.addMappingForUrlPatterns(null, true, "/*");

        //3 core controller
        ServletRegistration.Dynamic mvcServlet = servletContext.addServlet("springmvc", new DispatcherServlet(application));
        //mvcServlet.addMapping("*.action");
        mvcServlet.addMapping("/");
        mvcServlet.setLoadOnStartup(2);	//When tomcat starts, the initialization method of servlet is executed
    }
}
  • Configuration class MvcConfiguration:
package com.czxy.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


/**
 * @Author: Xiaoxin
 * @Date: 2021-12-07 16:48
 */
@Configuration
@ComponentScan(basePackages = {"com.czxy.controller"})
@EnableWebMvc
public class MvcConfiguration implements WebMvcConfigurer {
}
  • javaBean User:
package com.czxy.domain;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.Date;
import java.util.List;

/**
 * @Author: Xiaoxin
 * @Date: 2021-12-13 20:02
 */
public class User {
    private Integer id;
    private String username;
    private String password;
    private Integer age;
    @JsonIgnore
    private List<String> hobbies;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    //@DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")
    private Date birthday;

    public User(Integer id, String username, String password, Date birthday) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.birthday = birthday;
    }

    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public User(String username, String password, Integer age) {
        this.username = username;
        this.password = password;
        this.age = age;
    }

    public User() {
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", hobbies=" + hobbies +
                ", birthday=" + birthday +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<String> getHobbies() {
        return hobbies;
    }

    public void setHobbies(List<String> hobbies) {
        this.hobbies = hobbies;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public User(Integer id, String username, String password, List<String> hobbies, Date birthday) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.hobbies = hobbies;
        this.birthday = birthday;
    }
}

  • controller:
package com.czxy.controller;

import com.czxy.domain.User;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: Xiaoxin
 * @Date: 2021-12-13 20:02
 */
@RestController
@RequestMapping("/user")
public class Demo01Controller {

    /**
     * Query all
     * get
     * @return
     */
    @GetMapping
    public List<User> selectAll(){
        ArrayList<User> list = new ArrayList<>();
        list.add(new User(1,"jack","1234"));
        list.add(new User(2,"rose","4567"));
        list.add(new User(3,"tom","5678"));

        return list;
    }

    /**
     * Query details by id
     * @param uid
     * @return
     */
    @GetMapping("/{id}")
    public String selectAll(@PathVariable("id") String uid){
        System.out.println("selectById" + uid);
        return "selectById success";
    }


    /**
     * add to
     * post
     * @param user
     * @return
     */
    @PostMapping
    public User insert(@RequestBody  User user){
        System.out.println("Successfully added:" + user);
        return user;
    }


    /**
     * to update
     * put
     * @param user
     * @return
     */
    @PutMapping
    public User update(@RequestBody  User user){
        System.out.println("Update succeeded" + user);
        return user;
    }

    /**
     * delete
     * delete
     * @param uid
     * @return
     */
    @DeleteMapping("/{id}")
    public String delete(@PathVariable("id") String uid){
        System.out.println("delete" + uid);
        return "delete success";
    }
}

Topics: Java Spring mvc