封装json体。依赖 fastjson。需要的拿走。
此拦截器不处理带文件表单,请自行修改。
import com.alibaba.fastjson.JSONObject; import com.jfinal.aop.Interceptor; import com.jfinal.aop.Invocation; import com.jfinal.core.Controller; import com.jfinal.kit.StrKit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import java.io.IOException; public class DatagramInterceptor implements Interceptor { private static final Logger log = LoggerFactory.getLogger(DatagramInterceptor.class); @Override public void intercept(Invocation inv) { Controller controller = inv.getController(); process(controller.getRequest()); inv.invoke(); } public void process(HttpServletRequest request) { if (request.getAttribute("_params") != null) { return; } //如果是上传文件跳过 if (StrKit.notBlank(request.getContentType()) && request.getContentType().contains("multipart/form-data")) { return; } try (ServletInputStream is = request.getInputStream()) { byte[] bytes = new byte[is.available()]; is.read(bytes); String str = new String(bytes, "UTF-8"); JSONObject jsonObject = JSONObject.parseObject(str); request.setAttribute("_params", jsonObject); } catch (IOException e) { e.printStackTrace(); } } }
前端ajax调用示例:
var json = { "id": id } //相关推荐推荐 $.ajax({ type: "post", url: '/hello', data: JSON.stringify(json), dataType:"json", async: true, success: function (res) { console.log("请求成功"); }, error: function (e) { console.log('数据返回失败') } });
后台代码:controller中实现
String str = inv.getController().getRawData();
感谢分享