自定義PageData類案例,


 在公司的項目中用個的時候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; } }

這段代碼第一次看比較不容易懂,有興趣可以自己一步一步發送個請求將數據打印出來試試

歡迎評論指點,勿言惡語


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM