-1

Is it possible for a java servlet to call the function that is in another java servlet? And if it is possible, can you show me a simple example of how to do it?

Thank you in advance

1cyf1r3
  • 53
  • 1
  • 1
  • 9
  • 2
    A servlet is just another `class` - the same logic applies as with any other. – Boris the Spider Apr 12 '16 at 10:33
  • What do you mean by calling the function of another servlet? – João Rebelo Apr 12 '16 at 10:33
  • @BoristheSpider No. To access it, OP must create an instance of servlet which he cannot (shouldn't). – Suresh Atta Apr 12 '16 at 10:34
  • like example, I got 2 servlet which is ServletA and ServletB. ServletB contain a function call CreateUser which ServletA need to call. Is there a way to do it? – 1cyf1r3 Apr 12 '16 at 10:42
  • 2
    createUser() looks like it should be the part of service layer and not controller. – Prashant Apr 12 '16 at 10:44
  • Can you provide more information? What framework(s) are you using? Are you only using pure Servlets? Or implementing your own servlets by extending or implementing the Servlet Interface or HttpServlet? – João Rebelo Apr 12 '16 at 10:52
  • What is the problem instantiating the servlet class and calling the method? Is this your servlet or from 3th party? – tak3shi Apr 12 '16 at 11:08
  • Your question is ambiguous. Do you mean this? http://stackoverflow.com/q/3024949 Or do you generally mean this http://stackoverflow.com/q/2349633 or this http://stackoverflow.com/q/5003142? – BalusC Apr 12 '16 at 11:15
  • @sᴜʀᴇsʜᴀᴛᴛᴀ fair point - I more meant that you need to _have an_ instance... – Boris the Spider Apr 12 '16 at 12:19

4 Answers4

2

Calling a servlet directly from another servlet is not recommended and considered bad practice because servlet instances are managed by the servlet container. You should follow the separation of concerns principle.

The servlets are responsible for the interface to clients only and shouldn't contain business logic. Put your business logic in a separate layer (e.g. classes in another package) and call it from the servlets only. So the business classes are responsible for the actual internal data and transformations and the servlets are responsible for different views to the outside.

vanje
  • 10,180
  • 2
  • 31
  • 47
  • I also think that, but he might have a good reason to call a servlet from another. – João Rebelo Apr 12 '16 at 11:04
  • João Rebelo: Yes in very rare situations where you don't have access to the source code inside your own application. Most of the time it is just code smell and should be refactored. In fact if you consider to directly call another servlet this is a very good time for refactoring and make the code a little bit better. – vanje Apr 12 '16 at 11:17
  • True! I completely agree with your answer. I was just commenting that nevertheless you might want to do it just because you can! As some say, sometimes you need to learn the hard way :) – João Rebelo Apr 12 '16 at 16:20
0

Several options.

Making it static one way (I do not prefer).

Create a Class and supply required params and create instance in each servlet.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

Somewhat hackish way:

RequestDispatcher dispatcher = request.getRequestDispatcher("/someServletOfYours");
dispatcher.forward(request, response);

Now, implement the method of yours in doPost of your "someServletOfYours" class. In case you need to pass parameters, call the setAttribute method of ServletRequest, and fetch parameters from the request in your next servlet. From "someServletOfYourrs" you can redirect back to your original servlet. It will imitate a method call by means of http.

Artem Moskalev
  • 5,748
  • 11
  • 36
  • 55
-1

Servlet1

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Servlet1
 */
@WebServlet("/Servlet1")
public class Servlet1 extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        Servlet2 s = new Servlet2();
        s.CreateUser();

        response.getWriter().append("Served at: ").append(request.getContextPath());
    }
}

Servlet2

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Servlet1
 */
@WebServlet("/Servlet2")
public class Servlet2 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }


    public void CreateUser() throws FileNotFoundException{

        System.out.println("Create Users...");

    }
}

Output :

enter image description here

Rajesh Hatwar
  • 1,843
  • 6
  • 39
  • 58
  • No. You should never manually create instances of servlets. You don't even call `init()` - where a serlvet would create instances of dependencies. – Boris the Spider Apr 12 '16 at 12:18
  • 1
    @Boris the Spider I to agree you are telling right, but question doesn't demand any of those. more over i have removed every thing at the time of writing servlet class to show the answer. Because i seen the comment on question (4th point) and just gave the sample. vanje explained properly...! – Rajesh Hatwar Apr 12 '16 at 12:47
  • @Boris i am just giving what user need indeed. I don't want to west my time by considering every aspect. – Rajesh Hatwar Apr 12 '16 at 12:54
  • 2
    No one should call `new` on a call that `extends HttpServlet`. **ever**. – Boris the Spider Apr 12 '16 at 13:09