Not Able to Upload Java or Tomcat Cookbook

Tomcat is a very popular spider web server for hosting Coffee web applications. In contrast to a typical evolution scenario in which you deploy your Java web applications on a standalone Tomcat instance, you can integrate the server runtime directly within your applications, resulting in some interesting, user-friendly means of using Tomcat.

In this article, we volition share with y'all some ways of embedding Tomcat server into Java applications.

Tabular array of Content:

ane. Why Using Embedded Tomcat? Maven Dependencies for Embedded Tomcat

two. Maven Dependencies for Embedded Tomcat

three. The Tomcat Embed API

4. Embedding Tomcat server for a Programmatic Coffee Web Awarding

5. Using Embedded Tomcat server for a WAR File

half dozen. Embedding Tomcat server for an Existing Coffee Spider web Application

i. Why Using Embedded Tomcat? Maven Dependencies for Embedded Tomcat

Basically, nosotros want to use embedded Tomcat for the following purposes:

- Rapid unit of measurement testing for web components like Java servlets: instead of starting/stopping Tomcat server and opening a web browser for transmission unit of measurement testing, it is possible to apply embedded Tomcat to automate unit of measurement testing.

- Delivering a Java web awarding as a standalone Java application: the end users now can run a JAR file which starts the embedded server which hosts the spider web application. No demand to download and install Tomcat and deploy the spider web application manually.

- Programmatic control of the server: integrating an embedded server allows yous to have more than control of the server in programmatic ways, and automate manual steps.

- Any you lot can imagine.

2. Maven Dependencies for Embedded Tomcat

In lodge to use embedded Tomcat and pack its runtime with your Java spider web applications, add the following dependencies in Maven'spom.xmlfile:

<dependency> 	<groupId>org.apache.tomcat.embed</groupId> 	<artifactId>tomcat-embed-core</artifactId> 	<version>${tomcat.version}</version> </dependency> <dependency> 	<groupId>org.apache.tomcat.embed</groupId> 	<artifactId>tomcat-embed-jasper</artifactId> 	<version>${tomcat.version}</version> </dependency> <dependency> 	<groupId>org.apache.tomcat.embed</groupId> 	<artifactId>tomcat-embed-logging-juli</artifactId> 	<version>${tomcat.version}</version> </dependency>

Wheretomcat.version is a property that points to the actual version of Tomcat:

<properties> 	<tomcat.version>8.0.48</tomcat.version> </properties>

In case you don't use Maven, download and add together the following JAR files to your project's classpath:

  • ecj-3.12.3.jar
  • tomcat-annotations-api-viii.0.48.jar
  • tomcat-embed-core-eight.0.48.jar
  • tomcat-embed-el-8.0.48.jar
  • tomcat-embed-jasper-8.0.48.jar
  • tomcat-embed-logging-juli-eight.0.48.jar

Annotation that the version numbers may differ than it is shown here.

3. The Tomcat Embed API

The key class is org.apache.catalina.startup.Tomcat that lets you control most everything of an embedded server: create new case, configure server, add spider web applications, add servlets, starting time and stop the server, etc.

For example, the following code creates and starts an embedded Tomcat instance running on port number 8080:

Tomcat tomcat = new Tomcat(); tomcat.setPort(8080);  // configure the server // configure web applications  tomcat.kickoff();

You tin use following methods to configure the server:

  • setBaseDir(String baseDir) : sets the base directory for the server to work. This should be the kickoff method called. By default, Tomcat attempts to use these system properties in this social club: catalina.base , catalina.home, and user.dir.
  • setHostname(Cord name) : sets the hostname of the default host. Default is 'localhost'.
  • setPort(int port) : sets the port number for the default connector.

To create a web awarding programmatically, apply the post-obit method to add together a context to the server:

addContext(String contextPath, String docBase)

Where contextPath is the web awarding name, docBase is the base directory of the awarding. This method returns a Context object that represents an individual web application. Yous tin can employ this Context object to configure various aspects of the web applications, for instance:

// add context initialization parameters context.addParameter("param1", "value1"); context.addParameter("param2", "value2");  context.addErrorPage(new ErrorPage()); context.setCookies(truthful); context.setSessionTimeout(30);

To configure the server for an existing web application, use the following Tomcat's method:

addWebapp(String contextPath, String baseDir)

Where contextPath is the spider web application name and baseDir is the base of operations directory of the awarding. baseDir can refer to an external WAR file, or to a web application directory in the aforementioned project.

To add an existing Java servlet to a web application, you can use the post-obit method:

addServlet(String contextPath, String servletName, Servlet servlet)

Or use the post-obit static method:

Tomcat.addServlet(Context context, String servletName, Servlet servlet)

To configure URL mapping for a servlet, you tin use the following method of the Context form:

addServletMappingDecoded(String urlPattern, Cord servletName)

To first, stop and destroy the server:

      tomcat.commencement()

      tomcat.stop()

      tomcat.destroy()

And to cause the current thread to look until the server is shutdown, use the following argument:

tomcat.getServer().await();

For consummate reference, read the Javadocs of Tomcat and Context classes.

4. Embedding Tomcat server for a Programmatic Java Web Application

In this approach, yous create a whole Java spider web application programmatically from scratch. In that location's no existing spider web awarding, no existing servlet.

For case, the following program SimpleWebApp creates an instance of embedded Tomcat, a web application nether the root context path ("/"), a Java servlet named "Servlet1", and maps this servlet to the URL pattern "/go":

package net.codejava;  import coffee.io.File; import java.io.IOException; import coffee.io.PrintWriter;  import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;  import org.apache.catalina.Context; import org.apache.catalina.LifecycleException; import org.apache.catalina.startup.Tomcat;  public class SimpleWebApp {  	public static void main(String[] args) throws LifecycleException { 		Tomcat tomcat = new Tomcat(); 		tomcat.setBaseDir("temp"); 		tomcat.setPort(8080); 		 		String contextPath = "/"; 		String docBase = new File(".").getAbsolutePath(); 		 		Context context = tomcat.addContext(contextPath, docBase); 		 		HttpServlet servlet = new HttpServlet() { 			@Override 			protected void doGet(HttpServletRequest req, HttpServletResponse resp) 					throws ServletException, IOException { 				PrintWriter writer = resp.getWriter(); 				 				author.println("<html><championship>Welcome</title><body>"); 				writer.println("<h1>Have a Great Day!</h1>"); 				author.println("</torso></html>"); 			} 		}; 		 		String servletName = "Servlet1"; 		String urlPattern = "/get"; 		 		tomcat.addServlet(contextPath, servletName, servlet);		 		context.addServletMappingDecoded(urlPattern, servletName); 		 		tomcat.start(); 		tomcat.getServer().await(); 	} }

As you tin can meet, a Java servlet is created "on the fly", which overrides the doGet() method:

HttpServlet servlet = new HttpServlet() { 	@Override 	protected void doGet(HttpServletRequest req, HttpServletResponse resp) 			throws ServletException, IOException { 		PrintWriter writer = resp.getWriter();  		writer.println("<html><title>Welcome</championship><torso>"); 		author.println("<h1>Accept a Great Solar day!</h1>"); 		writer.println("</body></html>"); 	} };

This servlet sends a elementary HTML page to the client, with a heading "Have a Great Twenty-four hour period!".

Run this program in Eclipse and you can see the server'due south log in the Console view:

Run SimpleWebApp Console

The server is listening on port 8080, so type the post-obit URL in your web browser:

http://localhost:8080/go

And y'all can see the consequence looks like this:

Run SimpleWebApp Browser

That means the server and web application are up and running.

You can also write a Servlet in a separate class (AddServlet.java) similar this:

parcel net.codejava;  import java.io.IOException; import java.io.PrintWriter;  import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;  public form AddServlet extends HttpServlet { 	@Override 	protected void doGet(HttpServletRequest req, HttpServletResponse resp)  			throws ServletException, IOException { 		int a = Integer.parseInt(req.getParameter("a")); 		int b = Integer.parseInt(req.getParameter("b")); 		int sum = a + b; 		 		String result = String.format("%d + %d = %d", a, b, sum); 		 		PrintWriter author = resp.getWriter(); 		writer.println("<html><title>Addition</title><body>"); 		author.println("<h1>" + event + "</h1"); 		writer.println("</body></html>"); 	} }

This servlet returns sum of two numbers passed from query parameters. And add this servlet to the spider web awarding like this:

AddServlet addServlet = new AddServlet(); servletName = "AddServlet"; urlPattern = "/add together";  tomcat.addServlet(contextPath, servletName, addServlet); context.addServletMappingDecoded(urlPattern, servletName);

Call the servlet from the spider web browser:

http://localhost:8080/add?a=1234&b=5678

And event:

Run AddServlet

In this programmatic fashion, at that place is no JSP support. This arroyo is suitable for creating a minimum, simple, lightweight spider web awarding with an embedded Tomcat server.

To create an executable JAR file for this kind of application in Eclipse IDE, click File > Export… In the Export dialog, select Coffee > Runnable JAR file and click Next. In the Runnable JAR File Export screen, retrieve to choose the pick "Copy required libraries into a sub-folder adjacent to the generated JAR", every bit shown in the following screenshot:

Runnable JAR File Export

Click Finish, and eclipse generate the executable JAR file along with the required JAR files for embedded Tomcat in a directory next to the generated JAR. And then you lot tin can run the application using java command like this:

java -jar SimpleWebApp2.jar

And so yous can see the server is started and ready to accept client's requests.

5. Using Embedded Tomcat server for a State of war File

An interesting feature of embedded Tomcat is that you can programmatically starts the server for running a Java web awarding which is packed in a Spider web Archive (State of war) file.

Suppose you have a Coffee web application packed in Bookstore.state of war file, the post-obit plan creates a Tomcat instance and adds a web application from the State of war file:

package cyberspace.codejava;  import javax.servlet.ServletException;  import org.apache.catalina.LifecycleException; import org.apache.catalina.startup.Tomcat;  public class RunWarExample {  	public static void main(String[] args) throws ServletException, LifecycleException { 		Tomcat tomcat = new Tomcat(); tomcat.setBaseDir("temp"); 		tomcat.setPort(8080); 		 		Cord contextPath = "/Bookstore";		 		String warFilePath = "D:\\Web\\Website\\Bookstore.war"; 		 		tomcat.getHost().setAppBase("."); 		 		tomcat.addWebapp(contextPath, warFilePath); 		 		tomcat.outset(); 		tomcat.getServer().wait(); 	} }

Run this program and you can meet the content of the State of war file is extracted to the base directory, and you can access the web application using the specified context path.

This arroyo is very convenient for testing existing spider web applications which are packed in State of war files, and you lot don't have to touch their code.

For this kind of application, generate the executable JAR file in the aforementioned fashion as described in the programmatic web application.

vi. Embedding Tomcat server for an Existing Java Web Application

Perhaps this is the most frequently used feature of embedded Tomcat. This is the scenario: You're developing a Java spider web application and now you want to embed Tomcat for the purpose of unit of measurement testing or evangelize the web application every bit a standalone Coffee programme. So how to make it?

Suppose that your web application's files are stored in a directory named WebContent that looks like this:

WebContent

The post-obit program starts an embedded Tomcat instance to run the web awarding:

package net.codejava.servlet;  import java.io.File;  import javax.servlet.ServletException;  import org.apache.catalina.LifecycleException; import org.apache.catalina.startup.Tomcat;  public class EmbeddedTomcatTest {  	public static void master(String[] args) throws LifecycleException, ServletException { 		String contextPath = "/UploadApp"; 		String webappDir = new File("WebContent").getAbsolutePath(); 				 		Tomcat tomcat = new Tomcat(); 		tomcat.setBaseDir("temp"); 		tomcat.setPort(8080); 		 		tomcat.addWebapp(contextPath, webappDir); 		 		tomcat.start(); 		tomcat.getServer().await();		 	} }

Now yous can use your browser to access the web application using the specified port number and context path in the program higher up:

http://localhost:8080/UploadApp/upload.jsp

To generate executable JAR file for this kind of application, you need to use Tomcat Maven plugin as described here.

API References:

CourseTomcat Javadoc

ClassContext Javadoc

Other Tomcat Tutorials:

  • How to deploy a Java spider web application on Tomcat
  • How to Utilise Virtual Hosts in Tomcat
  • How to set web awarding context path as server root in Tomcat
  • How to configure JNDI DataSource for Database Connection Pooling in Tomcat
  • How to configure session timeout in Tomcat
  • How to change Tomcat port number
  • How to add Tomcat server in Eclipse
  • How to modify server location and deploy path for Tomcat in Eclipse

About the Author:

Nam Ha Minh is certified Coffee developer (SCJP and SCWCD). He started programming with Coffee in the time of Java ane.4 and has been falling in love with Java since then. Make friend with him on Facebook and sentry his Java videos you YouTube.

Add comment

langonch1956.blogspot.com

Source: https://www.codejava.net/servers/tomcat/how-to-embed-tomcat-server-into-java-web-applications

0 Response to "Not Able to Upload Java or Tomcat Cookbook"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel