Springboot集成minio做文件存储

准备

1.已经搭建好的minio环境

1
2
3
4
5
# minio 参数配置
minio.endpoint = http://192.168.0.18:8091
minio.accessKey: root
minio.secretKey: 1qaz2wsx
minio.bucketName: minitest

2.java 环境,springboot项目,maven项目

搭建

1.pom.xml文件引入minio 的包

1
2
3
4
5
6
<!-- 非结构化存储数据minio -->
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.0.3</version>
</dependency>

2.application.properties进行配置,

1
2
3
4
5
# minio 参数配置
minio.endpoint = http://192.168.0.18:8091
minio.accessKey: root
minio.secretKey: 1qaz2wsx
minio.bucketName: minitest

3.配置文件MinIoClientConfig.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.wangjikai.minitest.config;

import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
* @ClassName MinIoClientConfig
* @Author wjk
* @Date 2021/09/20 10:48
* @Version 1.0
**/
@Configuration
public class MinIoClientConfig {


@Value("${minio.endpoint}")
private String endpoint;
@Value("${minio.accessKey}")
private String accessKey;
@Value("${minio.secretKey}")
private String secretKey;

/**
* 注入minio 客户端
* @return
*/
@Bean
public MinioClient minioClient(){

return MinioClient.builder()
.endpoint(endpoint)
.credentials(accessKey, secretKey)
.build();
}
}

4.操作文件:

MinIoService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package com.wangjikai.minitest.platform.minioClient;

import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
* @ClassName MinIoService
* @Deacription TODO
* @Author wjk
* @Date 2021-09-20
* @Version 1.0
**/
@Service
public class MinIoService {

@Resource
private MinioClient instance;

@Value("${minio.endpoint}")
private String endpoint;

@Value("${minio.bucketName}")
private String adataBucketName;

private static final String SEPARATOR_DOT = ".";

private static final String SEPARATOR_ACROSS = "-";

private static final String SEPARATOR_STR = "";

/**
* @Description 判断 bucket是否存在
*
* @author wjk
* @date 2021-09-20 16:33
* @param bucketName
* @return boolean
*/
public boolean bucketExists(String bucketName){
try {
return instance.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
} catch (Exception e) {
e.printStackTrace();
}
return false;
}

/**
* 创建 bucket
* @param bucketName
*/
public void makeBucket(String bucketName){
try {
boolean isExist = instance.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
if(!isExist) {
instance.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
}
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* @Description 删除桶
*
* @author wjk
* @date 2021-09-20 16:46
* @param bucketName
* @return boolean
*/
public boolean removeBucket(String bucketName) throws InvalidKeyException, ErrorResponseException,
IllegalArgumentException, InsufficientDataException, InternalException,
InvalidResponseException, NoSuchAlgorithmException, XmlParserException, IOException, ServerException {
boolean flag = bucketExists(bucketName);
if (flag) {
Iterable<Result<Item>> myObjects = listObjects(bucketName);
for (Result<Item> result : myObjects) {
Item item = result.get();
// 有对象文件,则删除失败
if (item.size() > 0) {
return false;
}
}
// 删除存储桶,注意,只有存储桶为空时才能删除成功。
instance.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
flag = bucketExists(bucketName);
if (!flag) {
return true;
}
}
return false;
}

/**
* @Description 获取文件存储服务的所有存储桶名称
*
* @author wjk
* @date 2021-09-20 16:35
* @param
* @return java.util.List<java.lang.String>
*/
public List<String> listBucketNames() throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InsufficientDataException, InternalException {
List<Bucket> bucketList = listBuckets();
List<String> bucketListName = new ArrayList<>();
for (Bucket bucket : bucketList) {
bucketListName.add(bucket.name());
}
return bucketListName;
}

/**
* @Description 列出所有存储桶
*
* @author wjk
* @date 2021-09-20 16:35
* @param
* @return java.util.List<io.minio.messages.Bucket>
*/
public List<Bucket> listBuckets() throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
return instance.listBuckets();
}

/**
* @Description 列出存储桶中的所有对象名称
*
* @author wjk
* @date 2021-09-20 16:39
* @param bucketName
* @return java.util.List<java.lang.String>
*/
public List<String> listObjectNames(String bucketName) throws InvalidKeyException, ErrorResponseException,
IllegalArgumentException, InsufficientDataException, InternalException,
InvalidResponseException, NoSuchAlgorithmException, XmlParserException, IOException, ServerException {
List<String> listObjectNames = new ArrayList<>();
boolean flag = bucketExists(bucketName);
if (flag) {
Iterable<Result<Item>> myObjects = listObjects(bucketName);
for (Result<Item> result : myObjects) {
Item item = result.get();
listObjectNames.add(item.objectName());
}
}
return listObjectNames;
}

/**
* @Description 列出存储桶中的所有对象
*
* @author wjk
* @date 2021-09-20 16:39
* @param bucketName
* @return java.lang.Iterable<io.minio.Result<io.minio.messages.Item>>
*/
public Iterable<Result<Item>> listObjects(String bucketName) throws InvalidKeyException, ErrorResponseException,
IllegalArgumentException {
boolean flag = bucketExists(bucketName);
if (flag) {
return instance.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
}
return null;
}



/**
* @Description 通过文件地址,保留原始文件名 文件上传
*
* @author wjk
* @date 2021-09-20 15:16
* @param bucketName
* @param objectName
* @param stream
* @return java.lang.String
*/
public MinIoUploadVo upload(String bucketName, String objectName, InputStream stream) throws Exception {
if(!this.bucketExists(bucketName)){
this.makeBucket(bucketName);
}
instance.putObject(
PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
stream, stream.available(), -1) // PutObjectOptions,上传配置(文件大小,内存中文件分片大小)
.build());
String url =instance.getPresignedObjectUrl(
GetPresignedObjectUrlArgs.builder()
.method(Method.GET)
.bucket(bucketName)
.object(objectName)
.expiry(60 * 60 * 24)
.build());
// 返回生成文件名、访问路径
return new MinIoUploadVo(bucketName,objectName,"",url);
}

/**
* @Description 文件上传 (自定义文件名称)
*
* @author wjk
* @date 2021-09-20 13:45
* @param multipartFile
* @return java.lang.String
*/
public MinIoUploadVo upload(String strDir, MultipartFile multipartFile) throws Exception {

// bucket 不存在,创建
if (!this.bucketExists(adataBucketName)) {
this.makeBucket(adataBucketName);
}
InputStream inputStream = multipartFile.getInputStream();
// 创建一个 headers
Map<String, String> headers = new HashMap<>();
// 添加请求头 文件的ContentType 动态配置 multipartFile.getContentType()
headers.put("Content-Type", "application/octet-stream");

String fileName=multipartFile.getOriginalFilename();

String minFileName = minFileName(fileName);
instance.putObject(
PutObjectArgs.builder().bucket(adataBucketName).object(minFileName).stream(
inputStream, inputStream.available(), -1) // PutObjectOptions,上传配置(文件大小,内存中文件分片大小)
.headers(headers)
.build());
/*String url =instance.getPresignedObjectUrl(
GetPresignedObjectUrlArgs.builder()
.method(Method.GET)
.bucket(bucketName)
.object(strDir.concat("/").concat(minFileName))
.build());*/
String url =endpoint.concat("/").concat("adata/").concat("/").concat(minFileName);
// 返回生成文件名、访问路径
return new MinIoUploadVo(adataBucketName,fileName,minFileName,url);
}

/**
* @Description 下载文件
*
* @author wjk
* @date 2021-09-20 15:18
* @param response
* @return java.lang.String
*/
public void download(HttpServletResponse response, String bucketName,String minFileName ) throws Exception {

//InputStream fileInputStream = instance.getObject(GetObjectArgs.builder().bucket("adata").object(bucketName.concat("/").concat(minFileName)).build());
InputStream fileInputStream = instance.getObject(
GetObjectArgs.builder().bucket(bucketName).object(minFileName).build());

response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode("一些文件分享.txt", "UTF-8"));
response.setContentType("application/force-download");
response.setCharacterEncoding("UTF-8");
IOUtils.copy(fileInputStream,response.getOutputStream());
}

/**
* 删除一个文件
* @author wjk
* @date 2021-09-20 16:43
* @param bucketName
* @param objectName
* @return
*/
public boolean removeObject(String bucketName, String objectName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
boolean flag = bucketExists(bucketName);
if (flag) {
instance.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
return true;
}
return false;
}

/**
* @Description 删除指定桶的多个文件对象,返回删除错误的对象列表,全部删除成功,返回空列
* @author wjk
* @date 2021-09-20 16:43
* @param bucketName
* @param objects
* @return java.util.List<java.lang.String>
*/
public List<String> removeObject(String bucketName, List<DeleteObject> objects) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
List<String> deleteErrorNames = new ArrayList<>();
boolean flag = bucketExists(bucketName);
if (flag) {
Iterable<Result<DeleteError>> results = instance.removeObjects(
RemoveObjectsArgs.builder().bucket(bucketName).objects(objects).build());
for (Result<DeleteError> result : results) {
DeleteError error = result.get();
deleteErrorNames.add(error.objectName());
}
}
return deleteErrorNames;
}



/**
* @Description 生成上传文件名
*
* @author wjk
* @date 2021-09-20 15:07
* @param originalFileName
* @return java.lang.String
*/
private String minFileName(String originalFileName) {
String suffix = originalFileName;
if(originalFileName.contains(SEPARATOR_DOT)){
suffix = originalFileName.substring(originalFileName.lastIndexOf(SEPARATOR_DOT));
}
return UUID.randomUUID().toString().replace(SEPARATOR_ACROSS,SEPARATOR_STR).toUpperCase()+suffix;
}
}

ObjectStorageController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package com.wangjikai.minitest.platform.minioClient;


import com.wangjikai.minitest.commonbase.BaseController;
import com.wangjikai.minitest.platform.goodsacceptancerecord.GoodsAcceptanceRecord;
import com.wangjikai.minitest.util.ReturnDataJson;
import io.minio.messages.DeleteObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* @ClassName UploadController
* @Deacription 基于文件对象存储方案
* @Author wjk
* @Date 2021-09-20
* @Version 1.0
**/
@CrossOrigin
@RestController

@RequestMapping("/storage")
@Api("基于文件对象存储方案")
public class ObjectStorageController extends BaseController {


@Autowired
private MinIoService minIoService;

@Value("${minio.bucketName}")
private String bucketName;


@ApiOperation(value = "文件上传公共组件", notes = "基于所有类型文件上传公共组件")
@RequestMapping(value = "/upload" , method = RequestMethod.POST)
@ResponseBody
public FileResults upload(MultipartFile file) throws IOException {
String objectName=file.getOriginalFilename();
InputStream inputStream = file.getInputStream();
// String strDir= request.getParameter("bucketName")==null?"test":request.getParameter("bucketName");

try {
MinIoUploadVo uploadVo = minIoService.upload(null,file);
return new FileResults(true,200,"文件上传成功",uploadVo);
} catch (Exception e) {
//log.error("上传文件失败,msg={}",e.getMessage());
e.printStackTrace();
return new FileResults(false,500,"网络异常",null);
}
}

@ApiOperation(value = "文件下载公共组件", notes = "基于所有类型文件下载公共组件")
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void download(MinIoUploadVo minIoUploadVo) {

try {
minIoService.download(response, minIoUploadVo.getBucketName(), minIoUploadVo.getMinFileName());
} catch (Exception e) {
//log.error("下载文件失败,msg={}",e.getMessage());
e.printStackTrace();
}
}

@ApiOperation(value = "文件服务器文件删除(支持多个)", notes = "文件服务器删除公共组件")
@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
public FileResults delete(MinIoUploadVo minIoUploadVo) {

try {
List<DeleteObject> objectList= new ArrayList<>();

String fileDir = minIoUploadVo.getBucketName().concat("/");
Arrays.stream(minIoUploadVo.getMinFileName().split(",")).forEach(name -> objectList.add(new DeleteObject(fileDir.concat(name))));

minIoService.removeObject(bucketName, objectList);

return new FileResults(true,200,"删除文件成功",null);
} catch (Exception e) {
//log.error("删除文件失败,msg={}",e.getMessage());
e.printStackTrace();
return new FileResults(true,500,"网络异常",null);
}
}

/**
* 查询(获取全部Bucket)
*/
@RequestMapping(value = "/getAllBucket",method=RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "查询(获取全部)")
public ReturnDataJson getallBucket() {
ReturnDataJson res;
try {
List<String> list = this.minIoService.listBucketNames();
res = this.responseReturnDataJson(true,"成功",list,Long.valueOf(list.size()));
} catch (Exception e) {
logger.error(e.getMessage(), e);
res = this.responseReturnDataJson(false,"失败");
}
return res;
}

/**
* 查询(获取全部文件)
*/
@RequestMapping(value = "/getallFile",method=RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "查询(获取全部)")
public ReturnDataJson getallFile() {
ReturnDataJson res;
try {
List<String> list = this.minIoService.listObjectNames(bucketName);
res = this.responseReturnDataJson(true,"成功",list,Long.valueOf(list.size()));
} catch (Exception e) {
logger.error(e.getMessage(), e);
res = this.responseReturnDataJson(false,"失败");
}
return res;
}


}

5.相应的实体类:
FileResults.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.wangjikai.minitest.platform.minioClient;



/**
* @ClassName FileResults
* @Deacription TODO
* @Author wjk
* @Date 2021-09-20
* @Version 1.0
**/

public class FileResults {


private boolean success;//是否成功
private Integer code;// 返回码
private String message;//返回信息
private Object data;// 返回数据

public boolean isSuccess() {
return success;
}

public void setSuccess(boolean success) {
this.success = success;
}

public Integer getCode() {
return code;
}

public void setCode(Integer code) {
this.code = code;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public Object getData() {
return data;
}

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

public FileResults(boolean success, Integer code, String message, Object data) {
this.success = success;
this.code = code;
this.message = message;
this.data = data;
}
}

MinIoUploadVo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.wangjikai.minitest.platform.minioClient;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;


import java.io.Serializable;

/**
* @ClassName MinIoUploadVo
* @Deacription
* @Author wjk
* @Date 2021-09-20
* @Version 1.0
**/

@ApiModel(value = "Minio 上传文件对象",description = "上传文件对象")
public class MinIoUploadVo implements Serializable {
private static final long serialVersionUID = 475040120689218785L;
@ApiModelProperty("对象桶名")
private String bucketName;

@ApiModelProperty("文件真实名称")
private String fileRealName;

@ApiModelProperty("文件名称")
private String minFileName;

@ApiModelProperty("文件路径")
private String minFileUrl;

public static long getSerialVersionUID() {
return serialVersionUID;
}

public String getBucketName() {
return bucketName;
}

public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}

public String getFileRealName() {
return fileRealName;
}

public void setFileRealName(String fileRealName) {
this.fileRealName = fileRealName;
}

public String getMinFileName() {
return minFileName;
}

public void setMinFileName(String minFileName) {
this.minFileName = minFileName;
}

public String getMinFileUrl() {
return minFileUrl;
}

public void setMinFileUrl(String minFileUrl) {
this.minFileUrl = minFileUrl;
}

public MinIoUploadVo(String bucketName, String fileRealName, String minFileName, String minFileUrl) {
this.bucketName = bucketName;
this.fileRealName = fileRealName;
this.minFileName = minFileName;
this.minFileUrl = minFileUrl;
}
}

6.补充
BaseController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package com.wangjikai.minitest.commonbase;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wangjikai.minitest.util.CommResultMsg;
import com.wangjikai.minitest.util.PagesBean4DataTables;
import com.wangjikai.minitest.util.PagingBean;
import com.wangjikai.minitest.util.ReturnDataJson;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.IOUtils;

public abstract class BaseController {
/**
* 日志
*/
protected Logger logger = LoggerFactory.getLogger(getClass());
protected HttpServletRequest request;
protected HttpServletResponse response;
protected HttpSession session;
public String httpBodyJson = null;

public PagesBean4DataTables getjqPages(PagingBean pagingBean, List<?> list) {
PagesBean4DataTables p = new PagesBean4DataTables();
String drawString = this.request.getParameter("draw");
Integer draw = Integer.valueOf(StringUtils.defaultString(drawString, "0"));
Integer total = pagingBean.getTotalItems();
p.setData(list);
p.setDraw(draw);
p.setRecordsTotal(total);
p.setRecordsFiltered(total);
return p;
}

@ModelAttribute
public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
this.request = request;
this.response = response;
this.session = request.getSession();
try {
InputStream inputStream = request.getInputStream();
List<String> data = IOUtils.readLines(inputStream,"UTF-8");
StringBuffer buffer = new StringBuffer();
if (CollectionUtils.isNotEmpty(data)) {
for (String item : data) {
buffer.append(item);
}
httpBodyJson= buffer.toString();
}
} catch (IOException e) {
logger.error(e.getMessage(),e);
}
}

@InitBinder
public void initBinder(WebDataBinder binder) throws Exception{
String[] parsePatterns = new String[]{"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm"};
// Date 格式化
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
try {
setValue(DateUtils.parseDate(text,parsePatterns));
} catch (ParseException e) {
e.printStackTrace();
}
}
});
}

/**
* 返回json格式数据<br>
* contentType为application/json
*
* @param jsonString
*/
public void responseWriter(String jsonString) {
writeData(jsonString, "application/json");
}
/**
* 返回json格式数据<br>
* contentType为application/json
*
*/
public void responseWriter(Boolean result, String msg) {
writeData(getCommonJsonString(result,msg), "application/json");
}
/**
* 返回json格式数据<br>
* contentType为application/json
*
*/
public <T> void responseWriter(Boolean result, String msg, T t) {
writeData(getCommonJsonString(result,msg,t), "application/json");
}
/**
* 消息结果通用方法
*
* @param result 操作成功与否 标志位
* @param msg 额外描述系信息
* @return
*/
public String getCommonJsonString(Boolean result, String msg) {
CommResultMsg comm = new CommResultMsg();
comm.setResult(result);
comm.setDescription(msg);
return JSON.toJSONString(comm);
}

/**
* 消息结果通用方法
*
* @param result 操作成功与否 标志位
* @param msg 额外描述系信息
* @return
*/
public <T> String getCommonJsonString(Boolean result, String msg, T t) {
CommResultMsg<T> comm = new CommResultMsg<T>();
comm.setResult(result);
comm.setDescription(msg);
comm.setObj(t);
return JSON.toJSONString(comm);
}
/**
* 返回json格式数据<br>
* contentType为text/json
* @param jsonString
*/
public void writeTextJson(String jsonString) {
writeData(jsonString, "text/json");
}

/**
* 通过response返回字数据
* @param jsonString
* @param contentType
*/
public void writeData(String jsonString, String contentType) {
response.setContentType(contentType);
PrintWriter out = null;
try {
out = this.response.getWriter();
out.write(jsonString);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
out.flush();
out.close();
}
}

/**
* 成功
* 返回值带总数
*
*/
public ReturnDataJson responseReturnDataJson(Boolean status, String message, Object result,Long total) {
String statusCode = status == true ? ReturnDataJson.SUCCESS_CODE:ReturnDataJson.ERROR_CODE ;
ReturnDataJson returnDataJson = new ReturnDataJson(statusCode, message, result,total);
return returnDataJson;
}
/**
*
* 成功
* 返回值
*
*/
public ReturnDataJson responseReturnDataJson(Boolean status, String message, Object result) {
String statusCode = status == true ? ReturnDataJson.SUCCESS_CODE:ReturnDataJson.ERROR_CODE ;
ReturnDataJson returnDataJson = new ReturnDataJson(statusCode, message, result);
return returnDataJson;
}
/**
* 失败
* 返回值带总数
*
*/
public ReturnDataJson responseReturnDataJson(Boolean status,String message) {
String statusCode = status == true ? ReturnDataJson.SUCCESS_CODE:ReturnDataJson.ERROR_CODE ;
ReturnDataJson returnDataJson = new ReturnDataJson(statusCode, message);
return returnDataJson;
}
}
继开 wechat
欢迎加我的微信,共同交流技术