Gradle Building Java Web applications: servlet dependencies and Tomcat plugins

Source: Internet
Author: User

Gradle's official tutorial describes the basic methods for building Java Web applications. However, you will encounter problems when uploading using the servlet. Here's how to upload a file through a servlet, and how to use Gradle to build the appropriate Java Web project.

Reference original: How to Build Web scanning application with Gradle

servlet File Upload

Using the servlet file upload, you can refer to Oracle's official documentation for the FileUpload Example application. One of the issues to be aware of here is to receive multipart/form-data data, which must be stated in the servlet:

@WebServlet (name = "Fileuploadservlet", Urlpatterns = {"/upload"}) @MultipartConfig

Otherwise,GetPart () will return null. The servlet receives an upload file that can be written like this:

/* * 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"}) @ multipartconfigpublic 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 ();    &nbSp; 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 =&nBsp;filepart.getinputstream ();         int read =  0;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;FINAL&NBSP;BYTE[]&NBSP;BYTES&NBSP;=&NBSP;NEW&NBSP;BYTE[1024] ;         while  ((Read = filecontent.read (bytes)) &NBSP;!=&NBSP;-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&nBSP (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 Building Java Web Engineering

When using Gradle to build this Web project, if you follow the official document, Getpart This method is not found, the use of the dependency can be replaced by:

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

Another problem is that using the jetty plugin will also fail. Because Jetty does not support Servlet 3.0. The official forum has a reply : Unable to use Servlet 3.0 API in jetty plugin. Alternative methods can use the Gradle Tomcat plugin. In the Build.gradle file, add:

Buildscript {repositories {jcenter ()} dependencies {classpath ' Com.bmuschko:gradle-tomcat-plug in:2.1 '}} subprojects {Apply plugin: "Java" repositories {mavencentral ()}}

Then add the Tomcat plugin to the Build.gradle file of the subproject:

Apply plugin: "War" Apply plugin: ' Com.bmuschko.tomcat ' dependencies {providedcompile "javax:javaee-api:6.0" def TOMC atversion = ' 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}

Finally build the Operation project:

Gradle Buildgradle Tomcatrunwar

Source

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

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


Gradle Building Java Web applications: servlet dependencies and Tomcat plugins

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.