2

How to call Servlet from another Servlet? both in one app.

public class DBaddData extends HttpServlet {

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ....some actions here...
    ...get data from JSP...
    ...call INSERT INTO method...
    ...and then I want to call SELECT servlet...


    RequestDispatcher view = getServletContext().getRequestDispatcher("/myServlets/DBselTankList");
    view.forward(req, resp);
}

}

But I got only:

The requested resource is not available.

"Select servlet" calls select method from DB and then show JSP with results

public class DBselTankList extends HttpServlet {


protected void processRequest(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
 DBSelectRows dbSR = new DBSelectRows();  

    List<DBObjBaseStd> dboBStd=new ArrayList<DBObjBaseStd>();

    dboBStd=dbSR.sel(DBConnStrings.driver, DBConnStrings.url, DBConnStrings.dbName, DBConnStrings.userName, DBConnStrings.password, DBConnStrings.sslState);

    req.setAttribute("list", dboBStd);
    RequestDispatcher view = req.getRequestDispatcher("selectedTankList.jsp");
    view.forward(req, resp);
}

}

I also want to get this selectedTankList.jsp by link from header

<a href="selectedTankList.jsp">Tank list</a>

But how to call "Select servlet" without form and submit button?

Sergey Lotvin
  • 179
  • 1
  • 14

1 Answers1

1

Eventually I've found out. When you call Servlet by clicking link (i.e. you call first Servlet that execute code inside doGet and only after that it send JSP to client) you need to put URL for href and this must be what you put between tags <url-pattern>...</url-pattern> in your web.xml during the mapping target servlet. For the example above it must be:

<a href="DBselTankList">Tank list</a>

Why DBselTankList? Because look at my web.xml:

<servlet-name>DBselTankList</servlet-name>
<servlet-class>myServlets.DBselTankList</servlet-class>
<servlet-mapping>
    <servlet-name>DBselTankList</servlet-name>
    <url-pattern>/DBselTankList</url-pattern>
</servlet-mapping>

BTW, the names are not good, shame on me. I have to take time to study the good approach in naming. So, when you call Servlet from another Servlet (both in one project) do it like this:

RequestDispatcher view =  getServletContext().getRequestDispatcher("/DBselTankList");
view.forward(req, resp);

Namely, add "/" before the same name as for href

Sergey Lotvin
  • 179
  • 1
  • 14