Trying to build from the command line, and produce a WAR file

拟墨画扇 提交于 2019-12-01 07:44:15

问题


My folder layout is:

/web-inf/web.xml
/web-inf/classes/

HelloWorld.java:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet{ 
  public void doGet(HttpServletRequest request, 
  HttpServletResponse response)
  throws ServletException,IOException{
  response.setContentType("text/html");
  PrintWriter pw = response.getWriter();
  pw.println("<html>");
  pw.println("<head><title>Hello World</title></title>");
  pw.println("<body>");
  pw.println("<h1>Hello World</h1>");
  pw.println("</body></html>");
  }
}

I want to do the following:

  1. build everything via the command line
  2. publish to Tomcat's webapps directory using a .war file

Where should I put my HelloWorld.java file, and how to compile it using the command line? I believe the output of the HelloWorld.java goes in the /classes/ folder.

Then how do I generate the .war file?

I tried just manually compiling like this:

javac HelloWorld.java

And I got errors relating to the imports i.e. it couldn't find the libraries in my path. Is there a Java EE library I have to download and add it to my path?


回答1:


Your code depends on the servlet API which is not in the core Java library. You will need to add it to your classpath:

javac -classpath $TOMCAT_HOME/lib/servlet-api.jar yourpackage/HelloWorld.java

WARs share the same file format as JARs (ZIP with UTF-8 filenames.) Generally, you can use ZIP utilities to work with them.

A WAR structure might look like this:

index.html
foo.jsp
WEB-INF/classes/yourpackage/HelloWorld.class
WEB-INF/web.xml

The above assumes you have a package yourpackage; declaration in your .java file. The default package should be avoided.




回答2:


If this is just a toy project it may not be worth your while, but I suggest that you adopt a serious build tool as keeping track of all the libraries you need is soon going to become an unmanageable task. The one I use is Maven, but there are alternatives.




回答3:


You must to use jar command and to add dependencies to classpath



来源:https://stackoverflow.com/questions/7928654/trying-to-build-from-the-command-line-and-produce-a-war-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!