0

src/main/java/com.company.HelloWorldServlet.java

public class HelloWorldServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        String message = "hello";
        req.setAttribute("message", message);
        req.getRequestDispatcher("/WEB-INF/page.jsp").forward(req, res);
    }
}

web/WEB-INF/page.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Hello world Servlet + JSP</title>
</head>
<body>
<p>Data from Servlet: ${message}</p>
</body>
</html>

web/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>HelloWorldServlet</display-name>
    <servlet>
        <servlet-name>HelloWorld</servlet-name>
        <servlet-class>com.company.HelloWorldServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>/helloworld</url-pattern>
    </servlet-mapping>
</web-app>

The application is running on Tomcat7 server on localhost.

Accessing http://localhost:8080/HelloWorldServlet/helloworld gives a 404 - /HelloWorldServlet/helloworld.

Accessing http://localhost:8080/helloworld gives a 404 - /WEB-INF/page.jsp

Why isn't my .jsp page visible to the servlet? Putting the .jsp file in /web/ doesn't change anything either.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
RK1
  • 429
  • 2
  • 7
  • 28
  • So, you're not running the code you think you're running? Did you a full clean/rebuild/redeploy/restart/etc? If in vain, let the build system produce a WAR file which you in turn inspect using a ZIP tool and check if the JSP file is really there where you expected it to be. – BalusC Mar 12 '16 at 20:20
  • @BalusC I inspected the WAR file and the JSP file was not present indeed. I had to add the directory containing JSP as a resource in Maven's pom.xml file. Now it works fine. Thank you for the hint! – RK1 Mar 12 '16 at 20:58

1 Answers1

0

I added pom.xml entries to tell Maven where the resources and configuration files are, that solved the problem.

       <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
            </configuration>
        </plugin>
    </plugins>
    <resources>
        <resource>
            <directory>src/main/webapp</directory>
        </resource>
    </resources>
RK1
  • 429
  • 2
  • 7
  • 28