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