Doldrums
Doldrums

Reputation: 123

Creating Maven Project with Servlet in IntelliJ

I have been trying to create a servlet in intellij by following this tutorial: https://medium.com/@backslash112/create-maven-project-with-servlet-in-intellij-idea-2018-be0d673bd9af.

Here is the code I have added so far to the servlet class:

package com.demo;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/DemoServlet")
public class DemoServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<h3>Hello World!</h3>");
    }

}

I also set the run configuration to use Tomcat 9: enter image description here enter image description here

When I run the project I can view "Hello World!" on both http://localhost:8080 and http://localhost:8080/DemoServlet. enter image description here enter image description here

However, I thought that you should only be able to view "Hello World!" at http://localhost:8080/DemoServlet and not at http://localhost:8080. I would like to know if this is the expected behavior for the program, or did I make a mistake in my configuration of the Servlet?

Upvotes: 1

Views: 527

Answers (1)

CrazyCoder
CrazyCoder

Reputation: 401975

This result is expected. The webapp context root displays the same text because there is src/main/webapp/index.jsp file provided by maven-archetype-webapp with the following:

<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

Since servlet and the index page print the same text, you were confused and thought that this text is also printed by the servlet, while it's actually an index page.

Notice that the text size is different. The index page uses <h2>, servlet code is using <h3>.

Upvotes: 1

Related Questions