tags:

views:

43

answers:

2

Hello everyone,

I have two servlets: LoginServlet and MailServlet. LoginServlet queries a mysql table using jdbc to get a string(eMail). What I want is to forward this string to MailServlet which in turn will send an email to that e-mail ID sent by LoginServlet.

My question is how do I call and send the variable eMail to MailServlet, from LoginServlet? I thought of creating an instance of the MailServlet as :

MailServlet servlet = new MailServlet();

And then use the servlet object to call the function doGet() in MailServlet. But I am feeling that there is some error in this as this is not the right way to call a servlet. So how do I call and pass a variable to MailServlet?

+1  A: 

The purpose of a servlet is to respond to an HTTP request. What you should do is refactor your code so that the logic you want is separated from the other servlet and you can reuse it independently. So, for example, you might end up with a Mailman class, and a MailServlet that uses Mailman to do its work. It doesn't make sense to call a servlet from another servlet.

If what you need is to go to a different page after you hit the first one, use a redirect:

http://www.java-tips.org/java-ee-tips/java-servlet/how-to-redirect-a-request-using-servlet.html

Edit:

For example, suppose you have a servlet like:

public class MailServlet extends HttpServlet {
    public  void doPost(HttpServletRequest request,HttpServletResponse response)
                                  throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        response.setContentType("text/html");

        Message message =new MimeMessage(session1);

        message.setFrom(new InternetAddress("[email protected]"));
        message.setRecipients(...);
        message.doSomeOtherStuff();
        Transport.send(message);

        out.println("mail has been sent");
    }
}

Instead, do something like this:

public class MailServlet extends HttpServlet {
    public  void doPost(HttpServletRequest request,HttpServletResponse response)
                                  throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        response.setContentType("text/html");

        new Mailer().sendMessage("[email protected]", ...);

        out.println("mail has been sent");
    }
}

public class Mailer {
    public void sendMessage(String from, ...) {
        Message message =new MimeMessage(session1);
        message.setFrom(new InternetAddress("[email protected]"));
        message.setRecipients(...);
        message.doSomeOtherStuff();
        Transport.send(message);
    }
}
RMorrisey
Your point is good, but I'd rather end up with a `LoginServlet` and a `Mailer`. The whole `MailServlet` is unnecessary.
BalusC
My project involves applets as the front end and servlets as the back end. Since MailServlet needs an e-mail ID, LoginServlet provides it. Hence the need for inter servlet communication.
mithun1538
I agree - you probably don't need a MailServlet. You should have a LoginServlet, and then a servlet for the page that the user would go to when they log in. The mailing can be done behind-the-scenes by one of the other servlets. The only reason you would want a MailServlet would be if the user has to go to a particular screen to configure their mail preferences, or set up a mail to be sent out. It makes sense to have a servlet-based architecture, but that doesn't mean every operation needs its own servlet.
RMorrisey
@mithun: a servlet is only useful if you'd like to control/preprocess/postprocess a HTTP request. In a basic flattened JSP/Servlet setup you should think of just one servlet per JSP page. You have a login JSP. So you need a LoginServlet. You don't have a mail JSP. So you don't need a MailServlet. Just make it a normal Java class. E.g. `Mail mail = new Mail(from, to, subject, message); Mailer mailer = new Mailer(); mailer.send(mail);` or so.
BalusC
In any case, if you really need to go from one servlet to another, a redirect is the way to accomplish that.
RMorrisey
Actually, this is with a purpose of reusing code. I already have a MailServlet servlet sending mails for some other purpose. Since I just need to send an e-mail to an ID that I retrieved in LoginServlet servlet, I wanted to use the same MailServlet servlet again.
mithun1538
@mithun: then the `MailServlet` has too much responsibilities (tight coupled). You should refactor the mailing logic from it into reuseable Java classes so that it's reuseable in other places.
BalusC
Can you alter the structure of the MailServlet so that it makes calls to another class that takes care of the mailing? You can reuse your servlet code. Just pull it out so that there is a separate object that handles the actual business of sending mail. I'll edit my response to give an example.
RMorrisey
We're not attacking you, just trying to help out =) It's a good idea to reuse your code; we're trying to give you suggestions to push you in the right design direction
RMorrisey
@RMorrisey :) never felt that way. I just wanted to give more information so that you guys could help me better. @BalusC @RMorrisey umm, I think i will end up doing that, but I wanted to know if there are any mechanisms for servlet to servlet communication. Searched the net for the same, but all examples were very vague.
mithun1538
See the code sample I posted in my revised answer
RMorrisey
@RMorrisey yep. got the idea. Will accept this for now, but it still isn't what I am looking for.
mithun1538
What about the redirect, then?
RMorrisey
Have to run, I'll be back later on
RMorrisey
Nope. Redirect doesnt work. Don't know how to send eMail variable to second servlet by redirecting.
mithun1538
A: 

I think this may be what you were originally looking for: a request dispatcher. From the Sun examples documentation:

public class Dispatcher extends HttpServlet {
   public void doGet(HttpServletRequest request, 
         HttpServletResponse response) {
      request.setAttribute("selectedScreen",
         request.getServletPath());
      RequestDispatcher dispatcher =
         request.getRequestDispatcher("/template.jsp");
      if (dispatcher != null)
         dispatcher.forward(request, response);
   }
   public void doPost(HttpServletRequest request, 
            HttpServletResponse response) {
      request.setAttribute("selectedScreen",
         request.getServletPath());
      RequestDispatcher dispatcher =
         request.getRequestDispatcher("/template.jsp");
      if (dispatcher != null)
         dispatcher.forward(request, response);
   }
}

This appears to specify a new URL, for a different servlet, JSP, or other resource in the same container, to generate the response instead of the current servlet.

From the tutorial here: http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPTags6.html

RMorrisey
This seems way above my understanding, cause I am not that well versed with servlets. Anyway, your first answer solved the problem. Not quite the answer I was expecting, but it did the trick anyway.
mithun1538