Spring:jsp+java related knowledge Finishing (13)

Source: Internet
Author: User
Tags dateformat list of attributes

1. Get the path to the. properties file in Java (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. Get the value corresponding to the. Properties key

 Public string Getpropertyconfig (String key) {        new classpathresource ("test.properties");         NULL ;         Try {            = propertiesloaderutils.loadproperties (Resource);         Catch (IOException e) {            e.printstacktrace ();        }         return Props.getproperty (key);    }

3. Second way to obtain. Properties Key Corresponding Value method

 Public Staticstring Getvaluebykey (String key, String filePath) {Properties pps=NewProperties (); Try{InputStream in=NewBufferedinputstream (NewFileInputStream (FilePath));             Pps.load (in); String value=Pps.getproperty (key); SYSTEM.OUT.PRINTLN (Key+ " = " +value); returnvalue; }Catch(IOException e) {e.printstacktrace (); return NULL; }    }

4. Write modification. Properties Health value pair method [Tanjian]

 Public Static voidWriteProperties (String FilePath, String PKey, String pValue)throwsIOException {Properties pps=NewProperties (); InputStream in=NewFileInputStream (FilePath); //read the list of attributes from the input stream (key and element pairs)pps.load (in); OutputStream out=NewFileOutputStream (FilePath);        Pps.setproperty (PKey, PValue); //In a format that is appropriate for loading into the Properties table using the Load method,//writes the list of attributes (key and element pairs) in this properties table to the output streamPps.store (out, "Update" + PKey + "name")); }

5. Write modification. Properties Health value pair method [Read write from Hashtable]

 Public Static voidWriteProperties (String FilePath, map<string, string> maps)throwsIOException {Properties pps=NewProperties (); InputStream in=NewFileInputStream (FilePath); //read the list of attributes from the input stream (key and element pairs)pps.load (in); OutputStream out=NewFileOutputStream (FilePath);  for(String key:maps.keySet ()) {Pps.setproperty (key, Maps.get (key));; }                //In a format that is appropriate for loading into the Properties table using the Load method,//writes the list of attributes (key and element pairs) in this properties table to the output streamPps.store (Out, "Store Properties"); }

6. Convert a JSON String into a Java object;

There is a Java Model [standard POJO];

 Public classXxmodelImplementsjava.io.Serializable {PrivateString ID; PrivateString Createname; PrivateDate CreateDate;  PublicXxmodel () {} PublicString getId () {return  This. ID; }         Public voidsetId (String id) { This. ID =ID; }         PublicString Getcreatename () {return  This. Createname; }         Public voidsetcreatename (String createname) { This. Createname =Createname; }         PublicDate getcreatedate () {return  This. CreateDate; }         Public voidsetcreatedate (Date createdate) { This. CreateDate =CreateDate; }}

There is a string of JSON strings to convert to 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); //Timestamptodatemorpherjsonutils.getmorpherregistry (). Registermorpher (NewDatemorpher (NewString[] {"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=NewArraylist<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); }        }        returnObjs; }

How to use:

list<xxmodel> lists = getjavacollection (new  Xxmodel (), JSON);  for (Xxmodel model:lists) {    //...}

Because the createdate above is a date type, if the Getjavacollection method is not written:

jsonutils.getmorpherregistry (). Registermorpher (                new datemorpher (new string[] {" Yyyy-mm-dd ",                        " Yyyy-mm-dd ' t ' hh:mm "," Yyyy-mm-dd ' t ' HH:mm:ss "}));

Compile to set the current date of the system, and can only be the format of the year-month-day, when the seconds are not available, no error;

About the JSON date to the object date problem, this way how to set none of the success, similar to the getjavacollection in the relevant comment off the code, get out or only month and day;

Timestamptodatemorpher class Code: [Online Copy]

 Public classTimestamptodatemorpherextendsAbstractobjectmorpher { Publicobject Morph (object value) {if(Value! =NULL) {            return NewDate (Long.parselong (string.valueof (value))); }        return NULL; } @Override PublicClass Morphsto () {returnDate.class; }     Public Booleansupports (Class clazz) {returnLong.class. IsAssignableFrom (Clazz); }}

Finally, to Xxmodel added a date word string of code;

Private String createdatestr;

Get set code slightly;

Then after the JSON is converted to a Java object:

list<xxmodel> lists = getjavacollection (new  Xxmodel (), JSON);  for (Xxmodel model:lists) {    = datetime.parsedate (Model.getcreatedatestr, "Yyyy-mm-dd hh:mm");    Model.setcreatedate (date);     // ...}

Parsedate code under the DateTime class;

 /**   * convert Time to String *   @param   Strdate *   @return   *   @throws   parseexception  */ public  static  Date parsedate ( String strdate, String dateformat) throws   parseexception {simpledateformat sdf  = new   SimpleDateFormat (DateFormat);     return   Sdf.parse (strdate); }

Also, if the date type in the model corresponds to the Hibernate mapping profile, the date type in the mapping configuration file needs to be changed to: Timestamp can be fully saved into the data table;

7. The Requestmapping method for submitting data in spring, such as:

@RequestMapping (value = "/xxx", method=requestmethod.post) public String PostData ( HttpServletRequest req, HttpServletResponse resp) {    //...}

In some cases, it is necessary to @ResponseBody annotations, otherwise there may be errors;

For example, if the project database driver is using Alibaba's Druid, the following error is common:

Java.sql.SQLException:connection holder is null

It will then appear similar to the following:

Org.springframework.web.util.NestedServletException:Request processing failed; Nested exception is Java.lang.IllegalStateException:getWriter () have already been called for this response

The problem, very strange, as if to say that the output stream, has used some kind of output mode, but also in another way, there is an error;

Moreover, if the return method is not a String, it is possible that an error exception will occur;

8. Caused By:javax.el.PropertyNotFoundException property ' xxxx ' does found on type XXX model

According to the JavaBeans specification, the first two letters of a property cannot be a large or small, or a small one. Start with lowercase letters. Pojo:private String xxxxname;//Error 9. JSP--El expression (Call Java class method)
 Package xxx.yyy;  Public class Commons {    publicstatic  string Unescapse (String str) {          // ...          return str;    }}

JSP page:

<%@ Page Import="com.utils.Commons" %> <!--may not be required -<Jsp:usebeanID= "Commons"class= "Com.utils.Commons" /><C:foreachVarstatus= "vs"var= "Item"Items= "${addrs}">${commons.unescape (item.name)}</C:foreach>

There is no output value with the page import method: ${commons.unescape (Item.name)} output is empty;

Spring:jsp+java related knowledge Finishing (13)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.