Black Horse DAY15 Imitation net disk case

Source: Internet
Author: User
Tags map class

Project Description:

This project is mainly to complete the file upload and download the function of a comprehensive case.

1. Build the environment ...

Importing jar packages and developing tool classes ...

Jar Package:

Two tool classes are available: One is ioutils mainly provides the docking of the output stream and the input stream, and the function of closing the stream resource

One is the tool class that provides the data source Datasourceutils

Ioutils:

Package Cn.itheima.utils;import Java.io.ioexception;import Java.io.inputstream;import java.io.OutputStream;public Class Ioutils {private Ioutils () {}/** * reads the data in the stream into the output stream * @param in * @param out * @throws ioexception */public static void In2out (InputStream In,outputstream out) throws Ioexception{int Len=0;byte b[]=new byte[1024];while ((Len=in.read (b))! = -1) {out.write (b, 0, Len);}} /** * Close Resource * @param in * @param out */public  static void Closeio (InputStream in,outputstream off) {if (in!=null) {try {in . Close ();} catch (IOException e) {e.printstacktrace ();} Finally{in=null;}} if (out!=null) {try {out.close ();} catch (IOException e) {e.printstacktrace ();} Finally{out=null;}}}}
Datasourceutils:

Package Cn.itheima.utils;import Java.sql.connection;import Java.sql.sqlexception;import Javax.sql.DataSource; Import Com.mchange.v2.c3p0.combopooleddatasource;public class Datasourceutil {private static DataSource Source = new Combopooleddatasource ();p rivate datasourceutil () {}public static DataSource GetSource () {return source;} public static Connection Getconn () {try {return source.getconnection ();} catch (SQLException e) {e.printstacktrace (); throw new RuntimeException (e);}}
2. Prepare the database:

Create Database day15;
Use DAY15;
CREATE TABLE Netdisk (
ID int primary KEY auto_increment,
Uuidname varchar (255),
Realname varchar (255),
Savepath varchar (255),
IP varchar (100),
Uploadtime timestamp,
Description varchar (255)
);

Configuration file C3p0-config.xml

<?xml version= "1.0" encoding= "UTF-8"?><c3p0-config>  <default-config>    <property name= "Driverclass" >com.mysql.jdbc.Driver</property>    <property name= "Jdbcurl" >jdbc:mysql:// localhost:3306/day15?generatesimpleparametermetadata=true</property>    <property name= "user" >root </property>    <property name= "password" >169500</property>  </default-config></ C3p0-config>


3. Prepare the JavaBean class resource (to ensure consistency with the attributes in the database)

Package Cn.itheima.domain;import Java.io.serializable;import Java.sql.timestamp;public class Resource implements serializable{private int id;private String uuidname;//The name of the uploaded file, the file's UUID name private String realname;//file upload real name private String savepath;//file upload location private Timestamp uploadtime;//File upload time private string ip;//the IP address of the person who uploaded the file private string Description information for the description;//file public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String Getuuidname () {return uuidname;} public void Setuuidname (String uuidname) {this.uuidname = Uuidname;} Public String Getrealname () {return realname;} public void Setrealname (String realname) {this.realname = Realname;} Public String Getsavepath () {return savepath;} public void Setsavepath (String savepath) {this.savepath = Savepath;} Public Timestamp Getuploadtime () {return uploadtime;} public void Setuploadtime (Timestamp uploadtime) {this.uploadtime = Uploadtime;} Public String GetIP () {return IP;} public void setIp (String IP) {this.ip = IP;} Public String GetDescRiption () {return description;} public void SetDescription (String description) {this.description = description;}}
4. Build the main page of the project: provide two hyperlinks: File upload hyperlink-->upload.jsp, File download list hyperlink--

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >


5. Develop the load.jsp upload file page:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >




6. Development of the Servlet class Uploadservlet (need to establish the Temp temporary folder in the Web-inf directory and the folder where the upload upload file is located)

(1). Steps to upload a file

(2). Encapsulates the obtained data into an object in the resource ... The beanutils is used here.

(3). Add data to the database ...

(4). Redirect to homepage ...

Attention:

The path saved to the database is not the full path but the path after the hard drive path is intercepted ...

Encapsulating data does not get all the data, so build a map class to encapsulate the data yourself ...

Here is the Hashcode folder store ...

Package Cn.itheima.web;import Java.io.file;import Java.io.fileoutputstream;import java.io.ioexception;import Java.io.inputstream;import Java.io.outputstream;import Java.util.hashmap;import Java.util.List;import Java.util.map;import Java.util.uuid;import Javax.servlet.servletexception;import Javax.servlet.http.HttpServlet; Import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Javax.sql.datasource;import Org.apache.commons.dbutils.queryrunner;import Org.apache.commons.dbutils.handlers.beanlisthandler;import Org.apache.commons.fileupload.fileitem;import Org.apache.commons.fileupload.disk.diskfileitemfactory;import Org.apache.commons.fileupload.servlet.servletfileupload;import com.sun.org.apache.commons.beanutils.BeanUtils; Import Cn.itheima.domain.resource;import Cn.itheima.utils.datasourceutil;import Cn.itheima.utils.ioutils;public Class Uploadservlet extends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response)Throws Servletexception, IOException {Map map=new HashMap (); String ip= request.getremoteaddr (); Map.put ("IP", IP); try {//1. File Upload Factory class Diskfileitemfactory factory = new Diskfileitemfactory (); Factory.setsizethreshold (1024x768 *); Factory.setrepository (new File) This.getservletcontext (). Getrealpath ("Web-inf/temp"));//2. The core class of file upload servletfileupload fileUpload = new Servletfileupload (Factory); Fileupload.setfilesizemax (1024 * 1024 * 100);//Set the size of a single file Fileupload.setfilesizemax (1024 * 1024 * 300);//Set the total file size fileupload.setheaderencoding ("Utf-8");//solve the problem of Chinese garbled//3. Determine the type of form if (! Fileupload.ismultipartcontent (Request)) {throw new RuntimeException ("Please use the correct form type");} --Parse requestlist<fileitem> list = fileupload.parserequest (request),//--traverse for (Fileitem item:list) {if ( Item.isformfield ()) {//normal field string name = Item.getfieldname (); String value = item.getstring ("Utf-8"); Map.put (name, value);} else{//file Upload field string realname = Item.getname (); Map.put ("Realname", realname); String Uuidname=uuid.randomuuid () + "_" +Realname;map.put ("Uuidname", uuidname); String str = integer.tohexstring (Uuidname.hashcode ()); String Path=this.getservletcontext (). Getrealpath ("Web-inf/upload"); String Savepath = "/web-inf/upload"; for (char C:str.tochararray ()) {path+= "/" +c;savepath+= "/" +C;} Map.put ("Savepath", Savepath);//--creates a folder new File (path). Mkdirs (); InputStream In=item.getinputstream (); outputstream Out=new FileOutputStream (New File (Path,uuidname)); Ioutils.in2out (in, out); Ioutils.closeio (in, out); Item.delete (); /delete temporary files}}//2.//--encapsulated data in the database Resource r=new Resource (); Beanutils.populate (R,MAP); Queryrunner runner=new Queryrunner (Datasourceutil.getsource ()); String sql= "INSERT into netdisk values (null,?,?,?,?, null,?)"; Runner.update (Sql,r.getuuidname (), R.getrealname (), R.getid (), R.getsavepath (), r.getdescription ());//3. Redirect Back to homepage Response.sendredirect (Request.getcontextpath () + "/index.jsp");} catch (Exception e) {throw new RuntimeException ();}} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {doget (request, Response);}} 
7. Return to homepage ... Development Downloadlistservlet

(1). Database query data encapsulated into the list collection

(2). Put the list in the Request field ... Used to display in the list:

(3). Request forward to list.jsp

Package Cn.itheima.web;import Java.io.ioexception;import Java.sql.sqlexception;import java.util.List;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Javax.sql.DataSource; Import Org.apache.commons.dbutils.queryrunner;import Org.apache.commons.dbutils.handlers.beanlisthandler;import Cn.itheima.domain.resource;import Cn.itheima.utils.datasourceutil;public class Downloadlistservlet extends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {//1. Query database Queryrunner runner=new queryrunner (Datasourceutil.getsource ()); String sql= "SELECT * from Netdisk"; List list=null;try {list=runner.query (SQL, New Beanlisthandler<resource> (Resource.class));} catch ( SQLException e) {e.printstacktrace ();} Request.setattribute ("list", list), Request.getrequestdispatcher ("/list.jsp"). Forward (request, response);} PuBlic void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {doget ( request, response);}}
8. Develop list.jsp to traverse the data in list ...

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><%@ taglib uri= "http://java.sun.com/jsp /jstl/core "prefix=" C "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >




9. Develop Downloadservlet (note that the path to download is to be spliced.) Because the path that is stored in the database is web-inf/upload ....)

(1). Get ID

(2). Querying the database by id ... Get JavaBean.

(3). Follow the steps in the download to write the code ...

(4). Redirect to download list page

Package Cn.itheima.web;import Java.io.fileinputstream;import Java.io.fileoutputstream;import java.io.IOException; Import Java.io.inputstream;import java.io.outputstream;import java.net.urlencoder;import java.sql.SQLException; Import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Javax.sql.DataSource; Import Org.apache.commons.dbutils.queryrunner;import Org.apache.commons.dbutils.handlers.beanhandler;import Cn.itheima.domain.resource;import Cn.itheima.utils.datasourceutil;import Cn.itheima.utils.ioutils;public Class Downloadservlet extends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {//1. Gets the idstring id = request.getparameter ("id") of the downloaded file; Resource R=null; String sql= "SELECT * from Netdisk where id=?"; Queryrunner runner=new Queryrunner (Datasourceutil.getsource ()); try {r=runner.query (SQL, new BeanhaNdler<resource> (Resource.class), id); Response.setheader ("Content-disposition", "attchment;filename=" + Urlencoder.encode (R.getrealname (), "Utf-8")), Response.setcontenttype (This.getservletcontext (). GetMimeType ( R.getrealname ())); String Path=r.getsavepath (); String Savepath=this.getservletcontext (). Getrealpath (path+ "/" +r.getuuidname ()); InputStream in=new FileInputStream (Savepath); OutputStream Out=response.getoutputstream (); Ioutils.in2out (in, out); Ioutils.closeio (in, out); Response.sendredirect (Request.getcontextpath () + "/list.jsp");} catch (SQLException e) {e.printstacktrace ();}} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Doget (request, Response);}}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Black Horse DAY15 Imitation net disk case

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.