How to develop a Java Open source Framework-----JVN Framework implementation file upload and method encapsulation (vi) Starling strength explanation

Source: Internet
Author: User

Preface

One

Bloggers are teaching you how to develop a Java EE Framework (JVN framework) with a full development video on the blog, and each blog post is a knowledge point to help you understand the framework:

Blog home:http://www.cnblogs.com/everxs/

This content video and source code :http://pan.baidu.com/s/1pJsoGDd

1, why use the Java framework, and what benefits the framework can bring. 2, to help you understand the principles of the framework.

3, how the framework is implemented. 4, how to develop a Java framework that belongs to itself.

Two
The framework of the current development is called JVN Framework, the name of the blogger: Starling Commentary, leading you to the development framework.
The JVN framework contains the following features:
The 1,MVC framework, similar to the STRINGMVC or struts-like web framework, is not written from the servlet and is not written to the servlet configuration in Web. Xml.

The 2,orm framework, like Hibernate or Ibatis, is not bothered by complex JDBC operations.

The 3,spring framework, like the spring framework, is not bothered by bean management.

4,cache caching mechanism.

5, timing scheduling.

6, automatically generate online documents.

7, Interceptor

Three
Each blog post has a detailed solution of the video and the corresponding source code , and the video is continuous , want to learn how the JVN framework is developed, it is recommended to read from the first post JVN.

the content of this blog

Recall: The last lesson talked about customizing annotation and implementing interceptors

In this lesson, we will implement:

1, File Upload package, has uploaded files in the form of common parameters of the package.

2. Encapsulation of common methods

realization of the idea :

1, first import Commons-fileupload-1.3.1.jar,commons-io-2.4.jar these two packages.

2, then write the GetFile () and GetFiles () methods inside the Jvncontroller.

3, pass in the Save directory, save the file name to save files.

4, put the normal parameters in the form into the parammap inside.

5, through Getformparam () get the common parameters when uploading the file.

The following is the content of the video, as well as the source address:

Http://pan.baidu.com/s/1pJsoGDd

Ps: Video and code will continue to update, I hope you like, a lot of support.

qq:245223343 Forever Starling.

Here is the code I wrote:

Remember to first pour the jar package: Commons-fileupload-1.3.1.jar,commons-io-2.4.jar. My source code inside can be downloaded directly.

The following is the Jvncontroller class code:

Package Com.jvn.core;import Java.io.file;import Java.io.ioexception;import java.text.parseexception;import Java.text.simpledateformat;import Java.util.arraylist;import Java.util.date;import Java.util.HashMap;import Java.util.iterator;import Java.util.list;import Java.util.map;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.commons.fileupload.fileitem;import Org.apache.commons.fileupload.disk.diskfileitemfactory;import Org.apache.commons.fileupload.servlet.servletfileupload;import Com.jvn.kit.filekit;import Com.jvn.kit.MapKit; Import com.jvn.kit.strkit;/** * Controller's parent class * @author Administrator * */public class Jvncontroller {/** * Create Controller object When injected with two properties */private httpservletrequest request;private httpservletresponse response;private SimpleDateFormat SDF_DATE _time = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");p rivate simpledateformat sdf_date = new SimpleDateFormat (" Yyyy-mm-dd ");p rivate map<string,string> parammap = NEW hashmap<string, string> ();p ublic httpservletrequest getrequest () {return request;} public void Setrequest (HttpServletRequest request) {this.request = Request;} Public HttpServletResponse GetResponse () {return response;} public void Setresponse (HttpServletResponse response) {this.response = response;} /** * Here are some input methods *//** * Go int * @param paramname * @param defaultvalue * @return */public int getInt (String paramname,int DefaultValue) {int result = Defaultvalue;try{result = Integer.parseint (GetParam (paramname));} catch (Exception e) {} return result;} /** * Go int * @param paramname * @return */public int getInt (String paramname) {int result = Integer.parseint (GetParam (param Name)); return result;} /** * Go double * @param paramname * @param defaultvalue * @return */public double getdouble (String paramname,double Default Value) {Double result = Defaultvalue;try{result = Double.parsedouble (GetParam (paramname));} catch (Exception e) {} return result;} /** * Turn double * @param paramname * @param defaultvaLue * @return */public double getdouble (String paramname) {Double result = double.parsedouble (GetParam (paramname)); return result;} /** * Turn float * @param paramname * @param defaultvalue * @return */public float getfloat (String paramname,float Defaultvalu e) {float result = Defaultvalue;try{result = Float.parsefloat (GetParam (paramname));} catch (Exception e) {} return result;} /** * Turn float * @param paramname * @param defaultvalue * @return */public float getfloat (String paramname) {float result = F Loat.parsefloat (GetParam (paramname)); return result;} /** * Turn Boolen * @param paramname * @param defaultvalue * @return */public boolean getboolean (String paramname) {Boolean res Ult = Boolean.parseboolean (GetParam (paramname)); return result;} /** * Turn Boolean * @param paramname * @param defaultvalue * @return */public boolean Getboolean (String Paramname,boolean def Aultvalue) {Boolean result = Defaultvalue;try{result = Boolean.parseboolean (GetParam (paramname));} catch (Exception e) {} return result;} /** * Go to date * @param paramname * @param defaultvalue * @return */public date getDate (String paramname, date defaultvalue) {Date date = d Efaultvalue;try{date = Sdf_date.parse (GetParam (paramname));} catch (Exception e) {}return date;} /** * Go date * @param paramname * @param defaultvalue * @return */public date getDate (String paramname) {Date date = Null;t ry {date = Sdf_date.parse (GetParam (paramname));} catch (ParseException e) {e.printstacktrace (); throw new RuntimeException (e);} return date;} /** * Go date * @param paramname * @param defaultvalue * @return */public date getdatetime (String paramname, date Defaultval UE) {Date date = Defaultvalue;try{date = Sdf_date_time.parse (GetParam (paramname));} catch (Exception e) {}return date;} /** * Go date * @param paramname * @param defaultvalue * @return */public date getdatetime (String paramname) {Date date = Nu ll;try {date = Sdf_date_time.parse (GetParam (paramname));} catch (ParseException e) {e.printstacktrace (); throw new RuntimeException (e);} return date;} Public String GetParam (String paramname) {return request.getparameter (paramname);} public string GetParam (string paramname,string defaultvalue) {if (Request.getparameter (paramname) ==null) {return DefaultValue;} Else{return Request.getparameter (paramname);}} /** * Remove the parammap of the request into key-->value[0] Map * @return */public map<string,string> getmap () {map<string, string[]> map = Request.getparametermap (); map<string,string> _map = new hashmap<string, string> (); for (String S:map.keyset ()) {string[] values = map.ge T (s); _map.put (S, values[0]);} return _map;} /** * into Clazz return object * @param clazz * @return */public object GetObject (Class clazz) {Object object = Mapkit.maptoobject (Getma P (), clazz); return object;} /** * Returns String * @param content */public void renderstring (string content) {try {response.getwriter (). write (content);} cat CH (ioexception e) {e.printstacktrace ();}} /** * Returns a page */public void render (String view) {try {getrequest (). Getrequestdispatcher (view). Forward (Getrequest (), GetResponse ());} catch (Exception e) {e.printstacktrace (); throw new RuntimeException (e);}} /** * Redirect to a URL * @param actionname */public void Redirect (String actionname) {try {getResponse (). Sendredirect (ActionName );} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} /** * Get uploaded files, here need to add Commons-fileupload.jar,commons-io.jar * @param dirpath * @param fileName * @param maxSize 1024*1024 *1m * @return */public void GetFile (String dirpath,string filenameprefix,int maxSize) {try{diskfileitemfactory              Diskfactory = new Diskfileitemfactory ();            Threshold limit, critical value, i.e. HDD cache 1M Diskfactory.setsizethreshold (40 * 1024 * 1024);            String Tempath = Request.getrealpath ("/tmpfile");            File dir = new file (Tempath);            if (!dir.exists ()) {dir.mkdirs ();            } System.out.println ("Temporary folder path" +tempath);                        Repository storage room, temporary file directory diskfactory.setrepository (new file (Tempath)); ServletfIleupload upload = new Servletfileupload (diskfactory);            Upload.setheaderencoding (JvnConfig.CONSTANT.getEncoding ());              Set the maximum file size allowed to upload 4M 4 * 1024x768 * UPLOAD.SETSIZEMAX (maxSize);              Parse HTTP request message header List Fileitems = upload.parserequest (request);              Iterator iter = Fileitems.iterator ();            List<object> list =new arraylist<object> ();                  while (Iter.hasnext ()) {Fileitem item = (Fileitem) iter.next ();                      if (Item.isformfield ()) {//form contents String name = Item.getfieldname (). Trim ();                    String value = item.getstring (JvnConfig.CONSTANT.getEncoding ());                                    Parammap.put (name, value);                }else{//File contents String type = Strkit.getendtype (Item.getname (), "\ \"); Filekit.savefile (dirpath+filenameprefix+ ".") +type, Item.getinputstream ());                                }/** * Save the data to the database * * }}catch (Exception e) {e.getstacktrace (); throw new RuntimeException (e);}} /** * Get uploaded files, here need to add Commons-fileupload.jar,commons-io.jar * @param dirpath * @param fileName * @param maxSize 1024*1024 *1m * @return */public void GetFiles (String dirpath,string []filenameprefix,int maxSize) {try{diskfileitemfactory              Diskfactory = new Diskfileitemfactory ();            Threshold limit, critical value, i.e. HDD cache 1M Diskfactory.setsizethreshold (40 * 1024 * 1024);            String Tempath = Request.getrealpath ("/tmpfile");            File dir = new file (Tempath);            if (!dir.exists ()) {dir.mkdirs ();            } System.out.println ("Temporary folder path" +tempath);                       Repository storage room, temporary file directory diskfactory.setrepository (new file (Tempath));     Servletfileupload upload = new Servletfileupload (diskfactory);               Upload.setheaderencoding (JvnConfig.CONSTANT.getEncoding ());              Set the maximum file size allowed to upload 4M 4 * 1024x768 * UPLOAD.SETSIZEMAX (maxSize);              Parse HTTP request message header List Fileitems = upload.parserequest (request);              Iterator iter = Fileitems.iterator ();            List<object> list =new arraylist<object> ();            int count = 0;                  while (Iter.hasnext ()) {Fileitem item = (Fileitem) iter.next ();                      if (Item.isformfield ()) {//form contents String name = Item.getfieldname (). Trim ();                     String value = item.getstring (JvnConfig.CONSTANT.getEncoding ());                                    Parammap.put (name, value);                }else{//File contents String type = Strkit.getendtype (Item.getname (), "\ \");                if (count> (filenameprefix.length-1)) {count = 0; } FIlekit.savefile (dirpath+filenameprefix[count]+ ".")                +type, Item.getinputstream ());                                count++; }/** * Save data to Database */}}catch (E Xception e) {e.getstacktrace (); throw new RuntimeException (e);}} /** * Get the upload file, the form's normal parameters * @param attr * @return */public string getformparm (String attr) {return parammap.get (attr);}}

How to develop a Java Open source Framework-----JVN Framework implementation file upload and method encapsulation (vi) Starling strength explanation

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.