JavaEE-05 Paging and file upload

Source: Internet
Author: User
Tags temporary file storage

Learning Essentials
    • News Page Display data
    • News image Upload

JSP paging Displays data paging
    • More data information when the general use of the list display, easy to display information;
    • When the amount of data is large, it is usually displayed in the form of a list and page, which is easy to read.
    • Paging: Collection or session, stored procedure, SQL statement paging
Paging steps
    1. Determine the number of data displayed per page
    2. Determine the total number of pages required to display the page
    3. Write SQL query statements to implement data query
    4. Paging display settings in a JSP page
    5. Encapsulates data in a paging process, encapsulated in the page class
Implementation process
    1. Determine how much data is displayed per page: For example: 5 data per page
    2. Count the pages displayed: Use the count () function to query the number of records in the database, and to encapsulate the information in the page class by calculating the total number of pages by record count and the amount of data per page.
    3. Page class Code
/** */public class Page<t> {//Total pages private int totalpagecount = 1;//page size, which is the number of records displayed per page private int pageSize = 0;//record Total Number private int totalcount = 0;//Current page number private int currpageno = 1;//data collection per page private list<t> list;public list<t> get List () {return list;} public void setlist (list<t> list) {list = list;} public int Getcurrpageno () {if (Totalpagecount = = 0) return 0;return Currpageno;} public void Setcurrpageno (int currpageno) {if (This.currpageno > 0) This.currpageno = Currpageno;} public int Gettotalpagecount () {return totalpagecount;} public void Settotalpagecount (int totalpagecount) {this.totalpagecount = Totalpagecount;} public int getpagesize () {return pageSize;} public void setpagesize (int pageSize) {if (pageSize > 0) this.pagesize = pageSize;} public int Gettotalcount () {return totalcount;} public void Settotalcount (int totalcount) {if (TotalCount > 0) {this.totalcount = totalcount;//calculates the total number of pages Totalpagecount = t His.totalcount% PageSize = = 0? (this.totalcount/pagesize): This.totalcount/pagesize + 1;}}} 

  

JavaBean the concept : JAvaee A simple class that encapsulates data or business in a project.

Similar to page or news entity classes.

The news class implements the encapsulation of the data, the page class implements the encapsulation of the business, and none of the two classes inherit any class other than the object class or implement the interface, all attributes are encapsulated and there is no parameter construction method.

4. Designing SQL statements

MySQL Paging statement:

SELECT * FROM News ORDER by NID ASC LIMIT (pageindex-1) *pagesize,pagesize;

  

5. Number of Access layer implementations

Newsdao:

public abstract int Gettotalcount ();p ublic list<news> getpagenewslist (int pageindex,int pageSize);

  

Newsdaoimpl:

/** Get paging news information */public list<news> getpgenewslist (int pageno, int pageSize) {list<news> newslist = new ArrayList <News> (); String sql = "Select Nid,ntitle,ncreatedate from NEWS ORDER by ncreatedate desc LIMIT?,?"; O bject[] args = {(pageNo-1) * pageSize, pageSize}; ResultSet rs = this.executequery (sql, args); try {while (Rs.next ()) {int nId = Rs.getint ("Nid"); String ntitle = rs.getstring ("Ntitle"); Timestamp times = Rs.gettimestamp ("Ncreatedate"); SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String ncreatedate = Sdf.format (times);//String ncreatedate = Rs.getstring ("Ncreatedate"); News news = new News (News.setnid); News.setntitle (Ntitle); news.setncreatedate (ncreatedate); Newslist.add (News) ;}} catch (Exception e) {e.printstacktrace ();} return newslist;} /** query total number of records */public int gettotalcount () {int count = 0; Connection conn = This.getconnection (); PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT COUNT (1) from news"; try {pstmt = conN.preparestatement (sql); rs = Pstmt.executequery (); if (Rs.next ()) {count = Rs.getint (1);}} catch (SQLException e) {e.printstacktrace ();} finally {This.closeall (RS, PSTMT, conn);} return count;}

  

6. Test method

public static void Main (string[] args) {Newsdaoimpl Newsdao = new Newsdaoimpl (); int totalcount = Newsdao.gettotalcount ();P age<news> page = new page<news> ();p Age.setcurrpageno (3); Set Current page page.setpagesize (3); Set number of bars per page page.settotalcount (totalcount); Set total number of records SYSTEM.OUT.PRINTLN ("Total number of news is:" + page.gettotalcount ()); System.out.println ("Number of bars per page:" + page.getpagesize ()); System.out.println ("Total pages:" + Page.gettotalpagecount ()); System.out.println ("Current is the first" + Page.getcurrpageno () + "page:"); list<news> newslist = newsdao.getpgenewslist (Page.getcurrpageno (), Page.getpagesize ());p age.setlist (newsList );//Set the collection displayed per page for (News news:page.getList ()) {System.out.println (News.getnid () + "\ T" + news.getntitle () + "\ T" + NEWS.G Etncreatedate ());}}

 

7.JSP page Information page control code

Current page: [<%=pageindex%>/<%=totalpages%>]     <%    if (PageIndex > 1) {//control page display style%>         <a href= "Pagecontrol.jsp?pageindex=1" > Home </a>       <a href= "pagecontrol.jsp?pageindex=<%= pageindex-1% > > Previous </a>   <%}       if (PageIndex < totalpages) {//control page display style   %>       <a href= " pagecontrol.jsp?pageindex=<%= pageIndex +1%> "> Next </a>       <a href=" pagecontrol.jsp?pageindex= <%=totalpages%> > Last </a>    <%}%>   

  

8. Information Processing page reference code

String PageIndex = Request.getparameter ("PageIndex");//Gets the current page    if (PageIndex = = null) {        PageIndex = "1";    }    int currpageno = Integer.parseint (pageIndex);    Newsdaoimpl Newsdao = new Newsdaoimpl ();    int totalcount = Newsdao.gettotalcount ();//Get total Record Count    page<news> pages = new page<news> ();    Pages.setpagesize (3); Set number of bars per page    pages.settotalcount (totalcount);//Set total records    int totalpages = Pages.gettotalpagecount ();    /* Control of the first and last page */    if (Currpageno < 1) {        Currpageno = 1;    } else if (Currpageno > Pages.gettotalpagecount ()) {        Currpageno = totalpages;    }    Pages.setcurrpageno (Currpageno); Set Current page    list<news> newslist = newsdao.getpgenewslist (Pages.getcurrpageno (), pages.getpagesize ());    Pages.setlist (newslist); Sets the collection    Request.setattribute ("pages", pages) displayed per page, Request.getrequestdispatcher ("index.jsp"). Forward (Request , response);

  

On-machine exercise: Realizing news pagination display

Requirements Description

Write code to achieve the first page of the news title pagination display, the need to be able to perform the first page, the next page, previous pages, the end of the operation, and display the total number of pages and the current page

Implementation ideas

    • Determine the number of news displayed per page
    • Writing database access classes, declaring query methods
    • Writing SQL statements
    • Writing JavaBean wrapper paging information (page class)
    • Calling JavaBean in the JSP

Uploading file requirements using Commons-fileupload

In Web applications, it is often necessary to upload files to the server. Upload File page code:

<form action= "doupload.jsp" enctype= "Multipart/form-data" method= "POST" ><p> Name: <input type= "Text" Name= "User" ></p><p> Select Picture: <input type= "file" Name= "nfile" ></p><p><input type= " Submit "Value=" ></p></form>

  

The form to upload the file, you need to note two points:

1, set the Enctype property, the value must be multipart/form-data

2, the form must be submitted in the way of post

Uploading a file component
    • Commons-fileupload components can be easily embedded in the JSP file, in the JSP file to write only a small amount of code to complete the file upload function, very convenient.
    • Be able to control the upload content: You can get all the uploaded file information, including file name, type, size, etc., convenient operation.
    • The ability to control the size and type of uploaded files: In order to avoid abnormal data during the uploading process, the Commons-fileupload component is specifically provided with the appropriate method for controlling the uploaded files.

How to get commons-fileupload components
    • Http://commons.apache.org/fileupload Download Commons-fileupload Components

Commons-fileupload Component Class Library: Commons-fileupload-1.3.2.jar

API documentation for COMMONS-FILEUPLOAD components: Apidocs

    • Http://commons.apache.org/io Download Commons-io Components

Commons-io Component Class Library: Commons-io-2.5.jar

API documentation for COMMONS-IO components: Commons-io-2.5\docs

API for Commons-fileupload Components
    • Common methods of Servletfileupload class

Method name

Method description

public void Setsizemax (long s Izemax)

Set the maximum allowable number of bytes for request information entity content

Public List parserequest (httpservletrequest req )

Parses the data for each character in the form form, returning a collection of Fileitem objects

public static final Boolean Ismultipartcontent (httpservletrequest req )

Determine if the content in the request message is " Multipart/form-data "type

public void setheaderencoding (String enc oding)

Set the character set encoding to use when converting

    • Common methods of Fileitem interface

Method name

Method description

public boolean Isformfield ()

Determine the type of data encapsulated by the Fileitem object (normal form fields return true, File form fields return false)

Public String GetName ()

Get the file name in the File upload field (normal form field returns NULL)

Public String GetFieldName ()

Returns the Name property value of a form field element

public void Write ()

Saves the principal content in the Fileitem object to the specified file

Public String getString ()

Returns the principal content saved in the Fileitem object as a string. Its overloaded method public parameter in the public string getString (string encoding) is encoded using the specified character set

Public long GetSize ()

Returns the number of bytes of a single uploaded file

    • Fileitemfactory interface and Implementation class

Implementation class: Defaultfileitemfactory, Diskfileitemfactory

Method name

Method description

public void Setsizethreshold (int sizethreshold)

To set the size of a memory buffer

public void Setrepositorypath (String path)

Set the directory where temporary files are stored

Implementation of File Upload
    • Implementation steps
Create Fileitemfactory object//Create Servletfileupload object//Parse all files in form form if (normal form field) {  //Get form Field's Name property value if (this property is "user") {// Output xxx uploaded the file}}else{   

  

    • Sample code
<% @page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><% @page import= "Java.io.File"%>< % @page import= "Org.apache.commons.fileupload.FileItem"%><% @page import= " Org.apache.commons.fileupload.FileItemFactory "%><% @page import=" Org.apache.commons.fileupload.disk.DiskFileItemFactory "%><% @page import=" Org.apache.commons.fileupload.servlet.ServletFileUpload "%><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/";%&GT;&L T;%request.setcharacterencoding ("Utf-8"); String uploadfilename = ""; File name of the upload string fieldName = ""; The name attribute value of the form field element//whether the content in the request information is multipart type Boolean ismultipart = servletfileupload.ismultipartcontent (request);// The storage path of the uploaded file (absolute file path on the server file system) String Uploadfilepath = Request.getsession (). Getservletcontext (). Getrealpath ("upload/") ; if (Ismultipart) {Fileitemfactory factory = new Diskfileitemfactory (); Servletfileupload upload = new ServletFileUpload (factory); try {//parse all files in form form list<fileitem> items = upload.parserequest (Request);iterator< Fileitem> iter = Items.iterator (); while (Iter.hasnext ()) {//process each file sequentially Fileitem item = (Fileitem) iter.next (); if (item.i Sformfield ()) {//normal form field fieldName = Item.getfieldname ();//The name attribute value of the form field if (Fieldname.equals ("user")) {// The value of the Output form field out.print (item.getstring ("UTF-8") + "uploaded the file. <br/> ");}}  else {//File form field string fileName = Item.getname (); if (fileName! = null &&!filename.equals ("")) {File FullFile = new File (Item.getname ()); File SaveFile = new file (Uploadfilepath,fullfile.getname ()); Item.write (saveFile); uploadfilename = Fullfile.getname () ; Out.print ("The file name after successful upload is:" + uploadfilename); Out.print ("<br> File Save absolute Path is:" +savefile.getpath ()); Out.print ("< br> File Save relative path is: "+" upload\\ "+uploadfilename);}}} catch (Exception e) {e.printstacktrace ();}} %>

  

On-Machine Practice requirements Description

Add image function to complete news release information

Implementation ideas

1. Add Commons-fileupload.jar and Commons-io-2.5.jar

2. Import the Commons-fileupload class using the page directive in the JSP file

3. Call the Commons-fileupload component-related class method to obtain the file information and implement the Save

Control the properties of the uploaded file to control the type of file upload

Code Framework

List<string> filtype=arrays.aslist ("gif", "BMP", "JPG"); String ext=filename.substring (Filename.lastindexof (".") +1) if (!filtype.contains (EXT)) {  //Determine if the file type is within the allowable range    out.print ("Upload failed, file type can only be GIF, BMP, JPG");} else{     //upload file}

  

Control the size of file uploads

Code Framework

Servletfileupload upload = new Servletfileupload (factory);//Set maximum limit for individual files Upload.setsizemax (1024*30); try {//... Omit upload code}catch (fileuploadbase.sizelimitexceededexception ex) {    out.print ("Upload failed, file is too large, the maximum limit for individual files is:" +    Upload.getsizemax () + "bytes!");

  

Complete code example
<% @page import= "org.apache.commons.fileupload.FileUploadBase"%><% @page language= "java" import= "Java.util . * "pageencoding=" UTF-8 "%><% @page import=" Java.io.File "%><% @page import=" Org.apache.commons.fileupload.FileItem "%><% @page import=" org.apache.commons.fileupload.FileItemFactory "% ><% @page import= "org.apache.commons.fileupload.disk.DiskFileItemFactory"%><% @page import= " Org.apache.commons.fileupload.servlet.ServletFileUpload "%><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/";%&GT;&L T;%request.setcharacterencoding ("Utf-8"); String uploadfilename = ""; File name of the upload string fieldName = ""; The name attribute value of the form field element//whether the content in the request information is multipart type Boolean ismultipart = servletfileupload.ismultipartcontent (request);// The storage path of the uploaded file (absolute file path on the server file system) String Uploadfilepath = Request.getsession (). Getservletcontext (). Getrealpath ("upload/") ;//create temporary file directory path file Temppatchfile = new FiLe ("d:\\temp\\buffer\\"); if (!temppatchfile.exists ())//Determine if the file or directory exists temppatchfile.mkdirs (); Creates the specified directory, including all required but nonexistent parent directories if (Ismultipart) {Diskfileitemfactory factory = new Diskfileitemfactory ();// Set buffer size 4kbfactory.setsizethreshold (4096);//Set upload file for temporary file storage path Factory.setrepository (temppatchfile); Servletfileupload upload = new Servletfileupload (factory);//Set maximum limit for individual files Upload.setsizemax (1024x768 *); try {// Parse all files in form form list<fileitem> items = upload.parserequest (request);iterator<fileitem> iter = Items.iterator (); while (Iter.hasnext ()) {//process each file sequentially Fileitem item = (Fileitem) iter.next (); if (!item.isformfield ()) {// File form field String filename = Item.getname ();//create a fixed-length collection list<string> Filtype = Arrays.aslist by the Aslist () method of the Arrays class (" GIF "," BMP "," JPG "); String ext = filename.substring (Filename.lastindexof (".") + 1); if (!filtype.contains (EXT))//Determine if the file type is within the allowable range Out.print ( "Upload failed, file type can only be GIF, BMP, JPG"), else {if (FileName = null &&!filename.equals ("")) {file FullFile = new file (item.get Name ()); File SaveFile = new File (Uploadfilepath,fullfile.getname ()); Item.write (saveFile); uploadfilename = Fullfile.getname (); O Ut.print ("file name after successful upload is:" + uploadfilename+ ", File size is:" + item.getsize () + "bytes!");}}}} catch (Fileuploadbase.sizelimitexceededexception ex) {out.print ("The upload failed, the file is too large, the maximum limit for a single file is:" + upload.getsizemax () + " Bytes! ");} catch (Exception e) {e.printstacktrace ();}} %>

  

On-Machine Practice requirements Description
    • Administrators can upload news images at the same time when publishing news
    • The types of images allowed are: GIF files, JPG files, JPEG files, PNG files
    • The size of the uploaded image cannot exceed 5MB to complete the add image function of news release information
    • The administrator selects a news item, clicks the Edit link, and displays this news item on the news editor page.
    • After editing the news content, click the Submit button to update the news.
On-Machine Practice requirements Description
    • The administrator selects a news item, clicks the Edit link, and displays this news item on the news editor page.
    • After editing the news content, click the Submit button to update the news.

JavaEE-05 Paging and file upload

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.