FastJsonActiveRecordPlugin:
package com.jfinal.ext.plugin;
import javax.sql.DataSource;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import com.jfinal.ext.plugin.fastjson.ModelDeserializer;
import com.jfinal.ext.plugin.fastjson.ModelSerializer;
import com.jfinal.ext.plugin.fastjson.RecordSerializer;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Config;
import com.jfinal.plugin.activerecord.IDataSourceProvider;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
/**
* FastJson ActiveRecordPlugin
*
* @author Obama
*
*/
public class FastJsonActiveRecordPlugin extends ActiveRecordPlugin {
public FastJsonActiveRecordPlugin(String configName, IDataSourceProvider dataSourceProvider, int transactionLevel) {
super(configName, dataSourceProvider, transactionLevel);
}
public FastJsonActiveRecordPlugin(String configName, IDataSourceProvider dataSourceProvider) {
super(configName, dataSourceProvider);
}
public FastJsonActiveRecordPlugin(String configName, DataSource dataSource, int transactionLevel) {
super(configName, dataSource, transactionLevel);
}
public FastJsonActiveRecordPlugin(String configName, DataSource dataSource) {
super(configName, dataSource);
}
public FastJsonActiveRecordPlugin(IDataSourceProvider dataSourceProvider, int transactionLevel) {
super(dataSourceProvider, transactionLevel);
}
public FastJsonActiveRecordPlugin(IDataSourceProvider dataSourceProvider) {
super(dataSourceProvider);
}
public FastJsonActiveRecordPlugin(DataSource dataSource, int transactionLevel) {
super(dataSource, transactionLevel);
}
public FastJsonActiveRecordPlugin(DataSource dataSource) {
super(dataSource);
}
public FastJsonActiveRecordPlugin(Config config) {
super(config);
}
@Override
public ActiveRecordPlugin addMapping(String tableName, String primaryKey, Class<? extends Model<?>> modelClass) {
_fastJsonInit(modelClass);
return super.addMapping(tableName, primaryKey, modelClass);
}
@Override
public ActiveRecordPlugin addMapping(String tableName, Class<? extends Model<?>> modelClass) {
_fastJsonInit(modelClass);
return super.addMapping(tableName, modelClass);
}
private void _fastJsonInit(Class<? extends Model<?>> modelClass) {
if (modelClass == Model.class)
return;
// 序列化
SerializeConfig.getGlobalInstance().put(modelClass, ModelSerializer.instance);
// 反序列化
ParserConfig.getGlobalInstance().putDeserializer(modelClass, ModelDeserializer.instance);
}
@Override
public boolean start() {
boolean bol = super.start();
if (bol) {
SerializeConfig.getGlobalInstance().put(Record.class, RecordSerializer.instance);
// 时间格式
SerializeConfig.getGlobalInstance().put(java.sql.Timestamp.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));
}
return bol;
}
}
JfinalSerializer:
package com.jfinal.ext.plugin.fastjson;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.FilterUtils;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.NameFilter;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.alibaba.fastjson.serializer.PropertyPreFilter;
import com.alibaba.fastjson.serializer.SerialContext;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
/**
* FastJson JfinalSerializer
*
* @author Obama
*
*/
public abstract class JfinalSerializer implements ObjectSerializer {
protected abstract Map<String, Object> getMap(Object object);
@SuppressWarnings({ "rawtypes", "unchecked" })
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType) throws IOException {
SerializeWriter out = serializer.getWriter();
Map<String, Object> map = null;
if (object == null || (map = this.getMap(object)) == null) {
out.writeNull();
return;
}
if (out.isEnabled(SerializerFeature.SortField)) {
if ((!(map instanceof SortedMap)) && !(map instanceof LinkedHashMap)) {
try {
map = new TreeMap(map);
} catch (Exception ex) {
// skip
}
}
}
if (serializer.containsReference(object)) {
serializer.writeReference(object);
return;
}
SerialContext parent = serializer.getContext();
serializer.setContext(parent, object, fieldName);
try {
out.write('{');
serializer.incrementIndent();
Class<?> preClazz = null;
ObjectSerializer preWriter = null;
boolean first = true;
if (out.isEnabled(SerializerFeature.WriteClassName)) {
out.writeFieldName(JSON.DEFAULT_TYPE_KEY);
out.writeString(object.getClass().getName());
first = false;
}
for (Map.Entry entry : map.entrySet()) {
Object value = entry.getValue();
Object entryKey = entry.getKey();
{
List<PropertyPreFilter> preFilters = serializer.getPropertyPreFiltersDirect();
if (preFilters != null && preFilters.size() > 0) {
if (entryKey == null || entryKey instanceof String) {
if (!FilterUtils.applyName(serializer, object, (String) entryKey)) {
continue;
}
} else if (entryKey.getClass().isPrimitive() || entryKey instanceof Number) {
String strKey = JSON.toJSONString(entryKey);
if (!FilterUtils.applyName(serializer, object, strKey)) {
continue;
}
}
}
}
{
List<PropertyFilter> propertyFilters = serializer.getPropertyFiltersDirect();
if (propertyFilters != null && propertyFilters.size() > 0) {
if (entryKey == null || entryKey instanceof String) {
if (!FilterUtils.apply(serializer, object, (String) entryKey, value)) {
continue;
}
} else if (entryKey.getClass().isPrimitive() || entryKey instanceof Number) {
String strKey = JSON.toJSONString(entryKey);
if (!FilterUtils.apply(serializer, object, strKey, value)) {
continue;
}
}
}
}
{
List<NameFilter> nameFilters = serializer.getNameFiltersDirect();
if (nameFilters != null && nameFilters.size() > 0) {
if (entryKey == null || entryKey instanceof String) {
entryKey = FilterUtils.processKey(serializer, object, (String) entryKey, value);
} else if (entryKey.getClass().isPrimitive() || entryKey instanceof Number) {
String strKey = JSON.toJSONString(entryKey);
entryKey = FilterUtils.processKey(serializer, object, strKey, value);
}
}
}
{
List<ValueFilter> valueFilters = serializer.getValueFiltersDirect();
if (valueFilters != null && valueFilters.size() > 0) {
if (entryKey == null || entryKey instanceof String) {
value = FilterUtils.processValue(serializer, object, (String) entryKey, value);
} else if (entryKey.getClass().isPrimitive() || entryKey instanceof Number) {
String strKey = JSON.toJSONString(entryKey);
value = FilterUtils.processValue(serializer, object, strKey, value);
}
}
}
if (value == null) {
if (!serializer.isEnabled(SerializerFeature.WriteMapNullValue)) {
continue;
}
}
if (entryKey instanceof String) {
String key = (String) entryKey;
if (!first) {
out.write(',');
}
if (out.isEnabled(SerializerFeature.PrettyFormat)) {
serializer.println();
}
out.writeFieldName(key, true);
} else {
if (!first) {
out.write(',');
}
if (out.isEnabled(SerializerFeature.BrowserCompatible) || out.isEnabled(SerializerFeature.WriteNonStringKeyAsString)) {
String strEntryKey = JSON.toJSONString(entryKey);
serializer.write(strEntryKey);
} else {
serializer.write(entryKey);
}
out.write(':');
}
first = false;
if (value == null) {
out.writeNull();
continue;
}
Class<?> clazz = value.getClass();
if (clazz == preClazz) {
preWriter.write(serializer, value, entryKey, null);
} else {
preClazz = clazz;
preWriter = serializer.getObjectWriter(clazz);
preWriter.write(serializer, value, entryKey, null);
}
}
} finally {
serializer.setContext(parent);
}
serializer.decrementIdent();
if (out.isEnabled(SerializerFeature.PrettyFormat) && map.size() > 0) {
serializer.println();
}
out.write('}');
}
}
ModelSerializer(支持model序列化):
package com.jfinal.ext.plugin.fastjson;
import java.util.Map;
import com.jfinal.plugin.activerecord.Model;
/**
* FastJson ModelSerializer
*
* @author Obama
*
*/
public class ModelSerializer extends JfinalSerializer {
public static ModelSerializer instance = new ModelSerializer();
@Override
protected Map<String, Object> getMap(Object object) {
return com.jfinal.plugin.activerecord.CPI.getAttrs((Model<?>) object);
}
}
RecordSerializer(支持record序列化):
package com.jfinal.ext.plugin.fastjson;
import java.util.Map;
import com.jfinal.plugin.activerecord.Record;
/**
* FastJson RecordSerializer
*
* @author Obama
*
*/
public class RecordSerializer extends JfinalSerializer {
public static RecordSerializer instance = new RecordSerializer();
@Override
protected Map<String, Object> getMap(Object object) {
return ((Record) object).getColumns();
}
}
JsonFeildDes:
package com.jfinal.ext.plugin.fastjson;
import java.lang.reflect.Field;
import com.alibaba.fastjson.annotation.JSONField;
/**
* FastJson JsonFeildDes
*
* @author Obama
*
*/
public class JsonFeildDes {
private Field field;
private JSONField jasonField;
public JsonFeildDes(Field field, JSONField jasonField) {
super();
this.field = field;
this.jasonField = jasonField;
}
public Field getField() {
return field;
}
public void setField(Field field) {
this.field = field;
}
public JSONField getJasonField() {
return jasonField;
}
public void setJasonField(JSONField jasonField) {
this.jasonField = jasonField;
}
}
ModelDeserializer(支持model反序列化):
package com.jfinal.ext.plugin.fastjson;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.parser.JSONLexer;
import com.alibaba.fastjson.parser.JSONToken;
import com.alibaba.fastjson.parser.ParseContext;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;
/**
* FastJson ModelDeserializer
*
* @author Obama
*
*/
public class ModelDeserializer implements ObjectDeserializer {
public final static ModelDeserializer instance = new ModelDeserializer();
@SuppressWarnings("unchecked")
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
final JSONLexer lexer = parser.getLexer();
if (lexer.token() == JSONToken.NULL) {
lexer.nextToken(JSONToken.COMMA);
return null;
}
T model = null;
Map<String, Object> map = null;
ParseContext context = parser.getContext();
Class<? extends Model<?>> clazz = null;
Table table = null;
Map<String, JsonFeildDes> jfd = null;
try {
clazz = (Class<? extends Model<?>>) type;
table = TableMapping.me().getTable(clazz);
jfd = new HashMap<String, JsonFeildDes>();
_scanJsonAnnotation(clazz, jfd);
model = (T) clazz.newInstance();
map = com.jfinal.plugin.activerecord.CPI.getAttrs((Model<?>) model);
parser.setContext(context, map, fieldName);
deserialze(parser, fieldName, map, (Model<?>) model, jfd, table);
return model;
} catch (InstantiationException e) {
throw new JSONException("init model exceptopn:" + e.getMessage());
} catch (IllegalAccessException e) {
throw new JSONException("init model exceptopn:" + e.getMessage());
} catch (NumberFormatException e) {
throw e;
} finally {
parser.setContext(context);
clazz = null;
table = null;
jfd.clear();
}
}
private void _scanJsonAnnotation(Class<? extends Model<?>> clazz, Map<String, JsonFeildDes> jfd) {
for (Field f : clazz.getDeclaredFields()) {
if (Modifier.isStatic(f.getModifiers())) {
continue;
}
JSONField jf = f.getAnnotation(JSONField.class);
if (jf != null && jf.name() != null && jf.name().trim().length() != 0) {
jfd.put(jf.name().trim(), new JsonFeildDes(f, jf));
}
}
}
private <T> Map<String, Object> deserialze(DefaultJSONParser parser, Object fieldName, Map<String, Object> map, Model<?> model,
Map<String, JsonFeildDes> jfd, Table table) throws NumberFormatException {
JSONLexer lexer = parser.getLexer();
if (lexer.token() != JSONToken.LBRACE) {
throw new JSONException("syntax error, expect {, actual " + lexer.token());
}
ParseContext context = parser.getContext();
try {
for (;;) {
lexer.skipWhitespace();
char ch = lexer.getCurrent();
if (parser.isEnabled(Feature.AllowArbitraryCommas)) {
while (ch == ',') {
lexer.next();
lexer.skipWhitespace();
ch = lexer.getCurrent();
}
}
String key;
if (ch == '"') {
key = lexer.scanSymbol(parser.getSymbolTable(), '"');
lexer.skipWhitespace();
ch = lexer.getCurrent();
if (ch != ':') {
throw new JSONException("expect ':' at " + lexer.pos());
}
} else if (ch == '}') {
lexer.next();
lexer.resetStringPosition();
lexer.nextToken(JSONToken.COMMA);
return map;
} else if (ch == '\'') {
if (!parser.isEnabled(Feature.AllowSingleQuotes)) {
throw new JSONException("syntax error");
}
key = lexer.scanSymbol(parser.getSymbolTable(), '\'');
lexer.skipWhitespace();
ch = lexer.getCurrent();
if (ch != ':') {
throw new JSONException("expect ':' at " + lexer.pos());
}
} else {
if (!parser.isEnabled(Feature.AllowUnQuotedFieldNames)) {
throw new JSONException("syntax error");
}
key = lexer.scanSymbolUnQuoted(parser.getSymbolTable());
lexer.skipWhitespace();
ch = lexer.getCurrent();
if (ch != ':') {
throw new JSONException("expect ':' at " + lexer.pos() + ", actual " + ch);
}
}
lexer.next();
lexer.skipWhitespace();
ch = lexer.getCurrent();
lexer.resetStringPosition();
JsonFeildDes jsonfdes = null;
Object value;
lexer.nextToken();
int c = -1;
if (lexer.token() == JSONToken.NULL) {
value = null;
lexer.nextToken();
} else {
Type valueType = Object.class;
if ((jsonfdes = jfd.get(key)) != null) {
if (!jsonfdes.getJasonField().deserialize())
continue;
valueType = jsonfdes.getField().getGenericType();
key = jsonfdes.getField().getName();
jsonfdes = null;
}
if (table.hasColumnLabel(key)) {
c = 1;
valueType = table.getColumnType(key);
}
value = parser.parseObject(valueType);
valueType = null;
}
if (c == 1) {
model.set(key, value);
} else {
model.put(key, value);
}
parser.checkMapResolve(map, key);
parser.setContext(context, value, key);
final int tok = lexer.token();
if (tok == JSONToken.EOF || tok == JSONToken.RBRACKET) {
return map;
}
if (tok == JSONToken.RBRACE) {
lexer.nextToken();
return map;
}
}
} finally {
parser.setContext(context);
}
}
public int getFastMatchToken() {
return JSONToken.LBRACE;
}
}
FastJsonRender:
package com.jfinal.ext.render;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.jfinal.render.Render;
import com.jfinal.render.RenderException;
/**
* FastJson JsonRender
*
* @author Obama
*
*/
public class FastJsonRender extends Render {
private static final long serialVersionUID = 3606364198859021837L;
/**
* http://zh.wikipedia.org/zh/MIME 在wiki中查到:
* 尚未被接受为正式数据类型的subtype,可以使用x-开始的独立名称(例如application/x-gzip) 所以以下可能要改成
* application/x-json
*
* 通过使用firefox测试,struts2-json-plugin返回的是 application/json, 所以暂不改为
* application/x-json 1: 官方的 MIME type为application/json, 见
* http://en.wikipedia.org/wiki/MIME_type 2: IE 不支持 application/json, 在 ajax
* 上传文件完成后返回 json时 IE 提示下载文件
*/
private static final String contentType = "application/json;charset=" + getEncoding();
private static final String contentTypeForIE = "text/html;charset=" + getEncoding();
private boolean forIE = false;
public FastJsonRender forIE() {
forIE = true;
return this;
}
private String jsonText;
private String[] attrs;
public FastJsonRender() {
}
@SuppressWarnings("serial")
public FastJsonRender(final String key, final Object value) {
if (key == null)
throw new IllegalArgumentException("The parameter key can not be null.");
this.jsonText = JSON.toJSONString(new HashMap<String, Object>() {
{
put(key, value);
}
});
}
public FastJsonRender(String[] attrs) {
if (attrs == null)
throw new IllegalArgumentException("The parameter attrs can not be null.");
this.attrs = attrs;
}
public FastJsonRender(String jsonText) {
if (jsonText == null)
throw new IllegalArgumentException("The parameter jsonString can not be null.");
this.jsonText = jsonText;
}
public FastJsonRender(Object object) {
if (object == null)
throw new IllegalArgumentException("The parameter object can not be null.");
this.jsonText = JSON.toJSONString(object);
}
public void render() {
if (jsonText == null)
buildJsonText();
PrintWriter writer = null;
try {
response.setHeader("Pragma", "no-cache"); // HTTP/1.0 caches might
// not implement
// Cache-Control and
// might only implement
// Pragma: no-cache
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType(forIE ? contentTypeForIE : contentType);
writer = response.getWriter();
writer.write(jsonText);
writer.flush();
} catch (IOException e) {
throw new RenderException(e);
} finally {
if (writer != null)
writer.close();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void buildJsonText() {
Map map = new HashMap();
if (attrs != null) {
for (String key : attrs)
map.put(key, request.getAttribute(key));
} else {
Enumeration<String> attrs = request.getAttributeNames();
while (attrs.hasMoreElements()) {
String key = attrs.nextElement();
Object value = request.getAttribute(key);
map.put(key, value);
}
}
this.jsonText = JSON.toJSONString(map);
}
}
整合进jfinal很简单,只需要把ActiveRecordPlugin替换为FastJsonActiveRecordPlugin即可使用!
相关推荐
对于初学者,使用这款插件可以快速上手Jfinal框架,而对于经验丰富的开发者,它则能够提高工作效率,降低出错概率。 总的来说,Jfinal3.x Eclipse插件是Java开发者,特别是那些热衷于Jfinal框架的开发者们的得力...
jfinal 的eclipse插件 jfinal 的eclipse插件 jfinal 的eclipse插件
jfinal相关资源以及mannual手册
该项目是一款基于JFinal框架的邮件发送插件设计源码,包含36个文件,包括24个Java源文件、3个属性文件、2个配置文件、1个许可证文件、1个Markdown文件、1个项目配置文件和1个XML文件。该插件旨在为Java应用提供便捷...
jfinal demo 程序,使用bootstrap 本人编写的多款插件,如使用coffeescript-maven-plugin编译coffeescript代码,使用lesscsss-maven-plugin编译lesscss代码,使用flyway-maven-plugin运行数据库脚本,支持多种定制...
使用JFinal Redis Cluster插件时,首先需要将其引入到项目中,这里我们看到有一个名为 "jfinal-rediscluster-plugin-by-shixiaotian-0.0.1.jar" 的文件,这应该是该插件的可执行版本。通常,开发者会将这个JAR文件...
标题中的“jfinal redis cluster plugin”指的是一个专为JFinal框架设计的Redis集群插件,旨在帮助开发者在使用JFinal时能便捷地接入并管理Redis集群。JFinal是一款基于Java的轻量级Web开发框架,它以其简洁的API...
还有可能包含其他如 Servlet API、Jackson 或 Fastjson 用于 JSON 处理,以及各种插件和工具库。这些库文件对于理解 JFinal 如何与其他组件交互,以及如何实现其核心功能至关重要。 综上所述,JFinal 是一个强大的 ...
- **Model**: 用于数据持久化,通常通过继承 `Model` 类或使用 JFinal 的 ORM 插件,如 ActiveRecord 插件,实现数据库操作。 - **Controller**: 处理 HTTP 请求,调用 Service 层方法,返回视图或 JSON 数据。 -...
小demo 采用框架是轻量级的jfinal,上班空闲时间做的,主要是关于用fusioncharts V3.2.4 做的报表,数据来源是java代码拼凑json格式,jsp页面采用fusioncharts提供的setJSONUrl(url)的方法,项目部署在apache-tomcat...
将这个jar包导入到eclipse或者myeclipse的plugins内,重新启动即可使用JFinal插件。
jfinal-sqlinxml jfinal sqlinxml 插件,查看其他插件-> maven 引用 ${jfinal-sqlinxml.version} 替换为相应的版本如:0.1 < dependency> < groupId>... add( new SqlInXmlPlugin ());sql文件以xx_sql.xml结尾<...
4. 插件库:提供了 JFinal 3.2 支持的各种插件 jar 包,可以直接引入到项目中使用。 总结来说,JFinal 3.2 是一款强大且易用的 Java Web 开发框架,其高效、简洁的特性使得它在中小型项目中表现出色。通过深入学习...
10. **其他工具类**:包括线程池、JSON解析、日期时间处理等常用工具类,方便开发过程中的各种操作。 在实际使用中,开发者只需根据项目需求选择合适的组件和配置,就可以快速构建出一个功能完善的Web应用。JFinal...
4. **强大的插件支持**:JFinal 提供了丰富的插件,如 SQL 工具类、缓存管理、JSON 操作等,大大提升了开发效率。 5. **Model映射数据库**:JFinal 使用 Model 对象直接映射数据库表,通过注解或配置文件进行映射...
JFinal Email插件是对JavaMail API的封装,使得在JFinal项目中使用邮件服务变得更加便捷。 在Eclipse项目中,你需要导入jfinal-mail-plugin这个库,并配置相应的邮件服务器参数。这些参数通常包括SMTP服务器地址、...
JFinal 是一个基于 Java 语言的轻量级 Web 开发框架,它以“简单、高效”为设计理念,致力于提供快速...同时,JFinal 还支持很多插件,如 ORM 插件、缓存插件等,可以在实际项目中根据需求选择使用,以提升开发效率。
针对JFinal制作的Swagger插件,集成最新版swagger-bootstrap-ui,支持文_jfinal-swagger-junior
1. 插件增强:JFinal 3.1 对已有插件进行了优化,如 ActiveRecordPlugin、ShiroPlugin、QuartzPlugin 等,提高了插件的稳定性和性能。 2. SQL 动态生成:ActiveRecordPlugin 支持更加灵活的 SQL 动态生成,简化了...
JFinal的插件系统是其强大之处,包括缓存插件、上传下载插件、AOP插件等,覆盖了开发过程中的多个环节。这些插件使得JFinal具有高度的扩展性,满足各种复杂需求。 7. 性能优化 JFinal对性能进行了深度优化,包括零...