初始 Spring MVC【中】

Spring MVC 入门


ps:接上篇

五、图片上传

5.1 概述

  • spring mvc 默认使用 commons-fileupload 完成文件上传。

5.2 入门案例

5.2.1 导入坐标

<!--文件上传-->
<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.4</version>
</dependency>

5.2.2 配置类

  • 使用 CommonsMultipartResolver 对上传文件进行参数设置
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: 小新
 * @Date: 2021-12-07 16:48
 */
@Configuration
@ComponentScan(basePackages = {"com.czxy.mvc.controller")
@EnableWebMvc
public class MvcConfiguration implements WebMvcConfigurer {
    /**
     * 上传文件处理器
     * @return
     */
    @Bean
    public CommonsMultipartResolver multipartResolver(){
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        //设置所有的上传文件的总大小 10m
        multipartResolver.setMaxInMemorySize(10 * 1024 * 1024);
        //设置单个文件上传的大小 4m
        multipartResolver.setMaxUploadSize(4 * 1024 * 1024);
        multipartResolver.setDefaultEncoding("utf-8");
        return multipartResolver;
    }
}

5.2.3 单文件上传

  • 需求:选择一张图片上传到服务器,并保存到指定位置
  • 编写处理类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: 小新
 * @Date: 2021-12-10 19:54
 */
@Controller
@RequestMapping("/demo05")
public class Demo05UploadController {

    /**
     * 单文件上传
     * @param image
     * @return
     * @throws IOException
     */
    @RequestMapping("/upload")
    public String upload(MultipartFile image) throws IOException {
        System.out.println("上传文件名:" + image.getOriginalFilename());
        System.out.println("上传文件流:" + image.getInputStream());

        File file = new File("D:\\image", image.getOriginalFilename());
        FileUtils.copyInputStreamToFile(image.getInputStream(), file);
        return "file";
    }
}
  • 访问路径 + 表单:
<!--单文件上传-->
<form action="${pageContext.request.contextPath}/demo05/upload.action" method="post" enctype="multipart/form-data">
    选择文件: <input type="file" name="image" /> <br/>
    <input type="submit" value="单文件上传"/> <br/>
</form>

5.2.4 多文件上传

  • 需求:选择三张图片上传到服务器,并保存到指定位置
  • 编写处理类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: 小新
 * @Date: 2021-12-10 19:54
 */
@Controller
@RequestMapping("/demo05")
public class Demo05UploadController {
    /**
     * 多文件上传
     * @param images
     * @return
     * @throws IOException
     */
    @RequestMapping("/upload2")
    public String upload2(List<MultipartFile> images) throws IOException {
        for (MultipartFile image : images) {
            System.out.println("上传文件名:" + image.getOriginalFilename());
            System.out.println("上传文件流:" + image.getInputStream());

            File file = new File("D:\\image", image.getOriginalFilename());
            FileUtils.copyInputStreamToFile(image.getInputStream(), file);
        }
        return "file";
    }
}
  • 访问路径 + 表单:
<form action="${pageContext.request.contextPath}/demo05/upload2.action" method="post" enctype="multipart/form-data">
    选择文件: <input type="file" name="images" /> <br/>
    选择文件: <input type="file" name="images" /> <br/>
    选择文件: <input type="file" name="images" /> <br/>
    <input type="submit" value="多文件上传"/> <br/>
</form>

六、JSON数据交换

6.1 json数据格式

6.1.1 什么是JSON数据?

  • 是一种轻量级的数据交换格式。
  • 轻量级,不依赖任何框架、任何语言。

6.1.2 数据分类:对象、数组

  • 对象:
    • key必须使用双引号。
    • value除特殊类型外,都需要使用双引号(特殊类型:数字、布尔true/false)
    • 实例:
{
    "k":"v",
    "k2":"v2",....
}
  • 数组:
[
	元素,元素2,....
]

6.2 JSON使用流程

初始 Spring MVC【中】

6.3 入门案例

6.3.1 目标

  • 目标:请求JSON数据,响应JSON数据。
  • 需求:用户条件查询。
  • 请求:查询条件User 。
  • 响应:查询结果List

6.3.2 实现

  • 前提:spring mvc 底层jackson 出来JSON数据。
<!-- mvc json -->
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.10.2</version>
</dependency>
  • 编写JavaBean User类
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,接收请求数据 @RequestBody
@Controller
@RequestMapping("/demo06")
public class Demo06JsonController {

    @RequestMapping("/list")
    public void list(@RequestBody User user) {
        System.out.println(user);
    }
}
  • 编写controller,响应数据 @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: 小新
 * @Date: 2021-12-10 20:14
 */
@Controller
@RequestMapping("/demo06")
public class Demo06JsonController {

    /**
     * 请求JSON数据,响应JSON数据
     * @param user
     * @return
     */
    @RequestMapping(/*value = "/list" , method = RequestMethod.POST*/"/list")
    @ResponseBody
    public List<User> list(@RequestBody User user){
        System.out.println(user);
        //响应数据
        ArrayList<User> list = new ArrayList<>();
        list.add(new User(1,"小瓶子","54250",new Date()));
        list.add(new User(2,"胖胖","6666"));
        list.add(new User(3,"小新","牛掰"));

        return list;
    }
}
  • post Man 测试
    初始 Spring MVC【中】

6.4 常见注解

注解 描述
@RequestBody 请求数据为JSON字符串
@ResponseBody 响应数据为JSON字符串
@@JsonIgnore 忽略指定属性
@JsonFormat JSON数据日期的格式化
  • @JsonIgnore 作用是json序列化时将java bean中的一些属性忽略掉
public class User {
    @JsonIgnore
    private List<String> hobby;
}
  • @JsonFormat 格式化日期
public class User {
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Date birthday;
}

七、RESTFul

7.1 什么是RESTFul

  • RESTFul编写程序是一种风格,不是协议
  • 对http协议诠释(落地方案),请求方式的落地
    http协议共7中,常见四种,最常使用2种
    get、post、put、delete
    
  • RESTFul对服务器程序操作进行约定:
    • 每一个操作组成:请求路径 + 请求方式。(同一个路径因为请求方式不同,可以完成不同操作) 。

7.2 数据传输方式:JSON数据

  • RESTFul 风格路径:
查询:get    http://localhost:8080/user/
详情:get    http://localhost:8080/user/123
添加:post   http://localhost:8080/user/
修改:put    http://localhost:8080/user/
删除:delete http://localhost:8080/user/123

7.3 注解

7.3.1 类级别

  • @RestController :合成注入(@Controller 、@ResponseBody)

7.3.2 方法级别

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping

7.3.3 参数

  • @PathVariable :用于获取路径参数

7.4 方法返回值

//根据约束,基于RESTFul风格,方法的的返回值,建议使用 ResponseEntity 类型
// ResponseEntity 用于封装返回值信息,含状态码
// 返回200状态码,ResponseEntity.ok("添加成功");
// 其他状态码,new ResponseEntity<>("添加成功", HttpStatus.UNAUTHORIZED)

7.5 入门案例(增删改查)

7.5.1 实现

  • 配置类 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: 小新
 * @Date: 2021-12-07 16:49
 */
public class WebInitializer  implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        //1 配置spring工厂
        AnnotationConfigWebApplicationContext application = new AnnotationConfigWebApplicationContext();
        // 注册所有的配置类
        application.register(MvcConfiguration.class);

        //2 post中文乱码
        FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encoding", new CharacterEncodingFilter("UTF-8"));
        encodingFilter.addMappingForUrlPatterns(null, true, "/*");

        //3 核心控制器
        ServletRegistration.Dynamic mvcServlet = servletContext.addServlet("springmvc", new DispatcherServlet(application));
        //mvcServlet.addMapping("*.action");
        mvcServlet.addMapping("/");
        mvcServlet.setLoadOnStartup(2);	//tomcat启动时,执行servlet的初始化方法
    }
}
  • 配置类 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: 小新
 * @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: 小新
 * @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: 小新
 * @Date: 2021-12-13 20:02
 */
@RestController
@RequestMapping("/user")
public class Demo01Controller {

    /**
     * 查询所有
     * 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;
    }

    /**
     * 根据id查询详情
     * @param uid
     * @return
     */
    @GetMapping("/{id}")
    public String selectAll(@PathVariable("id") String uid){
        System.out.println("selectById" + uid);
        return "selectById success";
    }


    /**
     * 添加
     * post
     * @param user
     * @return
     */
    @PostMapping
    public User insert(@RequestBody  User user){
        System.out.println("添加成功:" + user);
        return user;
    }


    /**
     * 更新
     * put
     * @param user
     * @return
     */
    @PutMapping
    public User update(@RequestBody  User user){
        System.out.println("更新成功" + user);
        return user;
    }

    /**
     * 删除
     * delete
     * @param uid
     * @return
     */
    @DeleteMapping("/{id}")
    public String delete(@PathVariable("id") String uid){
        System.out.println("delete" + uid);
        return "delete success";
    }
}
上一篇:Redis之List类型


下一篇:Spring MVC+Spring+MyBatis 部分有价值的经验心得分享 逐渐更新