Java的一些高大上的方法

本文介绍了一种通用的图片上传和处理方法,利用Java反射思想实现图片路径设置,并展示了如何将查询结果转换为JSON格式,以支持AJAX无刷新需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果我们要保存图片,那么一定要有一个通用的方法。
下面是实体类的一个方法,方法名叫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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值