Java Servlet 在网络上的编程应用,如利用Servlet 上传和下载文件、Servlet 的数据库编程、在Servlet 中发送和接受邮件以及Java Servlet 在RMI和XML等方面的应用,由于篇幅有限,在这里就不在多介绍了,下面再举一个Servlet 上传的例子。
在Web 应用程序中,用户向服务器上传文件是非常普遍的操作。使用Servlet 实现文件的上传是比较简单的。
编程思路:下面的UploadServlet.java ,其主要功能为从InputStream 中读取文件内容,将上传文件保存在根目录下,且文件名与上传文件的文件名一致。
UploadServlet.java 的源代码如下:(代码节选)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class UploadServlet extends HttpServlet
{
//default maximum allowable file size is 1000k
static final int MAX_SIZE = 1024000;
//instance variables to store root and success message
String rootPath, successMessage;
/**
* init method is called when servlet is initialized.
*/
public void init(ServletConfig config) throws ServletException
{
super.init(config);
//get path in which to save file
rootPath = config.getInitParameter("RootPath");
if (rootPath == null)
{
rootPath = "/";
}
/*Get message to show when upload is complete. Used only if
a success redirect page is not supplied.*/
successMessage = config.getInitParameter("SuccessMessage");
if (successMessage == null)
{
successMessage = "File upload complete!";
}
}
/**
* doPost reads the uploaded data from the request and writes
* it to a file.
*/
public void doPost(HttpServletRequest request,
HttpServletResponse response)
{
ServletOutputStream out=null;
DataInputStream in=null;
FileOutputStream fileOut=null;
try
{
/*set content type of response and get handle to output
stream in case we are unable to redirect client*/
response.setContentType("text/plain");
out = response.getOutputStream();
//get content type of client request
String contentType = request.getContentType();
out.println("
contentType= " + contentType);
//make sure content type is multipart/form-data
if(contentType != null && contentType.indexOf(
"multipart/form-data") != -1)
{
//open input stream from client to capture upload file
in = new DataInputStream(request.getInputStream());
//get length of content data
int formDataLength = request.getContentLength();
out.println("
ContentLength= " + formDataLength);
//allocate a byte array to store content data
byte dataBytes[] = new byte[formDataLength];
//read file into byte array
int bytesRead = 0;
int totalBytesRead = 0;
int sizeCheck = 0;
while (totalBytesRead < formDataLength)
{
//check for maximum file size violation
sizeCheck = totalBytesRead + in.available();
if (sizeCheck > MAX_SIZE)
{
out.println("Sorry, file is too large to upload.");
return;
}
...........
...........
编程技巧说明: