Java的一些高大上的方法

如果我们要保存图片,那么一定要有一个通用的方法。
下面是实体类的一个方法,方法名叫setPic

public void setPic(String pic) {
   	this.pic = pic == null ? null : pic.trim();
}

下面是一个请求上传图片保存的方法,图片有可能为空所以@RequestParam(required=false)

@RequestMapping(value="/listAjax/save",method=RequestMethod.POST)
public ResponseEntity<String> editSave(Model model,HttpServletRequest request,@Validated Ttemplate ttemplate,
		String birth,String pic,@RequestParam(required=false) MultipartFile uploadfiles) throws Exception{
if(uploadfiles!=null)
ttemplate=(Ttemplate)PicToString(ttemplate,"setPic", uploadfiles, request);
else ttemplate.setPic(pic);
……………………

那么实际上只需要复用从if然后到else这段三行代码,就可以达到设置图片路径的方式

我们需要在基础控制类baseController类里面,加上PicToString方法,obj是实体,str是设置图片src的方法,后面两个参数不用多说了。核心是java反射思想。

public Object PicToString(Object obj,String str,MultipartFile uploadfile,HttpServletRequest request) {
		if(uploadfile!=null){
			try {
				String filename = uploadfile.getOriginalFilename();  
				String suffix = filename.substring(filename.lastIndexOf(".")); 
				String newPath="";Uploader up = new Uploader(request);
				String folder =  up.getFolder("upload");
				if ((".gif.png.jpg.jpeg.bmp".indexOf(suffix.toLowerCase()) >=0)) {  
					newPath=folder+"/"+FileUtil.newFileName(uploadfile.getOriginalFilename());
				}else{
					newPath=folder+"/"+FileUtil.newFileName(uploadfile.getOriginalFilename());
				}File file=new File(request.getServletContext().getRealPath("/")+newPath);
				if(!file.exists()){
					file.createNewFile();
				}
				uploadfile.transferTo(file);
				obj.getClass().getMethod(str, new Class[]{String.class}).invoke(obj,new Object[]{newPath});
				return obj;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return obj;
	}

然后我们需要把list转成json格式,才能配合ajax实现无刷新的需求
list是通过查询得到的,s代表日期格式化的参数,比如yyyy-MM-dd HH:mm:ss

public JSONArray JsonToText(@SuppressWarnings("rawtypes") List list,final String s) {
	JsonConfig config = new JsonConfig();
	config.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {
	private SimpleDateFormat sd = new SimpleDateFormat(s);
		@Override
		public Object processArrayValue(Object arg0, JsonConfig arg1) {
		return arg0 == null ? "" : sd.format(arg0);
		}
		@Override
		public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {
		return arg1 == null ? "" : sd.format(arg1);
		}
	});
	return JSONArray.fromObject(list,config);
}

我们调用的时候只需要类似这样的代码:return list.isEmpty()?"[]":JsonToText(list,“yyyy-MM-dd”).toString()

猜你喜欢

转载自blog.csdn.net/qq_33359662/article/details/88361783