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
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)} 輸出為 空;
