Home > Tutorials > Java

Dynamic Web Project with Maven and Eclipse

Last updated : 8 March 2021

Dynamic web projects use server-side scripting, meaning each user request is processed differently by the server and render different outcomes based on parameters. For example, when you log in to your email, you are responded with your own inbox with emails only belong to you.

When your requirements expand to serve users with dynamic content, you will have to process individual user requests differently and serve unique responses. Therefore, you must look beyond static web modules consist of html pages that serve same content for every user. A dynamic web project can fill the gap.

Creating a maven dynamic web project is pretty straightforward with eclipse ide's built-in project wizard. All you need is eclipse ide with integrated maven. Without any further due, lets find out how to create a dynamic web project. Review prerequisites to ensure you can move forward with the rest of the tutorial.

What do we build?

This tutorial shows you how to build a maven dynamic web project with Eclipse ide and deploy it in Eclipse integrated Tomcat environment. The end product is a deployable war file where you can deploy it in any web or application server that supports Java.

Tools we will use:

  • Eclipse IDE for java EE (Attached screen shots were taken from Eclipse Luna. Your menues may slightly differ depending on the Eclipse version you use)
  • Apache tomcat 9 (required to deploy the project)
  • Apache Maven (the latest eclipse ide's come with Maven pre-installed)

There are multiple ways to create a dynamic web project with maven support. In this tutorial, our focus will be to use eclipse ide to create the dynamic web project.
The other approach is to use the command line with maven, without any IDE. We discuss this in another tutorial.

Creating a new dynamic web project with the eclipse project wizard

Fire up your eclipse ide. You will require a work space to save your ide settings. If you haven't created a work space yet, now it is time to create one. Please refer to Eclipse related tutorials to see how to create a work space.

In your eclipse ide right click Project Explorer or click File.
Project Explorer -> New -> Project -> Maven -> Maven Project
Or
File -> New -> Project -> Maven -> Maven Project

Create new Maven Project
Figure 1 : Eclipse new project wizard

As illustrated in the above figure, select Maven Project option from the project wizard. If you are having a hard time finding this option, type Maven project in type filter text text box, and the wizard will filter that option for you. Click Next>

Project location
Figure 2 : New Maven project location

Give an appropriate Location of your choice. This is where you will save the web project on your disk. Make sure to uncheck Create simple project (skip archetype selection) option, for reasons listed below. Click next

Maven archtypes
Figure 3 : Maven project archtype for dynamic webapp

Now you will see a list of maven predefined archetypes. In short, archetype is a Maven project templating toolkit packed with industry standard best practices. Arctypes enable users getting startrd as quickly as possible by providing a sample project template that demonstrates best practices and many of the features of Maven. It also enables us to spend more time on implementing business logic while deligating core architecture and framework best practices to inherit from Maven. As you can see, there are many pre-defined archtypes to select from. They all have different, or slightly differnt use cases. Out of those selections, our best choice would be maven-archetype-webapp. Simply, it is a pre-defined maven template to create a dynamic web-app.
Select maven-archetype-webapp from the list.

Group id and artifact id
Figure 4 : Maven Group Id and Artifact Id

When you create a maven project, maven usually stores all the project related files in a common folder named ./m2 (dot m2). It is important to understand that this is not related to your workspace. Your workspace holds ide specific data, and the location you select holds your actual project. By default, Maven downloads all dependancy libraries to this .m2 folder for all projects you create on your computer, and refer them from project location. (More about this later) Therefore, we must have a way to identify your project among other maven projects. So, group id enforces a naming schema that will identify your project uniquely. The standard naming convention is the reversed domain name of your project, similar to Java package naming rules. learnbestcoding.com will become com.learnbestcoding.

Artifact id is the name of the jar file and the version is appended to it (if you provided a version). To summarize, you will find the file SpringWeb-0.0.1-SNAPSHOT.war in location .m2/repository/com/learnbestcoding after creating and maven installing this project. Alternatively, we can generate a war file in Eclipse ide without Maven installation.

After completing the above step, you have created yourself a dynamic maven webapp. However, most likely you will see some project errors. You can see them by clicking on Markers tab, below your eclipse editable text area. Please note that some versions of Eclipse label this tab as Problems. Lets fix them now before deploying this project on the server.

Fixing project errors

Double click on the pom file that got generated during the above process. This file is named pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.learnbestcoding</groupId>
   <artifactId>SpringWEB</artifactId>
   <packaging>war</packaging>
   <version>0.0.1-SNAPSHOT</version>
   <name>SpringJDBC Maven Webapp</name>
   <url>http://maven.apache.org</url>
   <dependencies>
    <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>javax.servlet-api</artifactId>
       <version>4.0.1</version>
    </dependency>
   </dependencies>
   <build>
     <finalName>SpringWEB</finalName>
       <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>          
				<version>3.8.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
       </plugins>
   </build>
</project>

Since our goal is to create a dynamic web project, we have to process our client requests before generating a response. In simple terms, this is done by servlets. A servlet is a small Java program that runs in a web server. Servlet or HttpServlet is the clients interface with the webserver, and is implemented by the webserver. We extend web server's HttpServlet to receive and respont to our custommer's requests. This happens usually accross HTTP protocol.

Adding HttpServlet support

By default, the support for HttpServlet is not included with the default maven artifact we used to create this web module. Therefore, we have to instruct maven to download and refer to supporting libraries for HTTPServlet. This is done by modifying the pom.xml file. In the above file, we include the javax.servlet functionality in lines 11-15. You can copy and past this section to your pom file.

Updating java version (optional)

Meantime, if you want to update the java version, add the <plugins> section listed in Lines 19 to 29. Change to your preferred java version by changing the <configuration> section. Before changing the java version, ensure that the intended java version is installed on your workstation.

Update to dynamic web module 4.0 (optional)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>Archetype Created Web Application</display-name>
</web-app>

If you decide to update your projects Dynamic Web Module to version 4.0 (or above), you will have to update web.xml as listed above. web.xml is the configuration file of web applications in java. It tells the web server how to handle incoming requests, what classes to load etc... We will discuss the detailed usage of web.xml file in advanced web development tutorial. Until that, lets keep our web.xml up to date by refering to the latest version. Ensure that web-app_4_0.xsd matches version="4.0"

4.3 Maven update the project

Maven update
Figure 5 : Do not forget to Maven update after changes to web.xml and pom.xml

After above changes, right click your project and do a maven update. Also, make sure that project's java compiler is changed properly by navigating to Project -> Properties -> Project Facets. If not, change java version to 14 or your preference, but make sure both Eclipse and webapp uses same version of Java. It is a good idea to do a clean and do another maven update after doing any project configuration changes in the pom.xml file. This will save you a lot of time.

If you still experience project errors at this point, I have listed down several errors you may encounter during this process and solutions for them. Click here to see them.

Once all of the above steps are completed successfully, your maven web project structure will look like this.

Maven web project structure
Figure 6 : Your maven web project structure

Add servlet to the dynamic web project

Now let's add a servlet to our dynamic web project to handle client requests.
Right-click project -> New -> Servlet

Creating a servlet
Figure 7 : Creating a servlet

Provide the servlet name and package name. It is a good practice to have a separate package dedicated to servlets.
Click Next

Servlet name and package
Figure 8 : Servlet name and package

Here we have the opportunity to provide the servlet URL mapping. The URL mapping determines how this servlet can be accessed by a URL. In this example, we use /WelcomeServlet, meaning this servlet is accessible by the URL http://localhost:8080/SpringWeb/WelcomeServlet

Servleturl mapping
Figure 9 : Servleturl mapping

Below we have selected two request methods doGet and doPost. The majority of the HTTP requests belong to doGet or doPost.

Servlet methods
Figure 10 : Servlet methods

Below is the servlet code auto-generated by the eclipse ide. Note that I tweaked the code in doGet method to receive the user name submitted by the JSP.

package com.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public WelcomeServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().append("Hello: ").append(request.getParameter("name"));
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

Add JSP to the dynamic web project

Adding a JSP is straightforward. Right-click the webapp folder located under the Deployed Resources folder and select New -> JSP file. My users.jsp file is listed below.

<html>
<body>
<b>Welcome to Servlets!</b>
<form action="WelcomeServlet" method="get">
    Enter your name: <input type="text" name="name" size="24">
    <input type="submit" value="Submit" />
</form>
</body>
</html>

Deploy Maven project to tomcat

Now our maven web app is ready for deployment. Follow these quick steps to create an embedded Tomcat server in Eclipse and deploy the project.

1.  Download Apache Tomcat server from http://tomcat.apache.org and extract it to a folder.

2.  In Eclipse, go to Window -> Show View -> Servers. This will open the servers view. Provide a server hostname and server name.

Eclipse create server
Figure 11: Host name and Server name

3.  Browse the Tomcat Server download location and set the Tomcat installation directory. The JRE should point to your JDK installation. Click Next.

server location and jdk
Figure 12: Server location and JDK installation

4.  Select the web project from available and ad it to the configured panel. Click Finish

select project to deploy
Figure 13: Select the project to deploy

5.  The server wizard will add the Tomcat 9 server to the servers panel. To run the project, right-click the server and select Debug or Start.

starting the Tomcat server
Figure 14: Starting the Tomcat server

Now our web app is deployed and ready to accept requests. Go to a browser and type http://localhost:8080/SpringWeb/users.jsp. Note that the Tomcat server's default port is 8080.

Accessing the jsp page
Figure 15: Accessing the jsp page
Response from the server
Figure 16: Response from the server

How to create dynamic web project war file?

Now we have a deployable dynamic web application (although it needs much work to be anything useful). For testing purposes, it is more practical to deploy your projects in Eclipse embeded server environment. But for production or distribution, you have to generate a deployable archive, that you can drop in server's deployment folder.

Exporting war file
Figure 17: Creating deployable war file of your webapp

As illustrated above, right click on the project and select export. This results in a project_name.WAR file that you can deploy in a server.

In order to accept client requests and to generate responses, this web app needs to be deployed in a web server, such as Tomcat, JBoss, etc...

Follow this post to deploy this app on Tomcat
How to deploy a java web application on tomcat server

How to change Maven user settings?

As stated esrlier in this tutorial, Maven, by default downloads all project dependancy libraries to repository folder usually located at C:\Users\username\.m2\repository If you like to have multiple locations for different projects, you can follow below steps. First, create an xml file as listed below. In this example, the file name is learnbestcoding.xml. It makes sense to name the same as your project name. Then go ahead and create an empty folder in the location you have specified in localRepository tag. Make sure to give the same name indicated in this tag.

<?xml version="1.0"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>C:\dev\custom_repo_locations\learnbestcoding</localRepository>
</settings>

Navigate to Window -> Preferences -> Maven -> User Settings

How to change Maven user settings
Figure 18 : Changing Maven user settings to change dependancy library folder

Change User Settings by selecting the newly created learnbestcoding.xml file. You will notice Local Repository ... will point to the folder you created. Click Apply and Close
As mentioned earlier, right click your project and do a maven update. Once the update is done, you will notice that Maven has downloaded all dependancy libraries to your new location.

Solutions for maven project errors

1.  Java compiler level does not match the version of the installed Java

  • Right-click the project and go to properties
  • Select Project-Facets
  • Ensure the Java version is the same version you specified in the pom.xml file. Else, set the java version and save it

2.  Cannot change the version of project facet Dynamic web module to 4.0

  • Right-click the project and go to properties
  • Select Project-Facets
  • Ensure Dynamic Web Module is 4.0

3.  Cannot save project facet after setting the dynamic web module to 4.0

  • Navigate to your workspace
  • Double click the project folder in the workspace and go to the .settings folder
  • Edit org.eclipse.wst.common.project.facet.core.xml and change the dynamic web module to 4.0 and save the changes
  • Right-click on the project (in the Project Explorer) and do a Maven update

4.  Creating src/main/java folder in Eclipse

If your default project structure does not contain a java folder. you may notice that you cannot create a java src folder in the src/main folder.
  • Right-click src folder and select
  • Build Path -> Remove from Build Path
  • Create the java folder under src/main
  • Right-click java folder and Build Path -> Use as Source Folder
  • Repeat this for src/test
Lance
By: Lance
Lance is a software engineer with over 15 years of experience in full-stack software development.
Read more...

Comments are disabled

No Comments