Compiling a simple hello world servlet in .war for tomcat

I am doing some simple tests and I want to create a simple servlet that displays the world hello, I have this part:

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>"); } } 

Now I installed with the installation of tomcat by default in the folder:

... / libexec / WebApps / ROOT

I believe that I need to drop the war file, is it possible to compile the above java class into a .war file without an editor and use it only using the command line?

+4
source share
1 answer

A war file is just a zip file, so with the appropriate directory structure and web.xml, you can create it using command line tools.

Web.xml should contain at least a way to redirect your URL to your servlet.

 <web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http:/java.sun.com/dtd/web-app_2_3.dtd"> <servlet> <servlet-name>HelloWorldServlet</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorldServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> 

This web.xml file should be in a folder named WEB-INF inside your war, and the compiled java-class file should be in WEB-INF/classes

The war file should be deleted in the webapps directory, and not in the ROOT directory.

Tomcat will find your war file and unzip it.

If it was named "hello.war", the default context name will be "hello" and is available at http://yourhost/hello/

+5
source

All Articles