关于springboot+mybatis的万能参数查询接口和阿里云OSS使用

在作分销商城项目时我发现一个接口任何参数都可以传入,并实现分页查询,我很感兴趣并在此记录
二话不多说上代码,干饭!
Controller接口:


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.hgj.common.web.RequestUtil;
import com.hgj.web.entity.SsProduct;

@Controller
@RequestMapping(value = "/base")
public class BaseController {

	@Autowired
	SqlSessionTemplate sqlSessionTemplate;

	@RequestMapping(method = {RequestMethod.GET,RequestMethod.POST}, value = { "/jsp/{jspName}" })
	public String toJsp(@PathVariable("jspName") String jspName) {
		return jspName;
	}


	/**
	 *      动态查询接口
	 * @param request
	 * @param statement
	 * @return
	 */
	@RequestMapping(method = {RequestMethod.GET,RequestMethod.POST}, value = { "/quickQuery/{statement}" })
	@ResponseBody
	public Object quickQuery(HttpServletRequest request,
			@PathVariable("statement") String statement ) {

		List resultList=sqlSessionTemplate.selectList(statement, RequestUtil.parse(request));
		String currentPage = request.getParameter("currentPage");
		String pageSize = request.getParameter("pageSize");
		if(StringUtils.isNumeric(currentPage)&&StringUtils.isNumeric(pageSize)) {
			return new PageInfo(resultList);
		}else {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("resultList", resultList);
			return map;
		}

	}


}

这里的SqlSessionTemplate 是mybaits提供的一个sql查询模板

这里需要一个工具类:

package com.hgj.common.web;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;

import com.hgj.common.util.ObjectUtil;



public class RequestUtil {

	private static Logger logger = LoggerFactory.getLogger(RequestUtil.class);

	public static class Parameters {
		private Map<String, String> textMap = new HashMap<String, String>();;
		private Map<String, List<FileItem>> fileItemMap = new HashMap<String, List<FileItem>>();

		public void addText(String key, String value) {
			textMap.put(key, value);
		}

		public void addFileItem(String key, FileItem fileItem) {
			List<FileItem> fileItemList = fileItemMap.get(key);
			if (fileItemList == null) {
				fileItemList = new ArrayList<FileItem>();
				fileItemMap.put(key, fileItemList);
			}
			fileItemList.add(fileItem);
		}

		public String getText(String key) {
			return textMap.get(key);
		}

		public Map<String, String> getTextMap() {
			return textMap;
		}

		public Map<String, List<FileItem>> getFileItemMap() {
			return fileItemMap;
		}

	}

	public static Parameters parseOfMultipart(HttpServletRequest request) {
		Parameters parameters = new Parameters();
		try {
			request.setCharacterEncoding("UTF-8");
			List<FileItem> fileItems = new ServletFileUpload(
					new DiskFileItemFactory()).parseRequest(request);
			for (FileItem fileItem : fileItems) {
				if (fileItem.isFormField()) {
					parameters.addText(fileItem.getFieldName(),
							fileItem.getString("UTF-8"));
					logger.debug("字段:key=" + fileItem.getFieldName()
							+ ",value=" + fileItem.getString("UTF-8"));
				} else {
					logger.debug("文件:fileName=" + fileItem.getFieldName()
							+ ",size=" + fileItem.getSize());
					if (fileItem.getSize() != 0) {
						parameters.addFileItem(fileItem.getFieldName(),
								fileItem);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return parameters;
	}

	public static void fillParameters(HttpServletRequest request, Object o) {
		if (MediaType.MULTIPART_FORM_DATA.equals(request.getContentType())) {
			Parameters parameters = parseOfMultipart(request);
			ObjectUtil.copyProperties(parameters.getTextMap(), o);
		} else {
			Map parameterMap = getParameterMap(request);
			o =parameterMap;
		}
	}

	public static Map<String, Object> parse(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (MediaType.MULTIPART_FORM_DATA.equals(request.getContentType())) {
			Parameters parameters = parseOfMultipart(request);
			ObjectUtil.copyProperties(parameters.getTextMap(), map);
		} else {
			Map parameterMap = getParameterMap(request);
			map =parameterMap;
		}
		for (Map.Entry<String, Object> entry : map.entrySet()) {

			if (entry.getValue() instanceof String
					&& StringUtils.isNumeric((String) entry.getValue())) {
				map.put(entry.getKey(), Long.valueOf((String) entry.getValue()));
			}

		}
		return map;
	}

	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	public static Map getParameterMap(HttpServletRequest request) {
		Map properties = request.getParameterMap();
		// 返回值Map
		Map returnMap = new HashMap();
		Iterator entries = properties.entrySet().iterator();
		Map.Entry entry;
		String name = "";
		String value = "";
		while (entries.hasNext()) {
			entry = (Map.Entry) entries.next();
			name = (String) entry.getKey();
			Object valueObj = entry.getValue();
			if(null == valueObj){
				value = "";
			}else if(valueObj instanceof String[]){
				String[] values = (String[])valueObj;
				for(int i=0;i<values.length;i++){
					value = values[i] + ",";
				}
				value = value.substring(0, value.length()-1);
			}else{
				value = valueObj.toString();
			}
			returnMap.put(name, value);
		}
		return returnMap;
	}
}

ObjectUtil工具类

package com.hgj.common.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.JsonParser;

public class ObjectUtil {

	private ObjectUtil() {
	}

	public static String toJson(Object o) {
		return new Gson().toJson(o);
	}

	public static <T> T fromJson(String json, Class<T> type) {
		return new Gson().fromJson(json, type);
	}

	public static EasyJsonObject toJsonObject(String json) {
		return new EasyJsonObject(new JsonParser().parse(json).getAsJsonObject());
	}

	public static void copyProperties(Object source, Object target) {
		if (source == null || target == null) {
			return;
		}
		try {
			StrongBeanUtils.copyProperties(source, target);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	// public static Map<String, Object> toMap(Object source) {
	// return new org.apache.commons.beanutils.BeanMap(source);
	// }

	public static Map<String, Object> toMap(Object bean) {
		try {
			Map<String, Object> returnMap = new HashMap<String, Object>();
			BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (int i = 0; i < propertyDescriptors.length; i++) {
				PropertyDescriptor descriptor = propertyDescriptors[i];
				String propertyName = descriptor.getName();
				if (!propertyName.equals("class")) {
					Method readMethod = descriptor.getReadMethod();
					Object result = readMethod.invoke(bean, new Object[0]);
					if (result != null) {
						returnMap.put(propertyName, result);
					} else {
						returnMap.put(propertyName, null);
					}
				}
			}
			return returnMap;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static void copyProperties(Map<String, Object> source, Object target) {
		try {
			StrongBeanUtils.populate(target, source);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static List<String> getConstant(Class constantClasss) {
		List<String> out = new ArrayList<String>();
		for (Field field : constantClasss.getDeclaredFields()) {
			try {
				out.add(field.get(constantClasss).toString());
			} catch (IllegalArgumentException e) {
				throw new RuntimeException(e);
			} catch (IllegalAccessException e) {
				throw new RuntimeException(e);
			}
		}
		return out;
	}

}

阿里OSS使用:

阿里OSS工具类

package com.hgj.web.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.hgj.web.support.ConstantProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * 阿里云OSS工具类
 */
public class AliyunOSSUtil {

    private static Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);

    static String endpoint = ConstantProperties.ENDPOINT;
    static String accessKeyId = ConstantProperties.ACCESS_KEY_ID;
    static String accessKeySecret = ConstantProperties.ACCESS_KEY_SECRET;
    static String bucketName = ConstantProperties.BUCKET_NAME;
    static String fileHost = ConstantProperties.FILE_HOST;

    //上传文件
    public static void upload(String fileName, InputStream inputStream) {
        logger.info("=========>OSS文件上传开始:".concat(fileName));
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 上传文件流。
        ossClient.putObject(bucketName, fileName, inputStream);
        logger.info("=========>OSS文件上传成功");
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    //获取上传文件路径
    public static String getFileUrl(String key){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        return url.toString();
    }
}

文件上传接口:

package com.hgj.web.admin.controller;

import com.hgj.web.config.AliyunOSSUtil;
import com.hgj.web.dto.FileUploadDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

/**
 * 上传图片模块
 * @author Administrator
 *
 */

@Controller
@ResponseBody
@RequestMapping("/pic/")
public class PictureController {

	@Value("${file.server.ip}")
	private String fileIp;

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

	/**
	 * 上传图片
	 * @param uploadFile
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value = "/upload")
	@ResponseBody
	public FileUploadDto pictureUpload(@RequestParam(value = "uploadFile", required = true) MultipartFile uploadFile) throws Exception{
		FileUploadDto  dto = new FileUploadDto();
		dto.setError(1);
		String originalFilename = uploadFile.getOriginalFilename();
		if(originalFilename.toUpperCase().endsWith(".JPG") || originalFilename.toUpperCase().endsWith(".JPEG")
				|| originalFilename.toUpperCase().endsWith(".PNG")){
			BufferedImage image = ImageIO.read(uploadFile.getInputStream());
			String fileName = "productImg/"+System.currentTimeMillis()+"".concat(originalFilename.substring(originalFilename.lastIndexOf(".")));
			AliyunOSSUtil.upload(fileName,uploadFile.getInputStream());
			String fileUrl = AliyunOSSUtil.getFileUrl(fileName);
			dto.setUrl(fileUrl);
			dto.setHeight(image.getHeight()+"");
			dto.setWidth(image.getWidth()+"");
		}else{
			dto.setError(0);
			dto.setMessage("只允许上传jpg,png,jpeg格式的图片!");
		}
		return dto;
	}



/*

*/
/*
	 * 删除图片
	 * @param imgDto
	 * @return
	 * @throws Exception

*//*

	@RequestMapping("/pic/deleteProductDetailFile")
	@ResponseBody
	public JSONObject deleteProductDetailFile(ImgDto imgDto) throws Exception{
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		String picName = GlobalProperties.getfileIp()+imgDto.getImgUrl();
		if(pictureService.deleteProductDetailFile(imgDto)==1){
			hashMap.put("data", "success");
		}else{
			hashMap.put("data", "fail");
		}
		String json = JSONUtils.entityToJson(hashMap);
		return JSONObject.parseObject(json);
	}

*/
/*
	 * 删除图片
	 * @param imgDto
	 * @return
	 * @throws Exception
	 *//*


	@RequestMapping("/pic/deleteProductGuidedGraph")
	@ResponseBody
	public JSONObject deleteProductGuidedGraph(ImgDto imgDto) throws Exception{
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		String picName = GlobalProperties.getfileIp()+imgDto.getImgUrl();
		if(pictureService.deleteProductGuidedGraph(imgDto)==1){
			hashMap.put("data", "success");
		}else{
			hashMap.put("data", "fail");
		}
		String json = JSONUtils.entityToJson(hashMap);
		return JSONObject.parseObject(json);
	}
*/

}

文件上传实体:

package com.hgj.web.dto;


import com.hgj.common.entity.BaseEntity;

public class FileUploadDto extends BaseEntity {


    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private Integer error;

    private String url;
    private String height;

    private String width;

    private String message;

    public Integer getError() {
        return error;
    }

    public void setError(Integer error) {
        this.error = error;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getHeight() {
        return height;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    public String getWidth() {
        return width;
    }

    public void setWidth(String width) {
        this.width = width;
    }

    public String getMessage() {
        return message;
    }

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

package com.hgj.web.support;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ConstantProperties implements InitializingBean {

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

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

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

    public static String ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;
    public static String ENDPOINT;
    public static String BUCKET_NAME;
    public static String FILE_HOST;

    @Override
    public void afterPropertiesSet() throws Exception {
        ACCESS_KEY_ID = accessKeyId;
        ACCESS_KEY_SECRET = accessKeySecret;
        ENDPOINT = endpoint;
        BUCKET_NAME = bucketName;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
# 需求分析 ## 1.前台 ### 1.1.首页 1.首页视频展示: ​ 按照时间降序显示 ​ 视频数据展示:视频链接、封面链接、视频标题、所属二级类别、点赞数、提交者的头像 2.搜索功能: ​ 根据视频名字或者用户名字模糊查询,将查询结果显示在首页 3.发布视频和图片功能: ​ 发布视频:选择视频,填写视频简介、标题和分类,发布 ​ 选择视频或图片提交。 ### 1.2.分类 1.根据分类查看视频(图片)功能: ​ 实现一级分类和二级分类的联动, 2.查看视频详情功能: ​ 进入二级分类的数据列表中,可以查看视频详情。同首页查看视频详情功能相同。 ### 1.3.动态 展示用户关注博主的动态:如发布的视频和图片。 ### 1.4.我的 1.用户编辑个人信息:点击头像进入编辑个人中心。 ​ 编辑资料: ​ 视频:发布的视频(右上角按钮可删除) ​ 分组:创建、删除、修改,查看用户的个人分组 ​ 图片:发布的图片(右上角按钮可删除) 2.历史: ​ 展示查看数据的列表 3.关注: ​ 我的关注:用户关注的博主列表; ​ 关注按钮,点击即可关注,再点击即可取消关注 ​ 关注的用户信息链接:粉丝数、发布的视频数、头像、分组信息 ​ 我的粉丝:关注用户的粉丝列表。 4.消息: ​ 评论信息、点赞信息 5.缓存 ​ 清空缓存 6.反馈: ​ 包括标题和内容,提交给后台管理系统 7.关于我们 8.语言环境-自动 9.隐私协议 10.学分计算 ​ 根据用户不同行为,增加学分 11.退出登录 ### 1.5.视频观看 简介: ​ 显示数据:发布者头像、昵称、发布时间、视频标题、简介、播放次数、点赞次数。 ​ 功能:点赞,不喜欢,收藏,分享,关注。 ​ 推荐视频列表。 评论: ​ 评论列表。 ​ 显示:评论的内容、时间,用户名,用户头像。 ​ 删除评论功能。 ​ 提交评论功能。 ## 2.后台管理系统 ### 2.1.视频or图片管理 ​ 审核数据。查看、删除功能。 ### 2.2.分组管理 ​ 管理数据的分组,实现分组的增删该查 ### 2.3.用户管理 ​ 修改用户状态 ### 2.4.反馈管理 ​ 查看、删除功能 ​
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

废弃的root

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值