天天看點

Spring: 讀取 .properties 檔案位址,json轉java對象,el使用java類方法相關 (十三)

1. 在Java中擷取 .properties 檔案的路徑 (src/main/resources 下)

ProjectName

|---src/main/java

|---src/main/resources

  |---test.properties

package xxx.yyy;
public class Utils {
    private String filePath = Utils.class.getClassLoader().getResource("test.properties").getPath();
}      

2. 擷取 .properties Key所對應的值

public String getPropertyConfig(String key) {
        Resource resource = new ClassPathResource("test.properties");
        Properties props = null;
        try {
            props = PropertiesLoaderUtils.loadProperties(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return props.getProperty(key);
    }      

3. 第二種擷取 .properties Key 對應值方法

public static String getValueByKey(String key, String filePath) {
        Properties pps = new Properties();
        try {
             InputStream in = new BufferedInputStream (new FileInputStream(filePath));  
             pps.load(in);
             String value = pps.getProperty(key);
             System.out.println(key + " = " + value);
             return value;
             
         }catch (IOException e) {
             e.printStackTrace();
             return null;
         }
    }      

4. 寫入修改 .properties 健值對方法 [單健]

public static void WriteProperties (String filePath, String pKey, String pValue) throws IOException {
        Properties pps = new Properties();
         
        InputStream in = new FileInputStream(filePath);
        //從輸入流中讀取屬性清單(鍵和元素對) 
        pps.load(in);
        
        OutputStream out = new FileOutputStream(filePath);
        pps.setProperty(pKey, pValue);
        //以适合使用 load 方法加載到 Properties 表中的格式,  
        //将此 Properties 表中的屬性清單(鍵和元素對)寫入輸出流  
        pps.store(out, "Update " + pKey + " name");
    }      

5. 寫入修改 .properties 健值對方法 [從Hashtable 讀取寫入]

public static void WriteProperties(String filePath, Map<String, String> maps) throws IOException {
        Properties pps = new Properties();
         
        InputStream in = new FileInputStream(filePath);
        //從輸入流中讀取屬性清單(鍵和元素對) 
        pps.load(in);

        OutputStream out = new FileOutputStream(filePath);
        
        for (String key : maps.keySet()) {
            pps.setProperty(key, maps.get(key));;
        }
        
        //以适合使用 load 方法加載到 Properties 表中的格式,  
        //将此 Properties 表中的屬性清單(鍵和元素對)寫入輸出流  
        pps.store(out, "Store properties");
    }      

6. 将 json String 轉化為 java 對象;

有這麼個 java Model [标準 POJO];

public class xxModel implements java.io.Serializable {
    private String id;
    private String createName;
    private Date createDate;
    
    public xxModel() {
        
    }
    
    public String getId() {
        return this.id;
    }
    
    public void setId(String id) {
        this.id = id;
    }
    
    public String getCreateName() {
        return this.createName;
    }
    
    public void setCreateName(String createName) {
        this.createName = createName;
    }
    
    public Date getCreateDate() {
        return this.createDate;
    }
    
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
}      

有這麼一串 json 字元串,要轉化為 xxModel:

String json = "[{\"id\":\"01\",\"createName\":\"admin\",\"createDate\":\"2014-09-02 14:30\"},{...}]";

@SuppressWarnings("unchecked")
    public static <T> List<T> getJavaCollection(T clazz, String jsons) {
        List<T> objs = null;
        JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(jsons);
        // TimestampToDateMorpher
        JSONUtils.getMorpherRegistry().registerMorpher(
                new DateMorpher(new String[] { "yyyy-MM-dd",
                        "yyyy-MM-dd'T'HH:mm", "yyyy-MM-dd'T'HH:mm:ss" }));
        // JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new
        // String[] {"MM/dd/yyyy", "MM/dd/yyyy HH:mm", "MM/dd/yyyy HH:mm:ss"}));
        // JSONUtils.getMorpherRegistry().registerMorpher(new
        // TimestampToDateMorpher());
        if (jsonArray != null) {
            objs = new ArrayList<T>();
            List<T> list = (List<T>) JSONSerializer.toJava(jsonArray);
            for (Object o : list) {
                JSONObject jsonObject = JSONObject.fromObject(o);
                T obj = (T) JSONObject.toBean(jsonObject, clazz.getClass());
                objs.add(obj);
            }
        }
        return objs;
    }      

使用方法:

List<xxModel> lists = getJavaCollection(new xxModel(), json);

for (xxModel model: lists) {
    //...
}      

因為上面的 createDate 是日期類型,如果 getJavaCollection 方法中沒寫:

JSONUtils.getMorpherRegistry().registerMorpher(
                new DateMorpher(new String[] { "yyyy-MM-dd",
                        "yyyy-MM-dd'T'HH:mm", "yyyy-MM-dd'T'HH:mm:ss" }));      

編譯給設定 系統目前的日期,而且隻能 是 年-月-日 的格式;時分秒都無法擷取,沒有提示錯誤;

關于json 日期 轉為對象日期問題,這邊怎麼設定都沒有成功,類似于 getJavaCollection 中相關注釋掉部分的代碼,擷取出來還是隻有年月日;

TimestampToDateMorpher 類代碼 :[網上抄的]

public class TimestampToDateMorpher extends AbstractObjectMorpher {
    public Object morph(Object value) {
        if (value != null) {
            return new Date(Long.parseLong(String.valueOf(value)));
        }
        return null;
    }

    @Override
    public Class morphsTo() {
        return Date.class;
    }

    public boolean supports(Class clazz) {
        return Long.class.isAssignableFrom(clazz);
    }
}      

最後是給 xxModel 再添加了個 日期字任串的代碼;

private String createDateStr;

get set 代碼略;

然後再 json 轉為 java 對象後:

List<xxModel> lists = getJavaCollection(new xxModel(), json);

for (xxModel model: lists) {
    Date date = DateTime.parseDate(model.getCreateDateStr, "yyyy-MM-dd HH:mm");
    model.setCreateDate(date);
    //...
}      

DateTime類下 parseDate 代碼;

/**
     * 把時間轉化為字元串
     * @param strdate
     * @return
     * @throws ParseException 
     */
    public static Date parseDate(String strdate, String dateFormat) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        return sdf.parse(strdate);
    }      

另外,如果 model 中日期類型 有與 Hibernate 映射配置檔案對應的,需要把 映射配置檔案中 Date 類型改為: timestamp 才可以完整儲存進 資料表;

7. spring 中 送出資料所對應的 RequestMapping 方法,如:

@RequestMapping(value = "/xxx", method=RequestMethod.POST)
public String postData(HttpServletRequest req, HttpServletResponse resp) {
    //...
}      

有些情況下 ,一定還需要 @ResponseBody 注解,不然有可能會出現錯誤;

比如,如果項目資料庫驅動是用 alibaba 的 druid 的話,就普通出現如下的錯誤:

java.sql.SQLException: connection holder is null

然後還會出現類似:

 org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: getWriter() has already been called for this response 

的問題,很奇怪;好像是說輸出流,已經使用了某種輸出方式,還用了另外的方式,就出現錯誤;

而且,如果傳回方式 不為 String 的話,有可能也會出現錯誤異常;

8. Caused by: javax.el.PropertyNotFoundException Property 'xxxx' not found on type xxx model

根據 JavaBeans 規範,屬性的前兩個字母不能是一大一小,或者是一小一大。開頭字母要小寫才行。

POJO:

private String XxxxName ;// 錯誤

9. JSP -- EL表達式 (調用java 類方法)

package xxx.yyy;
public class Commons {
    public static String unescapse(String str) {
          //...
          return str;
    }
}      

jsp頁面:

<%@ page import="com.utils.Commons" %> <!-- 可能不需要 -->
<jsp:useBean id="commons" class="com.utils.Commons" />

<c:forEach varStatus="vs" var="item" items="${addrs }">
     ${commons.unescape(item.name) }
</c:forEach>      

用 page import 方法沒有輸出值: ${Commons.unescape(item.name)} 輸出為 空;