实现机制:
1):利用 HttpServletRequest 里的getParameterNames()方法先枚举各字段名,再将各字段的值依次用getParameter(name)方法提取出来。
2):利用反射的原理得到各字段,filed.setAccessible(true)解封后将得到的字段的值赋给DO对象. filed.set(object,value).
@RequestMapping("dataAdd")
@ResponseBody
public String add(HttpServletRequest request,HttpSession session) {
Enumeration<String> enums = request.getParameterNames();
//第一种方案
/*Channel channel = new Channel();
while (enums.hasMoreElements()) {
String paramName = enums.nextElement();
String paramValue = request.getParameter(paramName);
Class<Channel> clazz = Channel.class;
try {
Field field = clazz.getDeclaredField(paramName);
field.setAccessible(true);
field.set(channel, paramValue);
} catch (Exception e) {
e.printStackTrace();
}
}*/
//第二种方案
Map<String, String> map = new HashMap<String, String>();
while (enums.hasMoreElements()) {
String paramName = enums.nextElement();
String paramValue = request.getParameter(paramName);
map.put(paramName, paramValue);
}
String josnMap = JSON.toJSONString(map);
ChannelParam channelParam = JSON.parseObject(josnMap, ChannelParam.class);
UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
int result = channelManageService.add(channelParam,userInfo);
String code = result>0? GlobalVar.RC_CODE_SUCCESS : GlobalVar.RC_CODE_FAIL;
String msg =result>0? GlobalVar.RM_CODE_SUCCESS : GlobalVar.RM_CODE_FAIL;
Map<String, String> resultMap = new HashMap<String, String>();
resultMap.put("code", code);
resultMap.put("msg", msg);
String json = JSON.toJSONString(resultMap);
return json;
}