改造目的:
实现json body参数可以通过action自动注入以及可以通过getPara/getBean进行获取
实现Validator对json对象的校验
实现:
自定义RestController继承Controller 重写getPara getBean相关方法
package com.qtgl.controller; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.jfinal.core.Controller; /** * @author * @version 1.0 * @date 2019/12/1 10:45 */ public class RestController extends Controller { private final static String POST = "post"; private final static String CONTENT_TYPE_JSON = "application/json"; private JSONObject paras = null; @Override public String getPara(String name) { initParas(); return paras == null ? super.getPara(name) : paras.getStr(name); } @Override public <T> T getBean(Class<T> beanClass) { return getBean(beanClass, null, false); } @Override public <T> T getBean(Class<T> beanClass, String beanName, boolean skipConvertError) { initParas(); return paras == null ? super.getBean(beanClass, beanName, skipConvertError) : JSONUtil.toBean(paras, beanClass, skipConvertError); } @Override public <T> T getBean(Class<T> beanClass, String beanName) { return getBean(beanClass, beanName, false); } /** * 初始化paras */ private void initParas() { if (paras == null) { boolean flag = POST.equalsIgnoreCase(getRequest().getMethod()) && ContentType.JSON.value().equalsIgnoreCase(getRequest().getContentType().split(";")[0]); if (flag) { String rawData = getRawData(); try { paras = JSONUtil.parseObj(rawData); } catch (Exception e) { renderError(415); } } } } }
2.创建ApiController继承RestController
package com.qtgl.controller; import com.jfinal.aop.Before; import com.jfinal.aop.Inject; import com.jfinal.core.paragetter.Para; import com.jfinal.ext.interceptor.POST; import com.qtgl.interceptor.ParaValidator; import com.qtgl.model.ReqPara; import com.qtgl.model.Result; import com.qtgl.service.ApiService; /** * @author * @version 1.0 * @date 2019/11/29 12:36 */ public class ApiController extends RestController { @Inject private ApiService apiService; @Before({POST.class, ParaValidator.class}) public void queryTasks(@Para("") ReqPara reqPara) { Result result = apiService.queryTasks(reqPara); renderJson(result); } }
总结:自我感觉对比社区众多方案是一个比较优雅的实现方式,并且也没有用到Handler和Interceptor,依赖于第三方工具包Hutool