支持 ? 后带参数,以及 post json数据。
post 与 get 参数重复。post会覆盖get
import com.alibaba.fastjson.JSONObject; import com.jfinal.core.Action; import com.jfinal.core.Controller; import com.jfinal.core.paragetter.ParaGetter; import javax.servlet.ServletInputStream; import java.io.IOException; import java.util.Iterator; import java.util.Map; public class JSONObjectGetter extends ParaGetter<JSONObject> { public JSONObjectGetter(String parameterName, String defaultValue) { super(parameterName, defaultValue); } @Override protected JSONObject to(String v) { //System.out.println("to(String v)..."); return null; } @Override public JSONObject get(Action action, Controller c) { return getData(c); } private JSONObject getData(Controller c) { JSONObject jobj = new JSONObject(); // ? 参数解析 getRequestData(c, jobj); // post 参数解析 postRequestData(c, jobj); return jobj; } private void postRequestData(Controller c, JSONObject jobj) { try (ServletInputStream is = c.getRequest().getInputStream()) { byte[] bytes = new byte[is.available()]; is.read(bytes); String str = new String(bytes, "UTF-8"); JSONObject postParams = JSONObject.parseObject(str); if (postParams != null) { for (Map.Entry<String, Object> e : postParams.entrySet()) { jobj.put(e.getKey(), e.getValue()); } } } catch (IOException e) { e.printStackTrace(); } } private void getRequestData(Controller c, JSONObject jobj) { Map<String, String[]> paraMap = c.getParaMap(); Iterator<Map.Entry<String, String[]>> entries = paraMap.entrySet().iterator(); Map.Entry entry; String name = ""; String value = ""; while (entries.hasNext()) { entry = entries.next(); name = (String) entry.getKey(); Object valueObj = entry.getValue(); if (null == valueObj) { value = ""; } else if (valueObj instanceof String[]) { String[] values = (String[]) valueObj; for (int i = 0; i < values.length; i++) { value = values[i] + ","; } value = value.substring(0, value.length() - 1); } else { value = valueObj.toString(); } jobj.put(name, value); } } }
调用示例:controller 中方法