Docsity

Advanced Java Servlets: File Upload and Download, Study notes of Software Engineering

Toggle sidebar
bg1
1
Advanced Java Servlets
Ye Wu
http://www.ise.gmu.edu/~wuye/
SWE 642
Software Engineering for the World Wide Web
sources: Java for the Web with Servlets, JSP and EJB, Kurniawan,
New Riders
Professional Java Server Programming, Patzer, Wrox
2006-2-27 Ā© Dr. Wu and Dr. Offutt 2
HttpServletRequest Interface
• Methods for request parameter
getParameter(), getParameterValues(), getParameterName()
• Methods for request attributes
getAttribute(), getAttributeNames(), setAttribute(), removeAttribute()
• Methods for input
getInputStream(), getReader()
• Methods for request path and URL
getPathInfo(), getPathTranslated(), getQueryString() getRequestURI(),
getServletPath() HelloRequest.java
• Methods for HTTP header
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Advanced Java Servlets: File Upload and Download and more Study notes Software Engineering in PDF only on Docsity!

Advanced Java Servlets

Ye Wu

http://www.ise.gmu.edu/~wuye/

SWE 642 Software Engineering for the World Wide Web

sources: Java for the Web with Servlets, JSP and EJB, Kurniawan, New Riders Professional Java Server Programming, Patzer, Wrox

2006-2-27 Ā© Dr. Wu and Dr. Offutt 2

HttpServletRequest Interface

  • Methods for request parameter

getParameter(), getParameterValues(), getParameterName()

  • Methods for request attributes

getAttribute(), getAttributeNames(), setAttribute(), removeAttribute()

  • Methods for input

getInputStream(), getReader()

  • Methods for request path and URL

getPathInfo(), getPathTranslated(), getQueryString() getRequestURI(), getServletPath() HelloRequest.java

  • Methods for HTTP header

2006-2-27 Ā© Dr. Wu and Dr. Offutt 3

File Upload to Servlets

  • Client Side

    • File to upload
  • When you submit, what is the real content Content-type: multipart/form-data, boundary=AaB03x

--AaB03x content-disposition: form-data; name="field1"

Joe Blow --AaB03x content-disposition: form-data; name="pics"; filename="file1.txt" Content-Type: text/plain

... contents of file1.txt ... FileLoad.java & FileUpload.java --AaB03x--

http://www.ietf.org/rfc/rfc1876.txt

2006-2-27 Ā© Dr. Wu and Dr. Offutt 4

File Upload to Servlets

  • Server-side
    • Get data length and data in = new DataInputStream(req.getInputStream()); int formDatalength = req.getContentLength(); byte dataByte[] = new byte[formDatalength]; dataByte[totalBytesRead] = in.readByte();
    • Get boundary String contentType = req.getContentType(); int lastIndex = contentType.lastIndexOf("="); String boundary = contentType.substring(lastIndex+1, contentType.length());
    • Get file name and content pos = file.indexOf("filename=""); pos = file.indexOf("\n", pos) + 1;

2006-2-27 Ā© Dr. Wu and Dr. Offutt 7

File Upload to Servlets

Apache Commons FileUpload Module

• Process the uploaded items

Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { name = item.getFieldName(); value = item.getString();} else { name = item.getFieldName(); filename = item.getName(); formDatalength = item.getSize(); File uploadedFile = new File("test_file"); item.write(uploadedFile);} }

2006-2-27 Ā© Dr. Wu and Dr. Offutt 8

HttpServletResponse Interface

• Method for content type and length

setContentType(), setContentLength()

• Method for output

getOutputStream(), getWriter()

• Method for buffered output

• setBufferSize(), getBufferSize(), flushBuffer(),

isCommitted()

• sendRedirect() method

2006-2-27 Ā© Dr. Wu and Dr. Offutt 9

Use Pre-Encoded Characters

Byte

Char

Char

Byte

byte byte byte

byte Char byte

2006-2-27 Ā© Dr. Wu and Dr. Offutt 10

Use Encoded Characters

res.setContentType(text/plain);

PrintWriter out = res.getWriter();

Reader in = new BufferedReader(new FileReader(ā€œaaā€));

char[] buf = new char[4096];

int count;

While (count=in.read(buf)) != -1) {

out.write(buf,0,count);

2006-2-27 Ā© Dr. Wu and Dr. Offutt 13

Download files

Another solution

Static files

  • Password protection - .htaccess
    • Create .htaccess file AuthUserFile /home/u3/wuye/passwd/.htpasswd AuthName "Welcome to the htaccess test page" AuthType Basic require valid-user
    • Create .htpasswd file
      • htpasswd command
      • Web htpasswd generator (http://www.euronet.nl/~arnow/htpasswd/)

2006-2-27 Ā© Dr. Wu and Dr. Offutt 14

Download Files with Servlets

Step1: set response’s content type to:

  • Application/pdf - pdf files
  • Application/msword – Microsoft word document
  • Image/gif – Gif files

Step2: Add an HTTP response header named

Content-disposition (RFC 2183)

Step3: Set data to the client

2006-2-27 Ā© Dr. Wu and Dr. Offutt 15

Download Files with Servlets

res.setContentType("APPLICATION/PDF"); //res.setContentType("APPLICATION/X-DOWNLOAD"); OutputStream out = res.getOutputStream(); String fname = "d:/a.pdf"; res.setHeader("Content-Disposition", "attachement; filename=a.pdf"); FileInputStream fis = new FileInputStream(fname); int i; while ((i=fis.read()) != -1) { out.write(i); } out.flush(); fis.close(); out.close();

2006-2-27 Ā© Dr. Wu and Dr. Offutt 16

Download Files through Firewall

URL url = new URL ( fileURL ); URLConnection conn = url.openConnection();

String authentication = "Basic " + new sun.misc.BASE64Encoder().encode("username:password".getBytes());

System.getProperties().put("proxySet", "true"); System.getProperties().put("proxyHost", PROXY_HOST); // your proxy host System.getProperties().put("proxyPort", PROXY_PORT); // your proxy port conn.setRequestProperty("Proxy-Authorization", authentication); BufferedInputStream bis = new BufferedInputStream(url.openStream());

2006-2-27 Ā© Dr. Wu and Dr. Offutt 19

Web Resources For Image Processing

  • Images Counters

http://www.vineburg.com.au/FreeHitCounters.htm

  • Gif Editor

Agifed95(shareware)

Advanced GIF Optimizer(15 uses trial version)

---- There are tons of similar stuff on web, this is just something I’m using

2006-2-27 Ā© Dr. Wu and Dr. Offutt 20

Web Resources For Image Processing

  • Acme GIF Encoder

Download file http://www.acme.com/resources/classes/Acme.tar.gz Unzip the file; Create a jar file by using the following command: Jar cf acme.jar …directoryname… Add the acme.jar file into your CLASSPATH

  • Java Advanced Imaging

http://java.sun.com/products/java-media/jai/index.jsp

2006-2-27 Ā© Dr. Wu and Dr. Offutt 21

Server Push - Only work for NN

  • Return several pages or even with different

content types(Follow the format of rfc1876)

Define the content type as:

Response.setContentType(ā€œmultipart/x-mixed- replace;boundary=Endā€);

Define the head of one part:

Out.println(ā€œContent-Type: ā€ + countentType); Outprintln();

Define the content of a part:

…out.println();

Define the end of a part:

Out.println(ā€œ--Endā€); ServerPush.java

2006-2-27 Ā© Dr. Wu and Dr. Offutt 22

Waiting Page

  • Waiting page

Refresh Interval

Refresh until it’s ready

  • Define a processing servlet or JSP page

Wait.java