Sending a vector to a servlet

i want to send a vector to a servlet via an applet. i think i have done this properly.
but i then want to write the information in this vector to a file and i'm wondering why its not working
i've read postings about how if everything i store in it implements Serializable, i can just serialize it to file.
i don't completely understand how to do this.
i'm putting strings into the vector before i send it to the servlet....will this cause a problem?
are strings serializable?
thanks
Andy

i'm not getting an error, but it appears like the POST isn't working...i think there must be something wrong with how i try to call the servlet
i think it might have something to do with my setRequestProperty...
here's my code....
/************applet************/
public void sendVector(Vector sendingVector)
URL baseURL = getCodeBase();
String protocol = baseURL.getProtocol();
String host = baseURL.getHost();
int port = 808;
try
String urlSuffix = "/servlet/contactlist.WriteToServlet";
URL servletURL = new URL(protocol, host, port, urlSuffix);
URLConnection conn = servletURL.openConnection();
// inform the connection that we will send output and accept input
conn.setDoInput(true);
conn.setDoOutput(true);
// Don't use a cached version of URL connection.
conn.setUseCaches (false);
conn.setDefaultUseCaches (false);
// Specify the content type that we will send binary data
conn.setRequestProperty ("Content-Type", "application/octet-stream");
// send the student object to the servlet using serialization
ObjectOutputStream outputToServlet = new ObjectOutputStream(conn.getOutputStream());
// serialize the object
outputToServlet.writeObject( sendingVector );
outputToServlet.flush();
outputToServlet.close();
} catch (IOException io) { io.printStackTrace(); }
} // end sendVector
/*********servlet*************/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
try
// get an input stream from the applet
ObjectInputStream inputFromApplet = new ObjectInputStream(request.getInputStream());
// read the serialized student data from applet
Vector passInfo = (Vector)inputFromApplet.readObject();
inputFromApplet.close();
for(int i =0; i < passInfo.size(); i++) System.out.println(passInfo.get(i));
// make this so that the vector filename has no spaces
FileWriter writer = new FileWriter("G:\\Intranet\\wwwroot\\Contact\\contactlist\\Departments\\" + getFileTitle(passInfo.get(1).toString()) + ".htm");
// prints information to the file
int a;
for(a = 0; a < (passInfo.size()-1); a++)
{  writer.write(passInfo.get(a) + "\n");
writer.write(passInfo.get(a).toString());
writer.flush();
writer.close();
catch(Exception e) { e.printStackTrace(); }
public void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
doGet(request, response);
} // end doPut

Similar Messages

  • Sending an email from a servlet

    Hi Guys,
    Im trying to send an email from a servlet. I am using the following code:
    IMPORTING LIBRARIES
    import java.util.*;
    import java.io.*;
    import javax.servlet.http.*;
    import javax.servlet.*;
    //importing JDBC
    import java.sql.*;
    //email
    import java.net.*;
    import java.text.*; // Used for date formatting.
    BEGIN CLASS
    public class Email3 extends HttpServlet
         private Socket smtpSocket = null;
         private DataOutputStream os = null;
         private DataInputStream is = null;
    public void doPost (HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    PrintWriter out = res.getWriter();
    OUTPUT TAGS FOR WEBPAGE
         out.println("<html>");
    out.println("<head>");
    out.println("<title>FYP</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<center>");
    send email
              //Date dDate = new Date();
              //DateFormat dFormat = _
         //DateFormat.getDateInstance(DateFormat.FULL,Locale.US);
         String m_sHostName="localhost";
         int m_iPort=25;
              try
              { // Open port to server
                   smtpSocket = new Socket(m_sHostName, m_iPort);
                   os = new DataOutputStream(smtpSocket.getOutputStream());
                   is = new DataInputStream(smtpSocket.getInputStream());
                   if(smtpSocket != null && os != null && is != null)
                   { // Connection was made.  Socket is ready for use.
                        out.println("Connection was made. Socket is ready for use.");
                        //[ Code to send email will be placed in here. ]
                        try
                             {   os.writeBytes("HELLO\r\n");
                             // You will add the email address that the server
                             // you are using know you as.
                             os.writeBytes("MAIL From: <[email protected]>\r\n");
                             // Who the email is going to.
                             os.writeBytes("RCPT To: <[email protected]>\r\n");
                             //IF you want to send a CC then you will have to add this
                             os.writeBytes("RCPT Cc: <[email protected]>\r\n");
                             // Now we are ready to add the message and the
                             // header of the email to be sent out.
                             os.writeBytes("DATA\r\n");
                             os.writeBytes("X-Mailer: Via Java\r\n");
                             //os.writeBytes("DATE: " + dFormat.format(dDate) + "\r\n");
                             os.writeBytes("From: Me <[email protected]>\r\n");
                             os.writeBytes("To: YOU <[email protected]>\r\n");
                             //Again if you want to send a CC then add this.
                             os.writeBytes("Cc: CCDUDE <[email protected]>\r\n");
                             //Here you can now add a BCC to the message as well
                             //os.writeBytes("RCPT Bcc: BCCDude<[email protected]>\r\n");
                             String sMessage = "Your subjectline.";
                             os.writeBytes("Subject: Your subjectline here\r\n");
                             os.writeBytes(sMessage + "\r\n");
                             os.writeBytes("\r\n.\r\n");
                             os.writeBytes("QUIT\r\n");
                             // Now send the email off and check the server reply.
                             // Was an OK is reached you are complete.
                             String responseline;
                             while((responseline = is.readLine())!=null)
                             {  // System.out.println(responseline);
                             out.println("responseline= "+responseline+"<br>");
                             if(responseline.indexOf("Ok") != -1)
                                  //out.println("responseline"+responseline);
                             break;
                             catch(Exception e)
                             {  System.out.println("Cannot send email as an error occurred.");
                                  out.println("Cannot send email as an error occurred.");
              catch(Exception e)
              { System.out.println("Host " + m_sHostName + "unknown"); }
              out.println("</center>");
              out.println("</body>");
              out.println("</html>");
              out.close();
    }//end class
    it compiles fine, the connection was made ok but im not receiving the email. When the email is sent off the server reply does not seem to be Ok, as the print statement i tried there is not being executed. When i print the content of my responseline= variable before the if statement i get the following:
    Connection was made. Socket is ready for use. responseline= 220 centaur.elec.qmul.ac.uk ESMTP Exim 3.16 #2 Thu, 09 Jan 2003 15:54:34 +0000
    responseline= 500 Command unrecognized
    responseline= 250 is syntactically correct
    responseline= 550 relaying to prohibited by administrator
    responseline= 500 Command unrecognized
    responseline= 503 No recipient(s).
    responseline= 500 Command unrecognized
    responseline= 500 Command unrecognized
    responseline= 500 Command unrecognized
    responseline= 500 Command unrecognized
    responseline= 500 Command unrecognized
    responseline= 500 Command unrecognized
    responseline= 500 Command unrecognized
    responseline= 500 Command unrecognized
    responseline= 221 Closing connection. Good bye.
    Can anyone help?
    Is there an easier way to send an email from a servlet?
    Thanks
    tzaf

    It's not a matter of "easier way" to send mail from servlet...you are missing a crucial element in your code: authorization to send mail. You need something like this (some of which you have already so note what is different):
            Properties properties = new Properties();
            properties.put("mail.smtp.host", String3 );
            properties.put("mail.smtp.dsn.notify", "SUCCESS" );
            properties.put("mail.smtp.host", "mailservernamegoeshere");
            properties.put("mail.smtp.auth", "true");
            MyAuthenticator auth = new MyAuthenticator();
            auth.setUser("user whos account you want to use goes here");
            auth.setPassword("user password goes here");
            Session session = Session.getDefaultInstance( properties,auth );Here is the auth class:
    class MyAuthenticator extends Authenticator {
       protected String m_strUser     = null;
       protected String m_strPassword = null;
       protected PasswordAuthentication getPasswordAuthentication()  {
          return new PasswordAuthentication(m_strUser,m_strPassword);
       public void setUser(String strUser)  {
          m_strUser = strUser;
       public void setPassword(String strPassword)  {
          m_strPassword = strPassword;

  • I want to send a response from the servlet and then call another servlet.

    Hi,
    I want to send a response from the servlet and then call another servlet. can this happen. Here is my scenario.
    1. Capture all the information from a form including an Email address and submit it to a servlet.
    2. Now send a message to the browser that the request will be processed and mailed.
    3. Now execute the request and give a mail to the mentioned Email.
    Can this be done in any way even by calling another servlet from within a servlet or any other way.
    Can any one Please help me out.
    Thanks,
    Ramesh

    Maybe that will help you (This is registration sample):
    1.You have Registration.html;
    2.You have Registration servlet;
    3.You have CheckUser servlet;
    4.And last you have Dispatcher between all.
    See the code:
    Registration.html
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <HTML>
      <HEAD>
        <TITLE>Hello registration</TITLE>
      </HEAD>
      <BODY>
      <H1>Entry</H1>
    <FORM ACTION="helloservlet" METHOD="POST">
    <LEFT>
    User: <INPUT TYPE="TEXT" NAME="login" SIZE=10><BR>
    Password: <INPUT TYPE="PASSWORD" NAME="password" SIZE=10><BR>
    <P>
    <TABLE CELLSPACING=1>
    <TR>
    <TH><SMALL>
    <INPUT TYPE="SUBMIT" NAME="logon" VALUE="Entry">
    </SMALL>
    <TH><SMALL>
    <INPUT TYPE="SUBMIT" NAME="registration" VALUE="Registration">
    </SMALL>
    </TABLE>
    </LEFT>
    </FORM>
    <BR>
      </BODY>
    </HTML>
    Dispatcher.java
    package mybeans;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.ServletException;
    import java.io.IOException;
    import javax.servlet.RequestDispatcher;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Dispatcher extends HttpServlet {
        protected void forward(String address, HttpServletRequest request,
                               HttpServletResponse response)
                               throws ServletException, IOException {
                                   RequestDispatcher dispatcher = getServletContext().
                                   getRequestDispatcher(address);
                                   dispatcher.forward(request, response);
    Registration.java
    package mybeans;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Registration extends Dispatcher {
        public String getServletInfo() {
            return "Registration servlet";
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            ServletContext ctx = getServletContext();
            if(request.getParameter("logon") != null) {          
                this.forward("/CheckUser", request, response);
            else if (request.getParameter("registration") != null)  {         
                this.forward("/registration.html", request, response);
    CheckUser.java
    package mybeans;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class CheckUser extends Dispatcher {
        Connection conn;
        Statement stat;
        ResultSet rs;
          String cur_UserName;
        public static String cur_UserSurname;;
        String cur_UserOtchestvo;
        public String getServletInfo() {
            return "Registration servlet";
        public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            try{
                ServletContext ctx = getServletContext();
                Class.forName("oracle.jdbc.driver.OracleDriver");
                conn = DriverManager.getConnection("jdbc:oracle:oci:@eugenz","SYSTEM", "manager");
                stat = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
               String queryDB = "SELECT ID, Login, Password FROM TLogon WHERE Login = ? AND Password = ?";
                PreparedStatement ps = conn.prepareStatement(queryDB); 
               User user = new User();
            user.setLogin(request.getParameter("login"));
            String cur_Login = user.getLogin();
            ps.setString(1, cur_Login);
            user.setPassword(request.getParameter("password"));
            String cur_Password = user.getPassword();
            ps.setString(2, cur_Password);
         Password = admin");
            rs = ps.executeQuery();
                 String sn = "Zatoka";
            String n = "Eugen";
            String queryPeople = "SELECT ID, Surname FROM People WHERE ID = ?";
           PreparedStatement psPeople = conn.prepareStatement(queryPeople);
                      if(rs.next()) {
                int logonID = rs.getInt("ID");
                psPeople.setInt(1, logonID);
                rs = psPeople.executeQuery();
                rs.next();
                       user.setSurname(rs.getString("Surname"));
              FROM TLogon, People WHERE TLogon.ID = People.ID";
                       ctx.setAttribute("user", user);
                this.forward("/successLogin.jsp", request, response);
            this.forward("/registration.html", request, response);
            catch(Exception exception) {
    }CheckUser.java maybe incorrect, but it's not serious, because see the principe (conception).
    Main is Dispatcher.java. This class is dispatcher between all servlets.

  • Problem sending a httprequest to a servlet java class

    i know that entering an URL like this in the browser can call the servlet class:
    http://www.xxxxxxxx.com/RequestHandler?action=showallitems
    but.....
    what codes do i need to send a httprequest to the servlet in java coding?
    thanks again.

    You mean like a normal Java code, not HTML, Request Dispatch, or something like that?
    If so, then you will want to use a URLConnection (HttpURLConnection). First, create a java.net.URL to the location you want. Then open a connection (which returns a URLConnection - if your URL uses an http protocol it will actually use an HttpURLConnection and can be casted).
    Use the methods in java.net.HttpURLConnection to adjust the headers, and parameters, and set up the method to use. Then get the input stream to commit the request and read the response from the server.
    Make sure you read the API for URLConnection and HttpURLConnection thoroughly. There are some quirks and specific order of events that need to be followed. Also read http://www.javaworld.com/javaworld/jw-03-2001/jw-0323-traps.html for info on how to properly use a URLConnection.

  • Unable to send a byte to a Servlet

    Hello,
    I am trying to execute a simple example of HTTP communication found in the Carol Hammer's book "Creating Mobile Games". I can send data from the servlet to the midlet, but i cannot send a single byte from the midlet to the servlet.
    I am using WTK version 2.2 for the devlopment and Tomcat 5.5.17 for running the servlet (in localhost)
    Here is the (partial) code of the midlet :
    public void communicationWithServlet() {
    HttpConnection connection = null;
    DataOutputStream dos = null;
    DataInputStream dis = null;
    try {
    connection = (HttpConnection)Connector.open(SERVER_URL);
    ((HttpConnection)connection).setRequestMethod(HttpConnection.POST);
    int rc = connection.getResponseCode();
    if (rc != HttpConnection.HTTP_OK) {
    throw new IOException("HTTP response code: " + rc);
         dos = connection.openDataOutputStream();
         System.out.println("before");
         dos.write((byte)100);
         System.out.println("after");
         dos.flush();
    dis = connection.openDataInputStream();
         byte[] data = new byte[10];
         dis.readFully(data);
         message = new String(data);
         System.out.println(message);
    } catch(Exception e) { }
    finally {
    try {
    if(dis != null) { dis.close();}
    if(connection != null) {connection.close();}
         catch(Exception e) {}
    The midlet is blocked by the instruction : dos.write((byte)100);
    Here is the code of the servlet :
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class SimpleServlet extends HttpServlet {
         public void doPost(HttpServletRequest requete, HttpServletResponse reponse)
              throws ServletException, IOException {
                   InputStream is = requete.getInputStream();
                   int data= is.read();
                   reponse.setContentType("text/html");
                   PrintWriter out = reponse.getWriter();
                   out.println("Hello");
                   out.close();
    Many thanks in advance for your help

    If I delete the following lines :
    int rc = connection.getResponseCode();
    if (rc != HttpConnection.HTTP_OK) {
    throw new IOException("HTTP response code: " + rc);
    my problem is solved : the byte is sent to the servlet
    But I would understand : why the call to the getResponseCode method prevents the midlet to send the byte to the servlet ?
    Thanks for your help

  • Sending emails+attachment from a servlet

    Hi all,
    I'd like to send emails from within my servlet. There must be a possibility to attach a file that has been uploaded to the server in a previous request.
    Currently I'm using sun.net.smtp.SmtpClient to send simple emails.
    Does the sun-smtp-package provide a way to attach a file to an email?
    regards
    Steffen

    I'm not sure but I think the sun.net.smtp package is part of J2EE. I didn't need to download it. You will need a Base64-Encoding algorithm for transforming the file-data (the attachment) into the email message. OReillys servlet package provides a class for this (www.servlets.com).
    Below is an example how to send an email with a file attached to it. You will have to specify the name of an SMTP-Server. If you do not have one you can (for testing purposes) direct the email into a text file.
    try{
         String host = /** @todo place your smtp-server name or IP here */
         SmtpClient smtp = new SmtpClient(host);
         smtp.from(from);
         smtp.to(toList);
         PrintStream out = smtp.startMessage();
         Base64Encoder b64e = new Base64Encoder(out); // Base64Encoder is also a Stream which we will only use for the attachment-data
         /* uncomment this if there is no smtp-server. The email will be stored in a file
         File fEml = new File(/** @todo add your filePath here */+File.separatorChar+"out.eml");
         PrintStream out = new PrintStream(new FileOutputStream(fEml));*/
         out.println("From: "+from);
         out.println("To: "+toList);
         out.println("Subject: "+subject);
         out.println("Date: "+date.toString());
         out.println("MIME-Version: 1.0");
         // we have to declare the email multipart/mixed to notify the email client that this mail contains sub parts of different content-types
         out.println("Content-Type: multipart/mixed;");
         // the boundary-string separates the sub parts (just like in HTTP-Multipart-Requests)
         out.println("\tboundary=\"----=_next_part\"");
         out.println("\r");
         out.println("This is a multipart message in MIME format.");
         out.println("\r");
         // first sub part starts here - its the text message
         out.println("------=_next_part");
         // this sub part contains only plain text
         out.println("Content-Type: text/plain;");
         out.println("\tcharset=\"iso-8859-1\"");
         out.println("Content-Transfer-Encoding: 7bit");
         out.println("\r");
         // Message text goes here
         out.println(/** @todo place your message here */);
         out.println("\r");
         // now the attachment
    out.println("------=_next_part");
    out.println("Content-Type: application/octet-stream;");
    out.println("\tname=\""+fileName+"\"");
    out.println("Content-Transfer-Encoding: base64");
    out.println("Content-Disposition: attachment;");
    out.println("\tfilename=\""+fileName+"\"");
    out.println("\n");
    // encode file piece by piece
    File f = new File(/** @todo place your filepath here */+File.separatorChar+fileName);
    FileInputStream fis = new FileInputStream(f);
    int i = 0;
    do{
    byte[] content = {0, 0, 0};
    i = fis.read(content, 0, 3);
    if (i != -1){
                   b64e.write(content);
         }//if
    }while(i != -1);
    fis.close();
    fis = null;
    f = null;
         // this is it, all there's left to do is to flush our output-stream and clean up
         out.flush();
         b64e.close();
         out.close();
         b64e = null;
         smtp.closeServer();
         out = null;
         smtp = null;
    }catch(IOException ioe){
         ioe.printStackTrace();
    }//catch
    HTH
    Steffen

  • Problem in sending image from applet to servlet

    dear friends,
    i have a need to send an image from applet to servlet via HttpConnection and getting back that image from applet.
    i am struggling with this sice many hours and got tired by searching any post that would help me but haven't got yet.
    i tried using this code but it dosent make any execution sit right. i got NPE at ImageIcon.getDescription() line;
    at applet side
          jf.setContentPane(getJContentPane());
                     FileDialog fd=new FileDialog(jf,"hi");
                     fd.setMode(FileDialog.LOAD);
                     fd.setVisible(true);   
                     v=new Vector();
                     try{                                                
                               FileInputStream fis=new FileInputStream(new File(fd.getDirectory()+fd.getFile()));      
                               byte[] imgbuffer=new byte[fis.available()];
                               fis.read(imgbuffer);
                               ImageIcon imgdata=new ImageIcon(imgbuffer);
                               v.add(0,imgicon);
                                String strwp ="/UASProject/Storeimage";              
                                URL servletURL = new URL(getCodeBase(),strwp);             
                                HttpURLConnection servletCon = (HttpURLConnection)servletURL.openConnection();       
                                servletCon.setDoInput(true); 
                                servletCon.setDoOutput(true);
                                servletCon.setUseCaches(false);
                                servletCon.setDefaultUseCaches(false);   
                                servletCon.setRequestMethod("POST");     
                                servletCon.setRequestProperty("Content-Type", "application/octet-stream");   
                                servletCon.connect();            
                                ObjectOutputStream oboutStream = new ObjectOutputStream(servletCon.getOutputStream());                     
                                oboutStream.writeObject(v);
                                v.remove(0);
                                oboutStream.flush();      
                                oboutStream.close();  
                                //read back from servlet
                                ObjectInputStream inputStream = new ObjectInputStream(servletCon.getInputStream());
                                 v= (Vector)inputStream.readObject();                     
                                 imgicon=(ImageIcon)v.get(1);
                                 showimg.setIcon(imgicon);
                                 this.getContentPane().validate();
                                 this.validate();  
                                inputStream.close();                                                        
                             //  repaint();
                     }catch(Exception e){e.printStackTrace();}  and this is at servlet side
            try {       
                         Vector v=new Vector();                    
                         ObjectInputStream inputFromjsp = new ObjectInputStream(request.getInputStream());                                      
                          v = (Vector)inputFromjsp.readObject();                                                                                                          
                          imgicon=(ImageIcon)v.get(0);                     
                          inputFromjsp.close();            
                          System.out.println(imgicon.getDescription());                                      
                          v.remove(0);
                          v.add(1,imgicon);
    //sending back to applet
                           response.setContentType("application/octet-stream");
                          ObjectOutputStream oboutstream=new ObjectOutputStream(response.getOutputStream());            
                          oboutstream.writeObject(v);
                          oboutstream.flush();
                          oboutstream.close();
                   } catch (Exception e) {e.printStackTrace();}  i really need your help. please let me out of this headche
    thanks
    Edited by: san_4u on Nov 24, 2007 1:00 PM

    BalusC wrote:
    san_4u wrote:
    how can i made a HttpClient PostMethod using java applets? as i have experience making request using HttpURLConnection.POST method. ok first of all i am going make a search of this only after i will tell. please be onlineOnce again, see link [3] in my first reply of your former topic.
    yeah! i got the related topic at http://www.theserverside.com/tt/articles/article.tss?l=HttpClient_FileUpload. please look it, i am reading it right now and expecting to be reliable for me.
    well what i got, when request made by html code(stated above) then all the form fields and file data mixed as binary data and available in HttpServletRequest.getinputstream. and at servlet side we have to use a mutipart parser of DiskFileItemFactory class that automatically parse the file data and return a FileItem object cotaing the actual file data,right?.You can also setup the MultipartFilter in your environment and don't >care about it further. Uploaded files will be available as request attributes in the servlet.is the multipartfilter class file available in jar files(that u suggested to add in yours article) so that i can use it directly? one more thing the import org.apache.commons.httpclient package is not available in these jar files, so where can got it from?
    one mere question..
    i looked somewhere that when we request for a file from webserver using web browser then there is a server that process our request and after retrieving that file from database it sends back as response.
    now i confused that, wheather these webservers are like apache tomcat, IBM's webspher etc those processes these request or there is a unique server that always turned on and process all the request?
    because, suppose in an orgnisation made it's website using its own server then, in fact, all the time it will not turned on its server or yes it will? and a user can make a search for kind of information about this orgnisation at any time.
    hopes, you will have understand my quary, then please let me know the actual process
    thanks
    Edited by: san_4u on Nov 25, 2007 11:25 AM

  • Send email from j2me through servlet

    Hi people,
    i hope you can help me because i am new in network programming.
    I am trying to send email from j2me to googlemail account I have 2 classes EmailMidlet (which has been tested with wireless Toolkit 2.5.2 and it works) and the second class is the servlet-class named EmailServlet:
    when i call the EmailServlet, i get on the console:
    Server: 220 mx.google.com ESMTP g28sm19313024fkg.21
    Server: 250 mx.google.com at your service
    this is the code of my EmailServlet
    import java.io.*;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.text.*;
    import java.util.Date;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class EmailServlet extends HttpServlet {
       public void doPost(HttpServletRequest request, HttpServletResponse response)
             throws IOException, ServletException {
          System.out.println("____emailservlet.doPost");
          response.setContentType("text/plain");
          PrintWriter out = response.getWriter();
          System.out.println("______________________________");
          out.println();
          String to = request.getParameter("to");
          System.out.println("____________________________to" + to);
          String subject = request.getParameter("subject");
          String msg = request.getParameter("msg");
          // construct an instance of EmailSender
          System.out.println("servlet_to" + to);
          send("[email protected]", to, subject, msg);
          out.println("mail sent....");
       public void send(String from, String to, String subject, String msg) {
          Socket smtpSocket = null;
          DataOutputStream os = null;
          DataInputStream is = null;
          try {
             smtpSocket = new Socket("smtp.googlemail.com", 25);
             os = new DataOutputStream(smtpSocket.getOutputStream());
             is = new DataInputStream(smtpSocket.getInputStream());
          } catch (UnknownHostException e) {
             System.err.println("Don't know about host: hostname");
          } catch (IOException e) {
             System.err
                   .println("Couldn't get I/O for the connection to: hostname");
          if (smtpSocket != null && os != null && is != null) {
             try {
                os.writeBytes("HELO there" + "\r\n");
                os.writeBytes("MAIL FROM: " + from + "\r\n");
                os.writeBytes("RCPT TO: " + to + "\r\n");
                os.writeBytes("DATA\r\n");
                os.writeBytes("Date: " + new Date() + "\r\n"); // stamp the msg
                                                    // with date
                os.writeBytes("From: " + from + "\r\n");
                os.writeBytes("To: " + to + "\r\n");
                os.writeBytes("Subject: " + subject + "\r\n");
                os.writeBytes(msg + "\r\n"); // message body
                os.writeBytes(".\r\n");
                os.writeBytes("QUIT\r\n");
                // debugging
                String responseLine;
                while ((responseLine = is.readLine()) != null) {
                   System.out.println("Server: " + responseLine);
                   if (responseLine.indexOf("delivery") != -1) {
                      break;
                os.close();
                is.close();
                smtpSocket.close();
             } catch (UnknownHostException e) {
                System.err.println("Trying to connect to unknown host: " + e);
             } catch (IOException e) {
                System.err.println("IOException: " + e);
       } 1.when i print "to" in EmailServlet also:
      String to = request.getParameter("to");
          System.out.println("____________________________to" + to);  it show null on the console :confused:
    2. ist this right in case of googlemail.com?
      smtpSocket = new Socket("smtp.googlemail.com", 25);  I would be very grateful if somebody can help me.

    jackofall
    Please don't post in old threads that are long dead. When you have a question, please start a topic of your own. Feel free to provide a link to an old thread if relevant.
    I'm locking this thread now.
    db

  • Problem sending email using javamail in servlet

    I try this code and make some changes of my own http://forums.sun.com/thread.jspa?threadID=695781.
    When i run the program the confirmtaion shows that the mail has been sent, but when i check in my inbox there's no the message. I'm using gmail and need to authenticate the username and password. I guess the error caused in the servlet.
    Here's the code for my servlet :
    import java.io.*;
    import java.util.Properties;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.mail.internet.*;
    import javax.mail.*;
    public class ServletEx extends HttpServlet {
       public void doPost(HttpServletRequest request, HttpServletResponse response)
             throws IOException, ServletException {
          System.out.println("____emailservlet.doPost");
          response.setContentType("text/plain");
          PrintWriter out = response.getWriter();
          System.out.println("______________________________");
          out.println();
          String to = request.getParameter("to");
          System.out.println("____________________________to" + to);
          String subject = request.getParameter("subject");
          String msg = request.getParameter("msg");
          // construct an instance of EmailSender
          System.out.println("servlet_to" + to);
          send(username, to, subject, msg);
          //send("[email protected]", to, subject, msg);
          out.println("mail sent....");
            String username = "[email protected]";
            String password = "my_password";
            String smtp = "smtp.gmail.com";
            String port = "587";
       public void send(String username, String to, String subject, String msg) {
            Properties props = new Properties();
            props.put("mail.smtp.user", username);
            props.put("mail.smtp.host", smtp);
            props.put("mail.smtp.port", port);
            props.put("mail.smtp.starttls.enable","true"); // just in case, but not currently necessary, oddly enough
            props.put("mail.smtp.auth", "true");
            //props.put("mail.smtp.debug", "true");
            props.put("mail.smtp.socketFactory.port", port);
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.fallback", "false");
            SecurityManager security = System.getSecurityManager();
            try
                Authenticator auth = new SMTPAuthenticator();
                Session session = Session.getInstance(props, auth);
                //session.setDebug(true);
                MimeMessage message = new MimeMessage(session);
                message.setText(msg);
                message.setSubject(subject);
                message.setFrom(new InternetAddress(username));
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
                Transport.send(message);
            catch (Exception mex)
                mex.printStackTrace();
       public class SMTPAuthenticator extends javax.mail.Authenticator {
            public PasswordAuthentication getPasswordAuthentication(String username, String password)
                return new PasswordAuthentication(username, password);
    }Actually it's been a long time for me to develope this program, especially with the authenticate smtp. Any help would be very appreciated :)

    Accordingly to your stackTrace, I think that you miss some utility jar from Geronimo app. server.
    As you are using Application server that is J2EE compliant, so there is an own JavaMail implementation embeded and used by the Server. To fix this problem you have to find and add to your calsspath a jar-file that contains Base64EncoderStream.class

  • How to send XML via HTTPS in Servlet

    I am new to Java. I need to make a servlet which can send a message via HTTPS with a content type of XML to another web server when it is called. each msg is proceeded with a header in the following format:
    requestID=rid&userID=uid&password=mypd
    and a detail information in XML:
    <S_Request>
    <requestControllID>1-rf200</requestControlID>
    <zipCode>99012</zipCode>
    <orderQuantity>35</orderQuantity>
    </S_Request>
    I have basic idea of how to send an http post with parameter string by using the Redirect function but don't know how to deal with the XML detail. Any one has idea about this? Any help will be greatly appreciated!

    This is what I did for one of my projects;
    String myXML = "all the xml tags and fields";
    URL url = new URL("https://www.somesite.com");
    HttpsURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    OutputStream outXML = connection.getOutputStream();
    outXML.write(myXML.getBytes());
    I think you can add the requestID and all to the begining of the string myXML
    Good luck
    Rajesh

  • Setting filename sending output to Excel form servlet

    Hi All
    I am successfully sending my tab separated output to Excel from the servlet using the following:
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition","inline;filename=statistics.txt");
    The output is automatically opened in a new window using excel.
    However the sheet in excel is named based on the url of the servlet it came from, not statistics as i have specified. The main issue with this, apart from the niceness of it, is that if the user then generates another excel output from the same servlet then the new file is not loaded as excel already has a file by that name open and can't handle duplicate names.
    I have seen many references to this syntax, but it doesn't quite work for me.
    I hope someone can clarify what i am missing here.
    Thanks in advance.

    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.ServletException;
    import java.io.IOException;
    * @author Ravi Desu (rdesu)
    * @version 1.0
    * $Id: ExcelGen.java, Jun 1, 2004 4:43:13 PM rdesu Exp $
    public class ExcelGen extends HttpServlet {
    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("Worksheet 1");
    HSSFRow row = sheet.createRow((short) 0);
    HSSFCell cell = row.createCell((short) 0);
    cell.setCellValue("This is text in a cell");
    httpServletResponse.setContentType("application/vnd.ms-excel");
    workbook.write(httpServletResponse.getOutputStream());
    In your web.xml:
    <servlet>
    <servlet-name>ExcelGenSrvlt</servlet-name>
    <servlet-class>ExcelGen</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>ExcelGenSrvlt</servlet-name>
    <url-pattern>/ExcelGen.xls</url-pattern>
    </servlet-mapping>
    download the org.apache.poi jars from
    http://www.apache.org/dyn/closer.cgi/jakarta/poi/
    http://jakarta.apache.org/poi/

  • Continuously send data to applet through servlet

    Hi,
    I'm trying to write a servlet that, once activated, will continuously send data back to a thread in the client. My problem is that the data isn't actually sent until the stream is closed. I'm hoping someone can point me in the right direction:
    Servlet code:
    public class testStream extends HttpServlet {
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    int[] somedata = new int [1];
    somedata [0] = 1000;
    String contentType =
    "application/x-java-serialized-object";
    response.setContentType(contentType);
    ObjectOutputStream out =
    new ObjectOutputStream(response.getOutputStream());
    while (true) {
    try {
    out.writeObject(somedata );
    System.out.println("Sent " + somedata [0]);
    somedata [0]++;
    } catch(Exception ie) {}
    out.flush();
    Thread.yield();
    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    doGet(request, response);
    Applet side code:
    * <P>
    * Taken from Core Servlets and JavaServer Pages
    * from Prentice Hall and Sun Microsystems Press,
    * http://www.coreservlets.com/.
    * &copy; 2000 Marty Hall; may be freely used or adapted.
    public class testStream implements Runnable {
    private boolean isDone = false;
    private URL dataURL;
    public testStream(String urlSuffix, URL currentPage) {
    try {
    // Only the URL suffix need be supplied, since
    // the rest of the URL is derived from the current page.
    String protocol = currentPage.getProtocol();
    String host = currentPage.getHost();
    int port = currentPage.getPort();
    dataURL = new URL(protocol, host, port, urlSuffix);
    Thread imageRetriever = new Thread(this);
    imageRetriever.start();
    } catch(MalformedURLException mfe) {
    System.err.println("Bad URL");
    isDone = true;
    public void run() {
    try {
    retrieveImage();
    } catch(IOException ioe) {
    isDone = true; // will never get hit
    public boolean isDone() {  // meaningless now with infinite loop
    return(isDone);
    private void retrieveImage() throws IOException {
    URLConnection connection = dataURL.openConnection();
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDefaultUseCaches (false);
    connection.setRequestProperty("Content-Type", "application/x-java-serialized-object");
    ObjectInputStream in = null;
    try {
    in = new ObjectInputStream(connection.getInputStream());
    } catch (Exception pe) { System.err.println(pe); }
    while (true) {
    // loop forever requesting data
    try {
    // The return type of readObject is Object, so
    // I need a typecast to the actual type.
    int[] someData = (int[]) in.readObject();
    System.err.println(someData[0]);
    } catch(ClassNotFoundException cnfe) {
    System.err.println("received NULL");
    Thread.yield();

    The original example was based on HTTP. I suppose yours is too. The HTTP protocol is for sending and receiving packets of finite length, and that is not your requirement. So don't use HTTP. Probably socket communications would be your best bet.

  • How to send a String to a Servlet using a HTTP POST

    Well, I have designed a servlet that receives a HTTP POST, I was testing it using an HTML form to send (using POST) information, now, I have coded a Java App to send it a string, I don't know how to make the servlet recognize that info so it can make its work, I am posting both codes (Servlet & API) so anyone can guide me and tell me how and where to modify them
    Servlet:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.sql.*;
    public class xmlwriter extends HttpServlet
    public void service(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    ServletOutputStream salida = res.getOutputStream();
    res.setContentType("text/HTML");
    String cadena = req.getParameter("cadena");
    File f1 = new File ("c:/salida.xml");
    FileWriter out = new FileWriter(f1);
    f1.createNewFile();
    out.write(cadena);
    out.close();
    salida.println("OK");
    Now, the JAVA API is:
    import java.io.*;
    import java.net.*;
    public class HTTPSender {
    public static void main(String[] args) throws Exception {
    URL url1 = new URL
    ("http://localhost:8080/XMLSender/xmlwriter");//internal site
    URLConnection UrlConnObj1 = url1.openConnection();
    HttpURLConnection huc1 = (HttpURLConnection)UrlConnObj1;
    huc1.setRequestMethod("POST");
    huc1.setDoOutput(true);
    huc1.setDoInput(true);
    huc1.setUseCaches(false);
    huc1.setDefaultUseCaches(false);
    String cadena = ""
    + "<root>\n"
    + "<tlf>$TLF$</tlf>\n"
    + "<op>$OP$</op>\n"
    + "<sc>$SC$</sc>\n"
    + "<body>$BODY$</body>\n"
    + "</root>";
         PrintWriter out = new PrintWriter(huc1.getOutputStream());
    System.out.println("string="+cadena);
    out.write(cadena);
    out.close();
    I'm a JAVA newbie, so, maybe I'm getting a bad idea of what I need to do, anyway, every (detailed) help is welcome. What my servlet should do (and it doesn't when I send the message through the API) is to write a file with the info received.

    I'm not trying to send a string from a WEB Page, I'm tryring to send it using a JAVA program, I mean, using a HTTPSender, in fact, I already have made the code to do that:
    import java.io.*;
    import java.net.*;
    public class HTTPSender {
    public static void main(String[] args) throws Exception {
    try {
    String cadena = "Message to be written";
    // Send data
    URL url = new URL("http://localhost:8080/XMLSender/xmlwriter");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(cadena);
    wr.flush();
    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
    // Process line...
    wr.close();
    rd.close();
    } catch (Exception e) {
    And modified my servlet so it can receive anything:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.sql.*;
    public class xmlwriter extends HttpServlet
    public void service(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    ServletOutputStream salida = res.getOutputStream();
    res.setContentType("text/HTML");
    String cadena = req.toString();
    File f1 = new File ("c:/salida.xml");
    FileWriter out = new FileWriter(f1);
    f1.createNewFile();
    out.write(cadena);
    out.close();
    salida.println("OK");
    Now the problem is that, the servlet in fact DOES create the file, but....the file is empty, that means that no info is arriving to the servlet, why?, how should I send it then? I repeat FORGET about a Web Page Form, that is in the past and I don't need that.

  • How to send a HTTP request to servlet in java application

    I'm new in Java. I need to send a HTTP request with parameters to servlet in a java aplication. Here is my code. It can be compiled but always threw an exceptions when I ran it. Can anyone help?
    package coreservlets;
    import java.io.*;
    import java.net.*;
    public class PostHTTP
         public static void main(String args[])
              throws IOException, UnknownHostException {
              try
              // URL and servlet
                   URL myURL = new URL("http://pc076/servlet/coreservlets.OffHold");
                   URLConnection c = myURL.openConnection();
                   c.setUseCaches(false);
                   c.setDoOutput(true);
                   ByteArrayOutputStream byteStream = new ByteArrayOutputStream(512);
                   PrintWriter out = new PrintWriter(byteStream, true);
    //parameters
                   String postData = "REASON_CODE=3B&RSPCODE=JSmith&CASENUM=NA795401&REPLY=123&SOURCE=XYZ&REPLYLINK=http://pc076/servlet/coreservlets.ShowParameters";
                   out.print(postData);
                   out.flush();
                   String lengthString = String.valueOf(byteStream.size());
                   c.setRequestProperty("Content-Length", lengthString);
                   c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                   byteStream.writeTo(c.getOutputStream());
                   BufferedReader in =     new BufferedReader(new InputStreamReader
                                                 (c.getInputStream()));
                   String line;
                   //String linefeed = "\n";
                   //resultsArea.setText("");
                   while((line = in.readLine()) != null) {
                        System.out.println(line);
                        //resultsArea.append(linefeed);
              catch(IOException ioe) {
              // Print debug info in Java Console
              System.out.println("IOException: " + ioe);

    here are some updates to your code I haven't tested it running
    post again if you still have trouble
    URL myURL = new URL("http://pc076/servlet/coreservlets.OffHold");
    HttpURLConnection c = (HttpURLConnection)myURL.openConnection();
    c.setDoInput(true);
    c.setDoOutput(true);
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream(512);
    String lengthString = String.valueOf(byteStream.size());
    c.setRequestProperty("Content-Length", lengthString);
    c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    PrintWriter out = new PrintWriter(byteStream, true);
    //parameters
    String postData = "REASON_CODE=3B&RSPCODE=JSmith&CASENUM=NA795401&REPLY=123&SOURCE=XYZ&REPLYLINK=http://pc076/servlet/coreservlets.ShowParameters";
    out.print(postData);
    out.flush();
    byteStream.writeTo(c.getOutputStream());
    // connect
    c.connect();
    BufferedReader in = new BufferedReader(new InputStreamReader
    (c.getInputStream()));
    String line;
    while((line = in.readLine()) != null)
        System.out.println(line);

  • How to send a email from a servlet

    Hi,
    I'm trying to send a e-mail from a servlet, but I don't know how to do it!!
    Please , help me
    Thanks

    Have a look at the Java Mail API and at the JAVA Mail Forum.

Maybe you are looking for