Suppose we have function foo() in Servlet A.
From Servlet B how can we call this foo() function of servlet A?
both servlet are from same application and in same context....

Dani AI

Generated

The simplest, safest design is to stop trying to call a servlet instance method directly and move the reusable work out of Servlet A into a plain Java class (a service/utility). This keeps servlets thin (handling requests/responses) and makes the logic reusable, testable and thread‑safe. Example shape:

public class FooService {
    public String foo(String input) {
        // business logic here
        return result;
    }
}

Both Servlet A and Servlet B call new FooService() (or obtain it from an application-scoped bean/DI container) and pass only the data needed. This avoids lifecycle and concurrency problems that come from trying to invoke another servlet's methods.

If the goal is to invoke Servlet A’s request-handling pipeline (so it produces its usual response), use the servlet request dispatcher to invoke it within the same request. That call dispatches to the other servlet on the server side and can pass data via request attributes:

request.setAttribute("key", value);
RequestDispatcher rd = request.getRequestDispatcher("/path/to/ServletA");
rd.forward(request, response);

A browser redirect (the advice from ) is different: it tells the client to make a new request, changes the URL, and requires passing parameters via query string or session. ’s tutorial link pointed to dispatching/redirecting as the common options.

Avoid instantiating servlet classes by hand or trying to fetch container-owned servlet instances (container lifecycle and concurrency are not under direct control). Also avoid storing request-specific data in servlet instance fields. When sharing state, prefer stateless service objects or properly synchronized/managed application-scoped components. ’s moderation reminder about reading available docs is apt: refactoring into a service + request dispatching covers most real needs.

Recommended Answers

All 4 Replies

An example can be found here:

how we can call one servlet from other servlet and give the source code of all process?
<snipped email>

how we can call one servlet from other servlet and give the source code of all process?
send it in this id: <removed>

1) Do not hijack threads. Post your own thread if you have a question.
2) Do not ask for code to be emailed. This is against the rules.
3) Read the tutorial that was already posted above. It is directly related to your question and you are just plain lazy if you cannot bother to read it.

just use response.sendRedirect(

commented: Well done. 3 years to late and not even full method name -3
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.