[Tips article]17. Those years have been to evade the problem of debt repayment web phase!

Source: Internet
Author: User

The Xingtang phase and two phase of the Sihai, when the use of data is always used list<map<string,object>> things, but Mr. Fat has not liked!

So I Lingyun 17 of the web phase, the use of the front-end form to submit data, directly re-servlet into the object, the background from the database query data also direct programming objects, such as list<user> form

We did not write the ORM framework ourselves, but to reproduce some of the foundation of the open source to fix, because again the web phase said ORM is a comparative pull, the risk is relatively large!

In the beginning, we use the instantiation Number object first, and then through Request.getparameter ("The name of the form corresponds to the value"); Each property is setter-operated, and it needs to be judged that repetitive operations are a waste of our learning life.

So I used Apache to provide open source tools beanutils, let me solve this problem

The value in the entity bean that corresponds to the value of the Name property in the form form that passes the data from the foreground, and the fields of the data , are all consistent, and this is our convention!

And the use of Request.getparametermap () is not used by everyone, get it done!

The form is as follows:

/** Mr. Fat's core code * */ // get the data for the client map<string, string[]> map = request.getparametermap (); // Instantiation of Objects New TestData (); // Data Conversion Beanutils.populate (testData, map);

At that time some students encountered problems here, we do not consider the big data type! But date this type there is no way to convert to java.util.Date type, then I let my students re-entity bean into the string type, solve the problem, in fact, lazy way, there is no too much to study, so sorry!

Since there is no processing of date types in Beanutils, I have written a conversion date processing class, mimicking write Beanutils in the converter written

 Packagecom.p5hui.utils;Importjava.text.ParseException;ImportOrg.apache.commons.beanutils.Converter;import org.apache.commons.lang3.time.DateUtils; Public classDateconvertImplementsConverter {Privatestring[] Parsepatterns = {        "Yyyy-mm-dd", "Yyyy-mm-dd HH:mm:ss", "Yyyy-mm-dd hh:mm", "yyyy-mm",         "Yyyy/mm/dd", "Yyyy/mm/dd HH:mm:ss", "Yyyy/mm/dd hh:mm", "yyyy/mm",        "YYYY. Mm.dd "," yyyy. Mm.dd HH:mm:ss "," yyyy. Mm.dd hh:mm "," yyyy. MM "}; @SuppressWarnings ("Unchecked") @Override Public<T> T Convert (class<t>arg0, Object arg1) {String P=(String) arg1; if(p==NULL|| P.trim (). Length () ==0){                return NULL; }               Try{                return(T) dateutils.parsedate (P, parsepatterns); }            Catch(Exception e) {Try {                    return(T) dateutils.parsedate (P, parsepatterns); } Catch(ParseException ex) {return NULL; }            }                    }    }

Here I used the import org.apache.commons.lang3.time.DateUtils; format the date, but this time there is a problem, if the converter to make it? Baidu a bit of information, you can inherit beanutils after the registration operation .

 Packagecom.p5hui.utils;Importjava.lang.reflect.InvocationTargetException;ImportJava.util.Map;Importorg.apache.commons.beanutils.BeanUtils;Importorg.apache.commons.beanutils.ConvertUtils; Public classBeanutilexextendsBeanutils {PrivateBeanutilex () {}Static {        //registers the Sql.date converter, that is, the value of the SQL type that allows beanutils.copyproperties when the source destination is allowed to be empty//Convertutils.register (New Sqldateconverter (), java.util.Date.class); //Convertutils.register (New Sqltimestampconverter (),//Java.sql.Timestamp.class); //registers the Util.date converter, that is, the value of the Util type that allows beanutils.copyproperties when the source target is allowed to be empty//Convertutils.register (New Utildateconverter (), java.util.Date.class);Convertutils.register (NewDateconvert (), Java.util.Date.class); }     Public Static voidPopulate (Object target, Map source)throwsInvocationTargetException, illegalaccessexception {org.apache.commons.beanutils.BeanUtils.populate (ta    Rget, source); }}

How to use the servlet again? The core code is as follows:

 Public voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {request.setcharacterencoding ("UTF-8"); //Request.getparameter ("The name of the form corresponds to the value");Map<string, string[]> map =Request.getparametermap (); TestData TestData=NewTestData (); Try{ beanutilex.populate (testData, map); //beanutilsbean.getinstance (). Populate (arg0, arg1); //beanutilsbean2.getinstance (). Populate (arg0, arg1);System.out.println (TestData); } Catch(illegalaccessexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(InvocationTargetException e) {//TODO auto-generated Catch blockE.printstacktrace (); } response.setcontenttype ("Text/html;charset=utf-8"); }

The JSP page code is as follows

  <formAction= "Test01.shxt"Method= "POST">Integral type:<inputtype= "text"name= "Age"> <BR/>string:<inputtype= "text"name= "Name"/><BR/>Date:<inputtype= "text"name= "Create_date"> <BR/>Amount:<inputtype= "text"name= "Salary"> <BR/>Length:<inputtype= "text"name= "Length"> <BR/>Hobbies:<inputtype= "checkbox"name= "Hobbys"value= "1"> <BR/>                <inputtype= "checkbox"name= "Hobbys"value= "Football"> <BR/>             <Buttontype= "Submit">Submit</Button>    </form>

The Testdata.java entity Bean is as follows

 PackageCom.p5hui.model;Importjava.util.Arrays;Importjava.util.Date; Public classTestData {PrivateInteger age; PrivateString account; PrivateDate create_date; PrivateFloat Salary; PrivateLong length; Privatestring[] Hobbys;  Publicstring[] Gethobbys () {returnHobbys; }     Public voidSethobbys (string[] hobbys) { This. Hobbys =Hobbys; }     PublicLong GetLength () {returnlength; }     Public voidsetLength (Long length) { This. length =length; }     PublicInteger getage () {returnAge ; }     Public voidsetage (Integer age) { This. Age =Age ; }     PublicString Getaccount () {returnAccount ; }     Public voidSetaccount (String account) { This. Account =Account ; }     PublicDate getcreate_date () {returncreate_date; }     Public voidsetcreate_date (date create_date) { This. create_date =create_date; }     PublicFloat getsalary () {returnsalary; }     Public voidsetsalary (Float salary) { This. Salary =salary; } @Override PublicString toString () {return"TestData [age=" + Age + ", account=" + Account+ ", create_date=" + Create_date + ", salary=" +Salary+ ", length=" + length + ", hobbys=" +arrays.tostring (Hobbys)+ "]"; }}

This process I also test how to use SQLite here do not say, this is not the point

Mr. Fat original production, must be a boutique!

[Tips article]17. Those years have been to evade the problem of debt repayment web phase!

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.