// Set the content type of the response
response.setContentType("text/html");
// Get a PrintWriter to write the response
PrintWriter out = response.getWriter();
// Write the HTML content
out.println("<html><body>");
out.println("<h1>Hello, World!</h1>");
out.println("</body></html>");
}
}
4. Run the Servlet
Run Configuration:
Click "Add Configuration..." in the top right corner.
Click the "+" button and select "Tomcat Server" -> "Local."
In the "Deployment" tab, click the "+" button and add your "HelloWorldServlet" artifact.
Click "OK."
Start Tomcat: Click the "Run" button (green play icon) to start the Tomcat server.
Access the servlet: Open a web browser and go to the URL http://localhost:8080/HelloWorldServlet/hello (replace "HelloWorldServlet" with your project name if it's different).
You should see the "Hello, World!" message displayed in your web browser!
Explanation
@WebServlet("/hello"): This annotation tells Tomcat to map requests to the "/hello" URL path to your HelloWorldServlet class.
doGet() method: This method handles HTTP GET requests to the servlet.
response.setContentType("text/html"): This line sets the content type of the response to HTML, so the browser knows how to display it.
PrintWriter out = response.getWriter(): This gets a PrintWriter object that you can use to write the HTML content to the response.
out.println(...): These lines write the actual HTML code that will be sent to the browser.
This comprehensive guide should help anyone with no prior knowledge create and run a simple "Hello, World!" servlet using IntelliJ IDEA and Apache Tomcat. Remember to replace "HelloWorldServlet" with your actual project name if you chose a different one.
Want to print your doc? This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (