场景:根据页面传入的字段,获取所对应的某个实体类的属性值
//利用反射获取
public String getByAttributeName(BcChannelInfo bcChannelInfo, String attributeName) {
for (Field field : bcChannelInfo.getClass().getDeclaredFields()) {
field.setAccessible(true);
try {
if (attributeName.toLowerCase().equals(field.getName().toLowerCase())) {
return new String(field.get(bcChannelInfo).toString());
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return null;
}
下面贴上完整代码
controller:
@RequestMapping("/getUpLoadFile")
public void getUpLoadFile(HttpServletRequest req, HttpServletResponse resp) {
OutputStream os = null;
FileInputStream in = null;
try {
String fileType = req.getParameter("fileType");
String channelId = req.getParameter("channelId");
//fileType:cardFrontPath、cardEndPath、bankCardPath
if (StringUtils.isEmpty(fileType)) {
return;
}
//获取已上传文件对应路径 获取对应的属性
String fileName = bcChannelInfoService.getUpLoadFile(fileType, channelId);
resp.setHeader("Pragma", "No-cache");
resp.setHeader("Cache-Control", "No-cache");
resp.setDateHeader("Expires", 0);
String format = fileName.substring(fileName.lastIndexOf(".") + 1);
resp.setHeader("Content-Type", format);
os = resp.getOutputStream();
in = new FileInputStream(fileName);
byte[] bytes = new byte[1024];
int len = -1;
while ((len = in.read(bytes)) > 0) {
os.write(bytes, 0, len);
os.flush();
}
} catch (
IOException e) {
log.error("图片信息读取异常:", e);
} finally {
try {
if (in != null) {
in.close();
}
if (os != null) {
os.close();
}
} catch (Exception e) {
log.error("关闭数据流异常:", e);
}
}
}
service:
/**
* 获取认证信息
*/
public String getUpLoadFile(String fileType, String channelId);
serviceimpl:
/**
* 获取上传的文件
*/
@Override
public String getUpLoadFile(String fileType, String channelId) {
QueryWrapper<BcChannelInfo> queryWrapper = new QueryWrapper<BcChannelInfo>();
//根据channelId查询渠道商信息
queryWrapper.eq("CHANNEL_ID", channelId);
BcChannelInfo bcChannelInfo = bcChannelInfoMapper.selectOne(queryWrapper);
String fileName = "";
if (bcChannelInfo != null && StringUtils.isNotEmpty(fileType)) {
fileName = getByAttributeName(bcChannelInfo, fileType);
if (log.isDebugEnabled()) {
log.debug("获取文件路径信息:" + fileName);
}
}
return fileName;
}
public String getByAttributeName(BcChannelInfo bcChannelInfo, String attributeName) {
for (Field field : bcChannelInfo.getClass().getDeclaredFields()) {
field.setAccessible(true);
try {
if (attributeName.toLowerCase().equals(field.getName().toLowerCase())) {
return new String(field.get(bcChannelInfo).toString());
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return null;
}
版权声明:本文为qq_43393995原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。