在公司的项目中用个的时候spring,sprngmvc,mybaties框架,外加shiro安全框架,框架是从网上购买的别人写的好的,圆形已经有了,不过封装的设计个有点难,表示有一部风权限管理的看不懂,项目中封装了个PageData类,它继承了HashMap,外加实现了Map,用来自动将前台传递过来的数组参数自动装换成Map对象(PageData的对象),这样做的 好处是每次不用手动去解析前台传递的数据了,直接用this.PageData.getString("属性名")即可获取到值,很方便,,,请看代码
1.首先写个BaseControl类,里面需要有获取当前请求的HttpServletRequest对象方法,跟PageData类方法
package com.beijia.controller.base;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.servlet.ModelAndView; import com.beijia.common.utils.webpage.PageData; public class BaseController<T> { /** * 得到PageData */ public PageData getPageData(){ return new PageData(this.getRequest()); } /** * 得到当前请求的request对象 */ public HttpServletRequest getRequest() { HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); return request; } }
每次在在写control的时候直接
PageData pd = this.getPageData(); String ref=pd.getString("ref");
//便可获取到传过来的参数值
2.重头戏在这里PageData类的编写
public class PageData extends HashMap implements Map{ Map map = null; HttpServletRequest request; @SuppressWarnings({ "unchecked" }) public PageData(HttpServletRequest request){ this.request = request; Map properties = request.getParameterMap(); Map returnMap = new HashMap(); Iterator entries = properties.entrySet().iterator(); Map.Entry entry; String name = ""; String value = ""; while (entries.hasNext()) { entry = (Map.Entry) entries.next(); name = (String) entry.getKey(); Object valueObj = entry.getValue(); if(null == valueObj){ value = "";
//此处需要注意的是前台传过来的是String数组对象就用String[]来判断,如果传递过来是json对象可以用JSONObject来尝试(这种方法没试过,应该是可以的),
//也可以传递在前台拼接个字符串后,后台直接用String来判断,然后用split方法来截断(这种当然可以,没试过,也不太方便) }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(); } returnMap.put(name, value); } map = returnMap; } }
这段代码第一次看比较不容易懂,有兴趣可以自己一步一步发送个请求将数据打印出来试试
欢迎评论指点,勿言恶语