JsonMapper、XmlMapper工具,增加 JsonView 过滤参数

This commit is contained in:
thinkgem
2020-05-20 23:16:26 +08:00
parent 4609d8aee7
commit 6b059e29dd
9 changed files with 131 additions and 38 deletions

View File

@@ -109,6 +109,20 @@ public class JsonMapper extends ObjectMapper {
} }
} }
/**
* Object可以是POJO也可以是Collection或数组。
* 如果对象为Null, 返回"null".
* 如果集合为空集合, 返回"[]".(根据 JsonView 渲染)
*/
public String toJsonString(Object object, Class<?> jsonView) {
try {
return this.writerWithView(jsonView).writeValueAsString(object);
} catch (IOException e) {
logger.warn("write to json string error:" + object, e);
return null;
}
}
/** /**
* 输出JSONP格式数据. * 输出JSONP格式数据.
*/ */
@@ -218,6 +232,13 @@ public class JsonMapper extends ObjectMapper {
return JsonMapper.getInstance().toJsonString(object); return JsonMapper.getInstance().toJsonString(object);
} }
/**
* 对象转换为JSON字符串根据 JsonView 渲染)
*/
public static String toJson(Object object, Class<?> jsonView){
return JsonMapper.getInstance().toJsonString(object, jsonView);
}
/** /**
* 对象转换为JSONP字符串 * 对象转换为JSONP字符串
*/ */

View File

@@ -67,6 +67,18 @@ public class XmlMapper extends com.fasterxml.jackson.dataformat.xml.XmlMapper{
} }
} }
/**
* Object可以是POJO也可以是Collection或数组。根据 JsonView 渲染)
*/
public String toXmlString(Object object, Class<?> jsonView) {
try {
return this.writerWithView(jsonView).writeValueAsString(object);
} catch (IOException e) {
logger.warn("write to xml string error:" + object, e);
return null;
}
}
/** /**
* 反序列化POJO或简单Collection如List<String>. * 反序列化POJO或简单Collection如List<String>.
* @see #fromJson(String, JavaType) * @see #fromJson(String, JavaType)
@@ -97,6 +109,13 @@ public class XmlMapper extends com.fasterxml.jackson.dataformat.xml.XmlMapper{
return XmlMapper.getInstance().toXmlString(object); return XmlMapper.getInstance().toXmlString(object);
} }
/**
* 对象转换为XML字符串根据 JsonView 渲染)
*/
public static String toXml(Object object, Class<?> jsonView){
return XmlMapper.getInstance().toXmlString(object, jsonView);
}
/** /**
* XML字符串转换为对象 * XML字符串转换为对象
*/ */

View File

@@ -21,6 +21,7 @@ import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.jeesite.common.collect.MapUtils; import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.io.PropertiesUtils; import com.jeesite.common.io.PropertiesUtils;
import com.jeesite.common.lang.ExceptionUtils; import com.jeesite.common.lang.ExceptionUtils;
@@ -179,8 +180,20 @@ public class ServletUtils {
* @param data 消息数据 * @param data 消息数据
* @return JSON字符串{result:'true',message:'', if map then key:value,key2:value2... else data:{} } * @return JSON字符串{result:'true',message:'', if map then key:value,key2:value2... else data:{} }
*/ */
@SuppressWarnings("unchecked")
public static String renderResult(String result, String message, Object data) { public static String renderResult(String result, String message, Object data) {
return renderResult(result, message, data, null);
}
/**
* 返回结果JSON字符串支持JsonP请求参数加__callback=回调函数名)
* @param result Global.TRUE or Globle.False
* @param message 执行消息
* @param data 消息数据
* @param jsonView 根据 JsonView 过滤
* @return JSON字符串{result:'true',message:'', if map then key:value,key2:value2... else data:{} }
*/
@SuppressWarnings("unchecked")
public static String renderResult(String result, String message, Object data, Class<?> jsonView) {
Map<String, Object> resultMap = MapUtils.newHashMap(); Map<String, Object> resultMap = MapUtils.newHashMap();
resultMap.put("result", result); resultMap.put("result", result);
resultMap.put("message", message); resultMap.put("message", message);
@@ -200,6 +213,7 @@ public class ServletUtils {
resultMap.put("data", data); resultMap.put("data", data);
} }
} }
Object object = null;
HttpServletResponse response = getResponse(); HttpServletResponse response = getResponse();
HttpServletRequest request = getRequest(); HttpServletRequest request = getRequest();
if (request != null){ if (request != null){
@@ -209,24 +223,29 @@ public class ServletUtils {
if (response != null){ if (response != null){
response.setContentType(MediaType.APPLICATION_XML_VALUE); response.setContentType(MediaType.APPLICATION_XML_VALUE);
} }
if (jsonView != null) {
return XmlMapper.toXml(resultMap, jsonView);
}else {
return XmlMapper.toXml(resultMap); return XmlMapper.toXml(resultMap);
}else{ }
if (response != null){
response.setContentType(MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8");
} }
if (ObjectUtils.toBoolean(PropertiesUtils.getInstance().getProperty("web.jsonp.enabled"))) { if (ObjectUtils.toBoolean(PropertiesUtils.getInstance().getProperty("web.jsonp.enabled"))) {
String functionName = request.getParameter("__callback"); String functionName = request.getParameter("__callback");
if (StringUtils.isNotBlank(functionName)){ if (StringUtils.isNotBlank(functionName)){
return JsonMapper.toJsonp(functionName, resultMap); object = new JSONPObject(functionName, resultMap);
} }
} }
return JsonMapper.toJson(resultMap);
} }
}else{
if (response != null){ if (response != null){
response.setContentType(MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8"); response.setContentType(MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8");
} }
return JsonMapper.toJson(resultMap); if (object == null) {
object = resultMap;
}
if (jsonView != null) {
return JsonMapper.toJson(object, jsonView);
}else {
return JsonMapper.toJson(object);
} }
} }
@@ -253,6 +272,19 @@ public class ServletUtils {
return renderString(response, renderResult(result, message, data), null); return renderString(response, renderResult(result, message, data), null);
} }
/**
* 直接将结果JSON字符串渲染到客户端支持JsonP请求参数加__callback=回调函数名)
* @param response 渲染对象:{result:'true',message:'',data:{}}
* @param result 结果标识Global.TRUE or Globle.False
* @param message 执行消息
* @param data 消息数据
* @param jsonView 根据 JsonView 过滤
* @return null
*/
public static String renderResult(HttpServletResponse response, String result, String message, Object data, Class<?> jsonView) {
return renderString(response, renderResult(result, message, data, jsonView), null);
}
/** /**
* 将对象转换为JSON、XML、JSONP字符串渲染到客户端JsonP请求参数加__callback=回调函数名) * 将对象转换为JSON、XML、JSONP字符串渲染到客户端JsonP请求参数加__callback=回调函数名)
* @param request 请求对象用来得到输出格式的指令JSON、XML、JSONP * @param request 请求对象用来得到输出格式的指令JSON、XML、JSONP
@@ -261,18 +293,33 @@ public class ServletUtils {
* @return null * @return null
*/ */
public static String renderObject(HttpServletResponse response, Object object) { public static String renderObject(HttpServletResponse response, Object object) {
return renderObject(response, object, null);
}
/**
* 将对象转换为JSON、XML、JSONP字符串渲染到客户端JsonP请求参数加__callback=回调函数名)
* @param request 请求对象用来得到输出格式的指令JSON、XML、JSONP
* @param response 渲染对象
* @param object 待转换JSON并渲染的对象
* @param jsonView 根据 JsonView 过滤
* @return null
*/
public static String renderObject(HttpServletResponse response, Object object, Class<?> jsonView) {
HttpServletRequest request = getRequest(); HttpServletRequest request = getRequest();
String uri = request.getRequestURI(); String uri = request.getRequestURI();
if (StringUtils.endsWithIgnoreCase(uri, ".xml") || StringUtils if (StringUtils.endsWithIgnoreCase(uri, ".xml") || StringUtils
.equalsIgnoreCase(request.getParameter("__ajax"), "xml")){ .equalsIgnoreCase(request.getParameter("__ajax"), "xml")){
return renderString(response, XmlMapper.toXml(object)); return renderString(response, XmlMapper.toXml(object));
}else{ }
if (ObjectUtils.toBoolean(PropertiesUtils.getInstance().getProperty("web.jsonp.enabled"))) { if (ObjectUtils.toBoolean(PropertiesUtils.getInstance().getProperty("web.jsonp.enabled"))) {
String functionName = request.getParameter("__callback"); String functionName = request.getParameter("__callback");
if (StringUtils.isNotBlank(functionName)){ if (StringUtils.isNotBlank(functionName)){
return renderString(response, JsonMapper.toJsonp(functionName, object)); object = new JSONPObject(functionName, object);
} }
} }
if (jsonView != null) {
return renderString(response, JsonMapper.toJson(object, jsonView));
}else {
return renderString(response, JsonMapper.toJson(object)); return renderString(response, JsonMapper.toJson(object));
} }
} }

View File

@@ -31,10 +31,10 @@ public class AreaUtils {
* @return * @return
*/ */
public static List<Area> getAreaAllList(){ public static List<Area> getAreaAllList(){
List<Area> areaList = SysUtils.getCache(CACHE_AREA_ALL_LIST); List<Area> areaList = SysCacheUtils.get(CACHE_AREA_ALL_LIST);
if (areaList == null){ if (areaList == null){
areaList = Static.areaService.findList(new Area()); areaList = Static.areaService.findList(new Area());
SysUtils.putCache(CACHE_AREA_ALL_LIST, areaList); SysCacheUtils.put(CACHE_AREA_ALL_LIST, areaList);
} }
return areaList; return areaList;
} }
@@ -43,7 +43,7 @@ public class AreaUtils {
* 清理区域缓存 * 清理区域缓存
*/ */
public static void clearCache(){ public static void clearCache(){
SysUtils.removeCache(CACHE_AREA_ALL_LIST); SysCacheUtils.remove(CACHE_AREA_ALL_LIST);
} }
} }

View File

@@ -20,9 +20,9 @@ import com.jeesite.modules.sys.service.EmployeeService;
import com.jeesite.modules.sys.service.OfficeService; import com.jeesite.modules.sys.service.OfficeService;
/** /**
* 员工工具类 * 员工部门工具类
* @author ThinkGem * @author ThinkGem
* @version 2016年11月2日 * @version 2020-5-20
*/ */
public class EmpUtils { public class EmpUtils {
@@ -158,7 +158,7 @@ public class EmpUtils {
} }
/** /**
* 获取当前员工所有机构编码,包括附属机构以及子机构(数据权限用) * 获取当前员工所有机构编码,包括附属机构以及子机构(数据权限用)V4.2.0
* @author ThinkGem * @author ThinkGem
*/ */
public static String[] getOfficeCodesAndChildren(){ public static String[] getOfficeCodesAndChildren(){
@@ -295,7 +295,7 @@ public class EmpUtils {
} }
/** /**
* 获取当前员工所有公司编码,包括子公司(数据权限用) * 获取当前员工所有公司编码,包括子公司(数据权限用)V4.2.0
* @author ThinkGem * @author ThinkGem
*/ */
public static String[] getCompanyCodesAndChildren(){ public static String[] getCompanyCodesAndChildren(){

View File

@@ -32,7 +32,7 @@ import com.jeesite.common.lang.TimeUtils;
import com.jeesite.common.shiro.realm.LoginInfo; import com.jeesite.common.shiro.realm.LoginInfo;
import com.jeesite.common.shiro.session.SessionDAO; import com.jeesite.common.shiro.session.SessionDAO;
import com.jeesite.common.web.BaseController; import com.jeesite.common.web.BaseController;
import com.jeesite.modules.sys.utils.SysUtils; import com.jeesite.modules.sys.utils.SysCacheUtils;
import com.jeesite.modules.sys.utils.UserUtils; import com.jeesite.modules.sys.utils.UserUtils;
/** /**
@@ -145,7 +145,7 @@ public class OnlineController extends BaseController{
public String kickOut(String sessionId) { public String kickOut(String sessionId) {
Session session = sessionDAO.readSession(sessionId); Session session = sessionDAO.readSession(sessionId);
if (session != null){ if (session != null){
Map<String, String> onlineTickOutMap = SysUtils.getCache("onlineTickOutMap"); Map<String, String> onlineTickOutMap = SysCacheUtils.get("onlineTickOutMap");
if (onlineTickOutMap == null){ if (onlineTickOutMap == null){
onlineTickOutMap = MapUtils.newConcurrentMap(); onlineTickOutMap = MapUtils.newConcurrentMap();
} }
@@ -157,7 +157,7 @@ public class OnlineController extends BaseController{
onlineTickOutMap.put(key, StringUtils.EMPTY); onlineTickOutMap.put(key, StringUtils.EMPTY);
} }
} }
SysUtils.putCache("onlineTickOutMap", onlineTickOutMap); SysCacheUtils.put("onlineTickOutMap", onlineTickOutMap);
sessionDAO.delete(session); sessionDAO.delete(session);
return renderResult(Global.TRUE, text("踢出已成功!")); return renderResult(Global.TRUE, text("踢出已成功!"));
} }

View File

@@ -165,7 +165,7 @@ public class ${ClassName}Controller extends BaseController {
<% } %> <% } %>
/** /**
* 保存${functionNameSimple} * 保存数据
*/ */
@RequiresPermissions("${permissionPrefix}:edit") @RequiresPermissions("${permissionPrefix}:edit")
@PostMapping(value = "save") @PostMapping(value = "save")
@@ -177,7 +177,7 @@ public class ${ClassName}Controller extends BaseController {
<% if(toBoolean(table.optionMap['isHaveDisableEnable'])){ %> <% if(toBoolean(table.optionMap['isHaveDisableEnable'])){ %>
/** /**
* 停用${functionNameSimple} * 停用数据
*/ */
@RequiresPermissions("${permissionPrefix}:edit") @RequiresPermissions("${permissionPrefix}:edit")
@RequestMapping(value = "disable") @RequestMapping(value = "disable")
@@ -198,7 +198,7 @@ public class ${ClassName}Controller extends BaseController {
} }
/** /**
* 启用${functionNameSimple} * 启用数据
*/ */
@RequiresPermissions("${permissionPrefix}:edit") @RequiresPermissions("${permissionPrefix}:edit")
@RequestMapping(value = "enable") @RequestMapping(value = "enable")
@@ -212,7 +212,7 @@ public class ${ClassName}Controller extends BaseController {
<% if(toBoolean(table.optionMap['isHaveDelete'])){ %> <% if(toBoolean(table.optionMap['isHaveDelete'])){ %>
/** /**
* 删除${functionNameSimple} * 删除数据
*/ */
@RequiresPermissions("${permissionPrefix}:edit") @RequiresPermissions("${permissionPrefix}:edit")
@RequestMapping(value = "delete") @RequestMapping(value = "delete")

View File

@@ -267,7 +267,14 @@ $("#testDataChildDataGrid").dataGrid({
labelName: 'testUser.userName', labelValue: val.split('|')[1], labelName: 'testUser.userName', labelValue: val.split('|')[1],
url: '${ctx}/sys/office/treeData?isLoadUser=true', cssClass: '' url: '${ctx}/sys/office/treeData?isLoadUser=true', cssClass: ''
}); });
},
custom_value: function(element, act){
return {userCode: element.find('[type=hidden]').val(),
userName: element.find('[type=text]').val()};
} }
},
unformat: function(val, obj, cell){
return $('#user_'+obj.rowId+'_'+obj.colModel.name+'Code', cell).val();
} }
}, },
{header:'${text("列表选择")}', name:'testUser2', width:150, {header:'${text("列表选择")}', name:'testUser2', width:150,

View File

@@ -122,7 +122,6 @@ $('#dataGrid').dataGrid({
searchForm: $("#searchForm"), searchForm: $("#searchForm"),
columnModel: [ columnModel: [
{header:'${text("单行文本")}', name:'testInput', index:'a.test_input', width:250, align:"left", frozen:true, formatter: function(val, obj, row, act){ {header:'${text("单行文本")}', name:'testInput', index:'a.test_input', width:250, align:"left", frozen:true, formatter: function(val, obj, row, act){
if (obj.exporttype == "excel") { return val||'' };
return '<a href="${ctx}/test/testData/form?id='+row.id+'" class="btnList" data-title="${text("编辑数据")}">'+(val||row.id)+'</a>'; return '<a href="${ctx}/test/testData/form?id='+row.id+'" class="btnList" data-title="${text("编辑数据")}">'+(val||row.id)+'</a>';
}}, }},
{header:'${text("多行文本")}', name:'testTextarea', index:'a.test_textarea', width:150, align:"left"}, {header:'${text("多行文本")}', name:'testTextarea', index:'a.test_textarea', width:150, align:"left"},
@@ -150,7 +149,7 @@ $('#dataGrid').dataGrid({
{header:'${text("创建时间")}', name:'createDate', index:'a.create_date', firstsortorder:'desc', width:150, align:"center"}, {header:'${text("创建时间")}', name:'createDate', index:'a.create_date', firstsortorder:'desc', width:150, align:"center"},
{header:'${text("备注信息")}', name:'remarks', index:'a.remarks', width:150, align:"left"}, {header:'${text("备注信息")}', name:'remarks', index:'a.remarks', width:150, align:"left"},
{header:'${text("操作")}', name:'actions', width:200, sortable:false, title:false, formatter: function(val, obj, row, act){ {header:'${text("操作")}', name:'actions', width:200, sortable:false, title:false, formatter: function(val, obj, row, act){
var actions = []; if (obj.exporttype == "excel") { return val||'' }; var actions = [];
<% if(hasPermi('test:testData:edit')){ %> <% if(hasPermi('test:testData:edit')){ %>
actions.push('<a href="${ctx}/test/testData/form?id='+row.id+'" class="btnList" title="${text("编辑数据")}"><i class="fa fa-pencil"></i></a>&nbsp;'); actions.push('<a href="${ctx}/test/testData/form?id='+row.id+'" class="btnList" title="${text("编辑数据")}"><i class="fa fa-pencil"></i></a>&nbsp;');
if (row.status == Global.STATUS_NORMAL){ if (row.status == Global.STATUS_NORMAL){