Pl. help to call a servlet page which is in another directory from a jsp page.

Dani AI

Generated

Building on ’s reply: you don’t call a servlet by its physical directory. The container routes requests by URL patterns. Map the servlet to a clean path and have the JSP submit to that path. Also, avoid hardcoding the app name; generate the context path so it works no matter where the app is deployed.

Example mapping:

<!-- web.xml -->
<servlet>
  <servlet-name>Front</servlet-name>
  <servlet-class>com.example.web.FrontController</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>Front</servlet-name>
  <url-pattern>/front</url-pattern>
</servlet-mapping>

From the JSP, post to the mapped URL:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<form action="<c:url value='/front'/>" method="post">
  <!-- fields -->
</form>

Notes and gotchas:

  • Mapping a servlet to a path that looks like a JSP (e.g., something.jsp) is confusing and can clash with the JSP servlet. Prefer paths like /front or /controller/*.
  • The legacy /servlet/... invoker URL is container-specific and often disabled in production. Stick to explicit mappings.
  • If you want a server-side handoff from a JSP to a servlet in the same webapp (no new URL in the browser), forward instead of redirecting:
<%
  request.getRequestDispatcher("/front").forward(request, response);
%>
  • If the servlet lives in a different web application (different context), you cannot forward to it directly; use response.sendRedirect(...) to its public URL. Keep JSPs as views and put logic in servlets or controllers.

If servlets are not mapped with use of web.xml you call it like this from the form for example

<form action="http://localhost:8080/PROJECT_NAME/servlet/SERVLET_NAME_NO_FILE_EXTENSION" method="POST">
YOUR FORM HERE
</form>

The web.xml mapping will look like this

<servlet>
       <servlet-name>SERVLET_NAME_YOU_WANT_TO_CALL_IT</servlet-name>
       <servlet-class>REAL_SERVLET_NAME_NO_FILE_EXTENSRION</servlet-class>
    </servlet>

    <servlet-mapping>
       <servlet-name>SERVLET_NAME_YOU_WANT_TO_CALL_IT</servlet-name>
       <url-pattern>/A_NAME.jsp</url-pattern>
    </servlet-mapping>

Example:
REAL_SERVLET_NAME_NO_FILE_EXTENSRION is FrontController
SERVLET_NAME_YOU_WANT_TO_CALL_IT I want to be Front
A_NAME.jsp I want to be front.jsp
to call my FrontController I will do following

<form action="front.jsp" method="POST">
FORM CODE HERE
</form>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.