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)} 输出为 空;

原文地址:https://www.cnblogs.com/editor/p/3952003.html