Gradle构建Java Web应用:Servlet依赖与Tomcat插件(转)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Gradle构建Java Web应用:Servlet依赖与Tomcat插件(转),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含6158字,纯文字阅读大概需要9分钟。
内容图文
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
源码
https://github.com/Dynamsoft/Dynamic-Web-TWAIN/tree/master/samples/gradle
git clone https://github.com/Dynamsoft/Dynamic-Web-TWAIN.git
http://my.oschina.net/yushulx/blog/401888
原文:http://www.cnblogs.com/softidea/p/5631587.html
内容总结
以上是互联网集市为您收集整理的Gradle构建Java Web应用:Servlet依赖与Tomcat插件(转)全部内容,希望文章能够帮你解决Gradle构建Java Web应用:Servlet依赖与Tomcat插件(转)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。