Search code examples
eclipsejspservletsjspinclude

Eclipse: jsp:include action with servlet


Well, here again strucked on a suppoused no problem. I have a simple servlet "Myservlet.java" that prints a string (Dynamic Web Project name is "JspCallingServlet" and its context root is "/") DynamicWebProject Explorer

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

/**
 * Servlet implementation class MyServlet
 */
@SuppressWarnings("serial")
@WebServlet(
        name="MyServlet",
        urlPatterns="/MyServlet"
        )
public class MyServlet extends HttpServlet {

... omitted code

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        PrintWriter out = response.getWriter();
        out.println("... I'M MyServlet ...");
    }

}

And it works since if i "Run As/Run on Server" it shows servlet output

So i thought that i could easily call it within a jsp with the include action, setting as page the servlet url

<html>
<head>
<title>Using servlet into a jsp</title>
</head>
<body>
    Using: MyServlet.java
    <br />
    <jsp:include page="/MyServlet" />
</body>
</html>

but why on hell the

<jsp:include page="/MyServlet" />

doesn't compile, and the message says

Fragment "/MyServlet" was not found at expected path /JspCallingServlet/WebContent/MyServlet

Why bothering the WebContent folder when it's supposed to open the "page" URL mapped to the servlet?.


Solution

  • :S i found an answer by myself.

    I was somehow misguided by the answer i found at How to call servlet through a JSP page before posting the very question i made...

    It seems - at least that's what happens to me - that the right "action" to use in order to include a servlet is the "forward" action: not the "include" one.

    Ie the right .jsp is the following

    <html>
    <head>
    <title>Using servlet into a jsp</title>
    </head>
    <body>
        Using "jsp:include" fails, while using "jsp:forward" works
        <br />
        <jsp:forward page="/MyServlet" />               <%-- WORKING --%>
        <%-- <jsp:include page="/MyServlet" /> --%>     <%-- NOT WORKING --%>
    </body>
    </html>