Create a Maven Project with Servlet in IntelliJ IDEA 2018
IntelliJ IDEA 2018.1 (Ultimate Edition)
macOS 10.13.4
A Servlet is a java class that is extended to handle the capabilities of a server. Servlets can be used to handle the requests and responses of a server.
Apache Maven is a software project management and comprehension tool. Maven can help you manage a project’s build, reporting and documentation from a central piece of information.
In this tutorial I’ll be explaining how to create a simple servlet project with maven in IntelliJ IDEA.
Step 1: Create a Maven project in intellij IDEA
Step 2: Use the pom.xml file to manage your project dependencies
POM stands for “Project Object Model”. It is an XML representation of a Maven project held in a file named pom.xml.
Here is a introduction of pom.xml file:
A project contains configuration files, as well as the developers involved and the roles they play, the defect tracking system, the organization and licenses, the URL of where the project lives, the project’s dependencies, and all of the other little pieces that come into play to give code life. It is a one-stop-shop for all things concerning the project. In fact, in the Maven world, a project need not contain any code at all, merely a pom.xml.
For the full introduction, please check https://maven.apache.org/pom.html#What_is_the_POM
Let’s go back to our project:
Go to the https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api/4.0.1 page, copy the dependency code inside the Maven tab:
Step 3: Create the web app
3.1 Create a servlet class
Firstly, create a new folder named java inside the src.main folder, then right-click the java folder, set it as sources root. If you don’t do that, then the IntelliJ IDEA will not show ‘Class’ when we right-click and select ‘New’.
Right-click the java folder, and select ‘New’ — ‘Servlet’, name it com.demo.DemoServlet.
Remember to change the annotation code from @WebServlet(name = “DemoServlet”) to @WebServlet(“/DemoServlet”).
Step 4: Run the project with Tomcat Server
4.2 Set up the Tomcat Server
Open the Run/Debug Configurations dialog (e.g. Run | Edit Configurations).
Click (⌘N), select the Tomcat Server and select Local.
If this is your first to use Tomcat, the ‘Application Server’ item should be empty.
You need to download the Apache Tomcat first. Visit https://tomcat.apache.org/ page, select ‘Download’ — ‘Tomcat 9’ — ‘Binary Distributions’ — ‘Core’ — ‘tar.gz’.
decompress it.
Then back to IntelliJ IDEA, press the ‘Configure’ button next to the ‘Application Server’ item, and select the Tomcat folder.
4.3 Pressing the Fix button to add artifact.
4.4 Finally, Build and Run.
Visit http://localhost:8080/DemoServlet
Sources
https://www.jetbrains.com/help/idea/working-with-artifacts.html#artifact_def