统一的渲染控制之定制渲染器
相对了上一个方案,此方案不需要基类,可控范围更广(响应也更广),使用更自由。
新风格
v3.6.0 后支持(以组件方式,替换掉 "@json" 渲染器)
@Component("@json")
public class RenderImpl implements Render {
@Override
public void render(Object data, Context ctx) throws Throwable {
//用 json 序列化器生成数据
String json = Solon.app().serializers().jsonOf().serialize(data);
String jsonEncoded = "";//加密
String jsonEigned = ""; //鉴名
ctx.headerSet("E", jsonEigned);
ctx.output(jsonEncoded);
}
}
旧风格
v2.8.3 后支持(定义 customize 渲染器,通过过滤器指定渲染器)
public class DemoApp {
public static void main(String[] args){
Solon.start(DemoApp.class, args, app->{
//注册一个 "customize" 渲染处理器为
app.render("customize", (data, ctx) -> {
//用 json 渲染器生成数据
String json = app.render("@json").renderAndReturn(data, ctx);
String jsonEncoded = "";//加密
String jsonEigned = ""; //鉴名
ctx.headerSet("E", jsonEigned);
ctx.output(jsonEncoded);
});
//通过过滤器,指定渲染处理器为 "customize"
app.filter(-999, (ctx,chain)->{
ctx.attrSet("@render", "customize");
});
});
}
}
v2.8.3 之前支持
public class DemoApp {
public static void main(String[] args){
Solon.start(DemoApp.class, args, app->{
//注册一个 "customize" 渲染处理器为
RenderManager.mapping("customize", (data, ctx) -> {
//用 json 渲染器生成数据
String json = RenderManager.get("@json").renderAndReturn(data, ctx);
String jsonEncoded = "";//加密
String jsonEigned = ""; //鉴名
ctx.headerSet("E", jsonEigned);
ctx.output(jsonEncoded);
});
//通过过滤器,指定渲染处理器为 "customize"
app.filter(-999, (ctx,chain)->{
ctx.attrSet("@render", "customize");
});
});
}
}
注意:RenderManager 为内部接口,未来有可能略有变化。