设为首页 收藏本站
查看: 956|回复: 0

[经验分享] Gradle构建Java Web应用:Servlet依赖与Tomcat插件(转)

[复制链接]

尚未签到

发表于 2017-3-2 09:58:59 | 显示全部楼层 |阅读模式
  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
DSC0000.png


源码
  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  http://my.oschina.net/yushulx/blog/401888

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-349137-1-1.html 上篇帖子: eclipse maven新建springMVC项目(原创) 下篇帖子: spring配置文件
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表