SpringMvc文件上传和Json处理

半世苍凉 提交于 2019-12-03 00:52:35

SpringMvc文件上传

首先添加pom依赖

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

然后在spring-servlet.xml中配置视图解析

<!--图片上传-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 文件最大大小(字节) 1024*1024*50=50M-->
        <property name="maxUploadSize" value="52428800"></property>
        <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
        <property name="resolveLazily" value="true"/>
    </bean>

upload.jsp

<body>
    <form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
        上传图片:<input type="file" name="img" />
        <input type="submit" value="上传" />
    </form>
</body>

Controller方法

    public String upload(MultipartFile img){
        try {
            FileUtils.copyInputStreamToFile(img.getInputStream(),new File("D:\\img\\"+img.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "forward:hello3";
    }

Json处理
在以前,我们需要把后台数据转为Json格式时一般都是用的Jackson和fastjson两个里面提供的工具类来转格式的,现在有了SpringMVC,我们可以通过注解的方式就能实现格式转换(@ResponseBody)

Demo
Controller

    @ResponseBody
    @RequestMapping("/jsonData1")
    private List<Map> jsonData1(){
        return bookService.listPager(new Book(),new PageBean());
    }


    @ResponseBody
    @RequestMapping("/jsonData2")
    private Map jsonData2(){
        return bookService.listPager(new Book(),new PageBean()).get(0);
    }

效果如下图:
在这里插入图片描述

Json处理

然后现在一般的前端有它固定的访问格式,所以我们一般需要用map来一个一个键值转化,所以就会有大量重复代码,所以一般我们可以自己封装一个转化工具类,来减少重复代码
比如
JSONResult.java

package com.liuting.util;

public class JSONResult {

    // 响应业务状态
    private Integer status;

    // 响应消息
    private String msg;

    // 响应中的数据
    private Object data;
    
    private String ok;	// 不使用

    public static JSONResult build(Integer status, String msg, Object data) {
        return new JSONResult(status, msg, data);
    }

    public static JSONResult ok(Object data) {
        return new JSONResult(data);
    }

    public static JSONResult ok() {
        return new JSONResult(null);
    }
    
    public static JSONResult errorMsg(String msg) {
        return new JSONResult(500, msg, null);
    }
    
    public static JSONResult errorMap(Object data) {
        return new JSONResult(501, "error", data);
    }
    
    public static JSONResult errorTokenMsg(String msg) {
        return new JSONResult(502, msg, null);
    }
    
    public static JSONResult errorException(String msg) {
        return new JSONResult(555, msg, null);
    }

    public JSONResult() {

    }

    public JSONResult(Integer status, String msg, Object data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public JSONResult(Object data) {
        this.status = 200;
        this.msg = "OK";
        this.data = data;
    }

    public Boolean isOK() {
        return this.status == 200;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

	public String getOk() {
		return ok;
	}

	public void setOk(String ok) {
		this.ok = ok;
	}

}

测试:

 @ResponseBody
    @RequestMapping("/jsonData3")
    private JSONResult jsonData3(){
        return JSONResult.ok("数据格式正确返回");
    }


    @ResponseBody
    @RequestMapping("/jsonData4")
    private JSONResult jsonData4(){
        return JSONResult.errorMsg("数据格式错误返回");
    }

效果如下图:
在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!