Hello-world in servlet with text editor
In this Article, I will show you how to create an Hello-world (welcome) application using servlet and run it yourself. The aim is to show you what is going on under the hood when you use an IDE like Netbeans or Eclipse which would increase your understanding and debugging.
Note: The example is based on Tomcat Server and the github repo is pasted below
Let’s get to it.
Servlet Structure
Every servlet based application directly or indirectly follows the below standard structure:
Create a project folder and call it welcome. Inside the welcome folder create index.html. Create another folder in welcome folder and call WEB-INF. Create classes and lib folders in WEB-INF folder.
Steps to follow when creating Servlet
- Create servlet
- Configure the servlet
- Compile and package the servlet
- Deploy the servlet
- Run the servlet
- Create servlet
To create servlet you have three options: you can either implement Servlet interface, extend GenericServlet class or extend HttpServlet class.
Using the last option in this example. Go the classes folder and create HelloServlet.java file
Note: It is not a must you create your .java files in classes folder. You can create it anywhere you like but after the compilation move your .class file to to classes folder.
public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("<h4> Welcome to Servlet App. </h4>");
}
}
2. Configure the Servlet
Create web.xml file in WEB-INF folder and type the following codes in it.
<web-app><servlet>
<servlet-name>helloworld</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet><servlet-mapping>
<servlet-name>helloworld</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping></web-app>
3. Compile and Package(Optional) the Servlet
Go the classes folder (if that is where you created your .java file) and type the following:
javac "C:\Program Files\Apache Software Foundation\Tomcat 9.0\lib\servlet-api.jar" HelloServlet.java
Note: You will get error if:
- Java environment variable is not set. Make sure you set environment variable and try again
- If your Tomcat installation path is different. Update the path accordingly
4. Deploy the Servlet
Go to your Server (Tomcat) folder and copy the app folder into the webapps folder of the server.
5. Run the Servlet
Make sure your server is running, go to your browser and enter the URL in this pattern:
localhost:{port}/{app-name}
My Tomcat is running on port 9090 so my URL is: localhost:9090/welcome
if everything is fine you should see the index of your application. Click on the link and that is your Servlet running!
If you have got a question or suggestion, let me know.