Gradle的官方tutorial介绍了构建Java Web应用的基本方法。不过在使用Servlet做上传的时候会碰到问题。这里分享下如何通过Servlet上传文件,以及如何使用Gradle来构建相应的Java Web工程。

参考原文:​​How to Build Web Scanning Application with Gradle​

Servlet文件上传

使用Servlet文件上传,可以参考Oracle的官方文档​​The fileupload Example Application​​。这里需要注意的一个问题就是要接收multipart/form-data数据,在Servlet中必须申明:

@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig

不然,getPart()会返回空。Servlet接收上传文件可以这样写:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package com.dynamsoft.upload;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet(name = "DWTUpload", urlPatterns = {"/DWTUpload"})
@MultipartConfig
public class DWTUpload extends HttpServlet {
private final static Logger LOGGER =
Logger.getLogger(DWTUpload.class.getCanonicalName());
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");

// Create path components to save the file
final Part filePart = request.getPart("RemoteFile");
final String fileName = getFileName(filePart);

OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();

String realPath = getServletContext().getRealPath("/");
if (realPath == null)
realPath = "f:\\web_upload"; // modify the default uploading dir accordingly

String uploadPath = realPath + File.separator + "upload";

File uploadDir = new File(uploadPath);
if (!uploadDir.exists())
uploadDir.mkdir();

try {
out = new FileOutputStream(new File(uploadPath + File.separator
+ fileName));
filecontent = filePart.getInputStream();

int read = 0;
final byte[] bytes = new byte[1024];

while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
writer.println("New file " + fileName + " created at " + uploadPath);
LOGGER.log(Level.INFO, "File{0}being uploaded to {1}",
new Object[]{fileName, uploadPath});
} catch (FileNotFoundException fne) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
writer.println("<br/> ERROR: " + fne.getMessage());

LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}",
new Object[]{fne.getMessage()});
} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}

private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

}

Gradle构建Java Web工程

在使用Gradle构建这个Web工程的时候,如果按照官方文档,getPart这个方法是找不到的,用到的依赖可以换成:

dependencies {
providedCompile "javax:javaee-api:6.0"
}

另外一个问题就是使用jetty插件了,同样会失败。因为jetty不支持Servlet 3.0。官方论坛里有回复: ​​Unable to use servlet 3.0 api in jetty plugin​​​。替代方法可以使用​​Gradle Tomcat plugin​​ 。在build.gradle文件中添加:

buildscript {
repositories {
jcenter()
}

dependencies {
classpath 'com.bmuschko:gradle-tomcat-plugin:2.1'
}
}

subprojects {
apply plugin : "java"
repositories {
mavenCentral()
}
}

然后在子工程的build.gradle文件中添加tomcat插件:

apply plugin: "war"
apply plugin: 'com.bmuschko.tomcat'

dependencies {
providedCompile "javax:javaee-api:6.0"

def tomcatVersion = '7.0.59'
tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}",
"org.apache.tomcat.embed:tomcat-embed-logging-juli:${tomcatVersion}",
"org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}"
}

tomcat {
httpPort = 8080
httpsPort = 8091
enableSSL = true
}

最后构建运行工程:

gradle build
gradle tomcatRunWar

Gradle构建Java Web应用:Servlet依赖与Tomcat插件(转)_Gradle    Java Web

源码

​https://github.com/Dynamsoft/Dynamic-Web-TWAIN/tree/master/samples/gradle​

git clone https://github.com/Dynamsoft/Dynamic-Web-TWAIN.git

 

​http://www.codepool.biz/gradle/how-to-build-web-scanning-application-with-gradle.html​