问题
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:
- build everything via the command line
- 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