"Servlet" uses Servlet3.0 Standard and JSTL expression to implement file uploading system, support image display after uploading

Source: Internet
Author: User

Along with the JDK1.6 Servlet3.0 standard, making JSP file upload system is no longer difficult, before the JSP file upload system needs "JSP" use Jspsmartupload complete a simple File upload system " (Click to open the link) like such a plugin to complete the file upload system, also does not support the Chinese language, so that you program ape empty mind to solve the problem. Now Servlet3.0 the file upload method to encapsulate, without chunking can be achieved. And Servlet3.0 not like the "servlet" simplest servlet javaweb program (click to open the link) in the Web. XML, a small annotation can complete the previous multi-line code.


I. BASIC OBJECTIVES

Implement the following file upload system, after uploading the file type, file size, filename, file suffix name, if the upload is a picture, the display, extremely robust. Probably the only drawback is that there is no progress bar ... Uploading the progress bar is also a big project, later. and the JSP page written in accordance with the MODEL2 standard, in the upload page and upload a successful display page, there is no JSP code, only the JSTL expression and JSP2.0 itself value expression. If you do not want to jump can refer to the "JSP" using Ajaxfileuploader and Jspsmartupload to complete the Ajax file upload system without refreshing (click the Open link) content.


If you directly access my upload file servlet, pop up the hint.


After uploading, the file is saved in the Server/upload folder, the server generally does not have Chinese file name, each file name is a timestamp, multi-user upload can also be taken to take the user's ID and the file name, time stamp generation can see I wrote before the "Java" Think about System.currenttimemillis () (Click to open link)



II. Basic Preparation

This web engineering directory structure, which uses the Servlet3.0 standard and the JSTL expression to implement the upload system, is as follows:


First in WebContent, if the MyEclipse is the Webroot Web site root folder, the following new upload folder, used to upload files.

The Web. xml file is created as "Javaweb" Eclipse for Java EE, which is automatically generated by XML (click the Open link), so that eclipse can build it itself without writing anything. The following is a brief example of the refinement:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-app_3_0.xsd "version=" 3.0 "></web-app>
Then the Lib folder is placed under the Servlet3.0 support package JAVAX.SERVLET-API-3.1.0.JAR,JSTL expression support Package Jstl.jar and Standard.jar, these things are JSP official development of things and tomcat like, the high version of T Omcat also comes with it, but to be compatible with all versions of Tomcat. These things can be searched on the Internet by themselves. Jstl Expression Support Package Jstl.jar and Standard.jar to go to search jakarta-taglibs-standard-1.1.2.zip, download after the decompression as shown, the lib inside the things are taken away.



Third, the production process

1, the first is the simplest, as long as the HTML will be the fileupload.jsp, on a file form, note the wording, when the front end of the time, the file form may mention, note in addition to post and action properties, there are enctype= " Multipart/form-data ", indicating that this is a transmittal file, the file form must match the server language aspx,jsp,php one of the three, running on the server only valid:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" Utf-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

2, after the Upload.java, came to the Servlet3.0, no longer have to engage in Web. XML, you can use part object to catch the entire uploaded file, add a sentence response.setcharacterencoding ("Utf-8"); Decoding can support the Chinese, if the use of interceptors to achieve global decoding, then this sentence can also be saved, you can refer to my previous "filter" Using filter filter to solve the post transmission coding problem and the use of El Expression simplified parameter passing "(click Open link), The rest is only the problem of cutting strings, in addition to set a dynamic array ArrayList with the following JSTL expression, dynamic array ArrayList do not understand can see "Java" Java Collections Class--java in the upgraded version of the data structure (Click to open the link), while the file name of the save server is a timestamp, all the content of the delivery using the request container, the container request after the message, that is, the requests container jump before the birth, jump finished page loaded, request container immediately die, specific see comments.

There's a file. Io,util is an import java.io.*;import java.util.*;import javax.servlet.*;import that sets a JSTL expression that follows a ArrayList mate Javax.servlet.http.*;import javax.servlet.annotation.*;//This setting can replace the previous Web. XML configuration servlet, but be aware of the introduction of the annotation package @ Webservlet (name= "Upload", urlpatterns={"/upload"})//This is a file-handling Servlet@multipartconfigpublic class upload extends HttpServlet {//Prevents users from entering URLs directly to access this servletprotected void doget (httpservletrequest request,httpservletresponse response) Throws Servletexception, IOException {printstream out = new PrintStream (Response.getoutputstream ()); Response.setcontenttype ("Text/html;charset=utf-8"); Out.print ("Please open this page normally");} File generally with DoPost method protected void DoPost (HttpServletRequest request,httpservletresponse response) throws Servletexception, IOException {//Decode response.setcharacterencoding ("Utf-8");//<input type= "file" with name file Name= "File"/> Inside the selected files passed over part Part=request.getpart ("file");//This will be able to take the upload file name, not why,// Content-disposition Front 35 characters is form-data file table sole name name= "file"//each uploaded file is a fixed string Filename=part.getheaDERs ("Content-disposition"). toString (). substring. replace ("\"] "," "), or//to the file name from the. Start intercept to take the suffix string Fileextensions=filename.substring (Filename.lastindexof (".")); /set a dynamic array FileInfo, keep the file information in arraylist<string> fileinfo=new arraylist<string> (); Fileinfo.add ("File type:" +part.getcontenttype ()); Fileinfo.add ("File Size:" +part.getsize ()/1024+ "KB"); Fileinfo.add ("FileName:" +filename); Fileinfo.add ("suffix name:" +fileextensions);//Set a parameter Request.setattribute ("Fileextensions", fileextensions) for the file's suffix name independently;// This is the server above the file name, the use of System.currenttimemillis () timestamp//followed by A + "" can be the Long Force ToString () the string serversfilename= System.currenttimemillis () + "";//dynamic array FileInfo also save this name on the server//for subsequent components of the image display address fileinfo.add (serversfilename); Put the dynamic array FileInfo into the container request.setattribute ("FileInfo", FileInfo);//If the file name is ending with a picture suffix// Of course, you can also fileextensions in the above with the equal method to judge//remember that the string is an object, do not use = = to compare it can be if (Filename.endswith (". jpg") | | Filename.endswith (". gif") | | Filename.endswith (". bmp") | | Filename.endswith (". png")) {//Is the request setting a property Haspic tells the next page whether the picture Request.setattribute ("Haspic", "true");} Else{request.setattribute ("Haspic", "false");} Save the file to Server Getservletcontext (). Getrealpath ("/upload") can be taken to the server/upload directory//without parameters is the root directory// After that is saved to the server's name and the file suffix name and then can be Part.write (Getservletcontext (). Getrealpath ("/upload") + "/" +serversfilename+ fileextensions);//Then jump to uploadsuccess page request.getrequestdispatcher ("/uploadsuccess.jsp") with the request container. Forward ( request,response);}}
Another thing to add is: the Part.getsize () method takes out the file size in bits, please divide yourself by 1024, or 1024 squared to convert.

3, upload the successful display page uploadsuccess.jsp, this page also shoulders the task of displaying pictures, while using the JSTL expression, remember that on this page the head declaration if the C tag, the following:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" Utf-8 "%><!--indicate that I want to use JSTL expression! --><% @taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
To do here, the whole use of Servlet3.0 standard and JSTL expression, support image upload file upload system, it is done.

Do you realize the superiority of the standard of the Model 2 of the Servlet3.0 standard and the JSTL expression?

And of course there are all kinds of ssh gods ready to squirt me ...

"Servlet" uses Servlet3.0 Standard and JSTL expression to implement file uploading system, support image display after uploading

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.