Applet - Servlet - Database - Servlet- Applet

Hi All,
I am using Oracle8i and IE 5.0. I am trying to retrieve the data from a db table and display it.
Sequence is as following:
1. Query passed to the applet.
2. Servlet excutes this query using JDBC and returns the resultset to applet.
3. Applet displaysthe results.
Is there anybody who has a code sample to do this, my id is [email protected] ? I am totally new to java and servlets. I would really appreciate any help.
Thanks a lot.
Manuriti
[email protected]

I've never dealt with the code to handle the applet portion of what you're trying to do, but I can help you with the servlet stuff.
Your servlet should contain code to accomplish the following steps:
1. Load an Oracle JDBC driver into memory.
2. Open a JDBC connection to the Oracle database.
3. Create a JDBC Statement object which contains the appropriate Oracle SQL code.
4. Execute the Statement object, which will return a ResultSet.
5. Read the ResultSet data.
6. Pool or close the Statement and Connection objects.
All of these steps are simple. Here's what they might look like in practice:
// load the Oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// open the connection
String cs = "jdbc:oracle:[email protected]:1521:DBNAME"; // connection string
String userName = "scott";
String password = "tiger";
Connection con = DriverManager.getConnection(cs, userName, password);
// create a Statement object
Statement stmt = con.createStatement();
// create a ResultSet object
ResultSet rs = stmt.executeQuery("select * from DUAL"); // your SQL here
// INSERT CODE HERE TO READ DATA FROM THE RESULTSET
// close the Statement object
stmt.close();
// close the Connection object
con.close();
So that's how you get data from your Oracle database. Now, how do you pass it to your applet? Well, this is hardly trivial. Typically, servlets return an HTML-formatted text stream. It is possible to have an applet communicate with a servlet, but that raises security issues that I don't fully understand. I believe you would have to have your user's browsers set to the lowest possible security settings, otherwise the browser won't let the applet open a socket to a foreign IP, but again, I'm shaky on that one.
Anywho, let me know if this was of help and if you have more questions on the servlet/applet stuff. I can probably help you with more specific questions,.

Similar Messages

  • Advantages and Disadvantages of  Applet over JSP/servlet

    Can some one please let me know what are the major advantages and disadvantages of using Applets over JSP/Servlet technology?

    Well, a servlet / jsp is generated on the server, an applet on the client side. That's the most important difference.
    Appelt's usually are for little applications like games and stuff, you can run in a browser.
    Servlets are for dynamic pages, for example database-viewing and stuf...

  • How to call a Applet from a servlet and vice versa...?

    Hi all
    Can anyone help me how to call a applet from a servlet and vice versa. When the applet is called it should contact the database (oracle8i) and get the data. When i submit the applet form the data in the applet should be saved in the database.
    Thanks in advance
    Kamalakannan

    Sweep is correct about requestDispatcher being another approach for inter-servlet delegation; the only issue that i recall with this approach is that it defaults the method of the destination servlet to the one it was called from...for example, calling servlet2 from within servlet1.post() resulted in the dispatcher attempting to utilize servlet2.post() - i believe that i searched for a parameterize solution to no avail :( (ended up handling the request by placing a "fake" doPost() in servlet2 that simply called servlet2.doGet())
    however, if your application is functioning correctly on your pc/webserver then the problem may be external to servlet communication (e.g. client webserver's ports not configured or blocked, missing runtime classes, etc.)
    my suggestion would be to set aside the programmatic concerns for the moment - what is the response if you open a browser on a client's machine and access the URL in question (i.e. http://clientserver:port/stefanoServlet)? If it will not respond to access in this manner then it certainly won't when your application calls for it.
    It's possible that there is a coding error but, given the info supplied, i'd start examining the environment, first. Let us know if you have any luck with the test i recommended or not (please provide abundant detail). Or, if you've found the solution then you may want to post back with a quick blub so the next person knows how to escape the trap.
    D

  • Is there any way to call the servlet from the applet

    hi all,
    My problem is that i have a applet .After the applet completes execution a servlet should be invoked.Is it possible to do so.
    I also want to pass a string array to the servlet.
    Is it possible to pass a string array to aservlet.
    If yes please do inform me that method.
    And from that servlet we should be able to redirect the the response of the applet to the servlet or JSP.
    The flow is some what lILE THIS
    APPLET TO SERVLET TO SERVLET/JSP

    Stop double posting. It won't help
    http://forum.java.sun.com/thread.jspa?threadID=642015
    and take a look at this.
    http://www.google.com/search?hl=en&q=applet+servlet+communication

  • Help needed to call a servlet from an applet

    Hi,
    can someone help me with the way to call a servlet from an applet.
    actually on click of a button i wanna call my servlet and save some data in DB.
    i am not able to call my servlet. see the sample code which i am trying..
    public void actionPerformed(ActionEvent event) {
    if (event.getActionCommand().equals("Upload")) {
    try {
    System.out.println("Upload button has been clicked -----------");
    URL url = new URL("http://localhost:8084/uploadApp/TestServlet");
    URLConnection urlConnection = url.openConnection();
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    ObjectOutputStream objOut = new ObjectOutputStream (urlConnection.getOutputStream());
    objOut.writeBytes(userId); // pass parameter to servlet
    objOut.flush();
    objOut.close();
    } catch (MalformedURLException ex) {
    Logger.getLogger(ButtonListener.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
    Logger.getLogger(ButtonListener.class.getName()).log(Level.SEVERE, null, ex);
    is there any problem with the code? please suggest.

    hii,
    checkout my add from, HTH
    [http://forums.sun.com/thread.jspa?threadID=5419921&messageID=10885709#10885709]
    ... kopik

  • Applet in a servlet

    I have an applet class in my webserver directory. How do i call it within a servlet .What should be the values for code and codebase properties. Kindly send me an example code if possible.
    Bye for now
    Thanx in advance
    Naveen

    You don't call an applet from a servlet. But if you want to include the applet in the HTML generated by the servlet, there are no special rules that apply because a servlet generated the HTML. Just follow the usual rules for applets embedded in HTML.

  • How can I use URLConnection to use applet communication with servlet?

    I want to send a String to a servlet in applet.I now use URLConnection to communicat between applet and servlet.
    ====================the applet code below=========================
    import java.io.*;
    import java.applet.Applet;
    import java.awt.*;
    import java.net.*;
    //I have tested that in applet get data from servlet is OK!
    //Still I will change to test in applet post data to a servlet.
    public class TestDataStreamApplet extends Applet
    String response;
    String baseurl;
    double percentUsed;
    String total;
    public void init()
    try
    java.net.URL url = new java.net.URL(getDocumentBase(),"/servlet/dataStreamEcho");
    //String currenturl=new String("http://lib.nju.edu.cn");
    java.net.URLConnection con = url.openConnection();
    //URL currentPage=getCodeBase();
    // String protocol=currentPage.getProtocol();
    // String host=currentPage.getHost();
    //int port=currentPage.getPort();
    // String urlSuffix="/servlet/dataStreamEcho";
    // URL url=new URL(protocol,host,port,urlSuffix);
    // URLConnection con=url.openConnection();
    con.setUseCaches(false);
    con.setDoOutput(true);
    con.setDoInput(true);
    ByteArrayOutputStream byteout = new ByteArrayOutputStream();
    PrintWriter out=new PrintWriter(byteout,true);
    String currenturl=new String("http://lib.nju.edu.cn");
    String var1=this.encodedValue(currenturl); //encode the data
    String data="currenturl="+var1;
    out.print(data);
    out.flush();
    con.setRequestProperty("Content-Length",String.valueOf(byteout.size()));
    con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    byteout.writeTo(con.getOutputStream());
    BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line;
    while((line=in.readLine())!=null)
         System.out.println(line);
    catch (Exception e)
    e.printStackTrace();
    private String encodedValue(String rawValue)
         return(URLEncoder.encode(rawValue));
    =========================The servlet code below=====================
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class DataStreamEcho extends HttpServlet
    {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
          res.setContentType("text/plain");
          PrintWriter out = res.getWriter();
          Runtime rt = Runtime.getRuntime();
          out.println(rt.freeMemory());
          out.println(rt.totalMemory());
          response.setContentType("text/html; charset=GBK");     
          request.setCharacterEncoding("GBK");
          PrintWriter out = response.getWriter();
          HttpSession session=request.getSession();
          ServletContext application=this.getServletContext();
          String currenturl=(String)session.getAttribute("currenturl");
          out.print(currenturl);
    =============================================================
    I have done up,but I found the program don't run as I have thought.
    Can you help me to find where is wrong?Very thank!

    You are trying to pass the current URL to the servlet
    from the applet, right?
    Well, what I put was correct. Your servlet code is
    trying to read some information from session data.
    request.getInputStream() is not the IP address of
    anything...see
    http://java.sun.com/products/servlet/2.2/javadoc/javax
    servlet/ServletRequest.html#getInputStream()
    Please read
    http://www.j-nine.com/pubs/applet2servlet/Applet2Servle
    .htmlNo,you all don't understand I.
    I want to send an Object to the server from a applet on a client.not url only.I maybe want to send a JPEG file instead.
    All I want is how to communicate with a servlet from an applet,send message to servlet from client's applet.
    for example,Now I have a method get the desktop picture of my client .and I want to send it to a server with a servlet to done it.How can I write the applet and servlet program?
    Now my program is down,But can only do string,can't not done Object yet.Can anyone help me?
    =======================applet=============================
    public void init()
    try
    java.net.URL url = new java.net.URL(getDocumentBase(),"/servlet/dataStreamEcho");
    //String currenturl=new String("http://lib.nju.edu.cn");
    java.net.URLConnection con = url.openConnection();
    //URL currentPage=getCodeBase();
    // String protocol=currentPage.getProtocol();
    // String host=currentPage.getHost();
    //int port=currentPage.getPort();
    // String urlSuffix="/servlet/dataStreamEcho";
    // URL url=new URL(protocol,host,port,urlSuffix);
    // URLConnection con=url.openConnection();
    con.setUseCaches(false);
    con.setDoOutput(true);
    con.setDoInput(true);
    ByteArrayOutputStream byteout = new ByteArrayOutputStream();
    PrintWriter out=new PrintWriter(byteout,true);
    String currenturl=new String("http://lib.nju.edu.cn");
    String var1=this.encodedValue(currenturl); //encode the data
    String data="currenturl="+var1;
    out.print(data);
    out.flush();
    con.setRequestProperty("Content-Length",String.valueOf(byteout.size()));
    con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    byteout.writeTo(con.getOutputStream());
    con.connect();
    BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line;
    while((line=in.readLine())!=null)
         System.out.println(line);
    catch (Exception e)
    e.printStackTrace();
    =======================servlet=============================
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
         response.setContentType("text/html; charset=GBK");
    //request.setCharacterEncoding("GBK");
    PrintWriter out = response.getWriter();
    HttpSession session=request.getSession();
    ServletContext application=this.getServletContext();
    //String currenturl=(String)session.getAttribute("currenturl");
    String currenturl=(String)request.getParameter("currenturl");
    out.print(currenturl);
    File fileName=new File("c:\\noname.txt");
    fileName.createNewFile();
    FileOutputStream f=new FileOutputStream(fileName); //I just write the String data get from
    //applet to a file for a test.
    byte[] b=currenturl.getBytes();
    f.write(b);
    f.close();
    }

  • How to call a method in the servlet from an applet

    I want to get the data for the applet from the servlet.
    How to call a method that exits in the servlet from the applet? I want to use http protocol to do this.
    Any suggestions? Please help.
    thanks

    Now that Web Services is around, I'd look at possibly implement a Web Service call in your applet, which can then be given back any object(s) on return. Set up your server side to handle Web Service calls. In this way, you can break the applet out into an application should you want to (with very little work) and it will still function the same

  • How to forward an applet page to servlet/jsp?

    I have an applet in imageMap.jsp file. This applet displays a map. When user enters the page of imageMap.jsp, they will see the map . If user clicks a point of the map, the latitude and longitude of that point should be sent to Search.java servlet and search results should replace the current page.
    My Search.java servlet works well.
    I think I should add mouse event in the applet. I can use MouseEvent.getX() and MouseEvent.getY() in the applet to get latitude and longitude. But I do not know how to go from this applet to servlet. How can I forward applet page to servlet?

    The <jsp:plugin> action is used in pages to generate client specific HTML tags involving download and execution of the applet that is specified in the tag.

  • Can a servlet launch an Applet or Application?

    Hello:
    Is it possible for a servlet to launch an Applet or Application? I am new to servlet technology, and am trying to find out what I can and cannot do. I've gone through much of the forums, and see that servlet can correspond with Applets, but can servlets launch something other than a servlet? If so, can someone please provide an implementation example?
    Thanks in advance for your replies!

    Thanks for replying, but I would love for you to be a bit more specific. My knowledge of servlets is limited. I just purchased Marty Hall's moreservlet book, and am just getting done with chapter 3. I would like to write a servlet from which I can launch an applet, but that is not covered in his book (I don't think). I know it can be done because I've seen a code snippet using the applet tag and codebase, but I do not know how to put it together in a complete servlet. Can you please help? I would truly appreciate it!

  • Notifying an applet (from a servlet)

    Is there a way to send events to an applet (on Internet, not just on Intranet)? To tell the applet that it should upgrade the view or something. The event may be sent as a string, but is it more difficult to send another (serialized) object ? Thanks for any answers !

    First off, I'm assuming you want to "push" the data/events to the applet, not have the applet request the data. The first reply's method would require that the applet make some kind of request to the servlet.
    I don't think there is a way to do this with servlets directly, but you could have a servlet set up an object on the server that "pushed" the events to the applet(s). You would need to come up w/ your own protocol for sending / receiving the events (I'm sure there are some examples on the net). You might even be able to use some kind of RMI to go back and forth between the server and applet.
    The problem you will run into here though could be firewalls. The port number you use to communicate between the server and the applet may not be able to be port 80, since you usually have to have administrative priviledges to use any ports below 1024. But if you aren't on port 80, you will have trouble going through some firewalls (this may not be a problem here though).
    You might want to search for some sample code that implements a Chat servlet / applet. This kind of thing would be similar to what you are asking about.

  • A servlet  From an applet

    Dear friends,
    Hope you are doing well.
    I am facing a problem of how to call a servlet from an applet.
    Any help , please forward it.
    thanks
    vishal

    You can communicate with servlet from an applet, using URL connection, and then send POST/GET methods through HTTP protocol, here is a code snippet,
    // applet side, this method will send a POST method to the servlet and then get url openstream to read a
    // returned object from the servlet, params should be in the form param1=value&param2=value etc...
    public Object getObjectFromServlet(String servletName,String params) {
        Object object = null;
        try {
          URL url = new URL(codeBase,
                            contextRoot + servletName + params);
          URLConnection con = url.openConnection();
          con.setUseCaches(false);
          InputStream in = con.getInputStream();
          ObjectInputStream result = new ObjectInputStream(in);
          object = result.readObject();
          result.close();
          in.close();
        catch (ClassNotFoundException ex) {
          System.err.println("ClassNotFoundException caught:" + ex.getMessage());
        catch (MalformedURLException ex) {
          System.err.println("MalformedURLException caught:" + ex.getMessage());
        catch (IOException ex) {
          System.out.println("IOException caught:" + ex.getMessage());
        return object;
    //servlet side
    public void doPost(HttpServletRequest request, HttpServletResponse response){
          //Extract all the necessary supplied parameters from the request object and configurations.
           String param1 = request.getParameter("param1");
           String param2 = request.getParameter("param2");
      try {
            ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());
            out.writeObject(object);
            out.close();
          catch (IOException ioe) {
            System.err.println("IOException caught:" + ioe.getMessage());
    }

  • Sending an image from an applet to  a servlet

    I have sucessfully set up a Serializable connection between my applet and my servlet. However if i try to pass an object that implements the serializable interface that has a BufferedImage object encapsulated in it... a NotSerializableException is thrown... The reason i am doing this is that i have to save the image to disk (Server Side).. If someone could advise me on a way to solve this problem or provide a better solution to my problem i would grateful

    Implementing Serializable isn't enough to make a class serializable: every not-transient field must implement Serializable too.
    Said this, you can marshal an array of int (arrays are serializable of course!) containing your pixels:
    //Applet side
    BufferedImage img;
    Raster r=img.getRaster();
    int[] pixels=r.getPixels(0,0,r.getWidth(),r.getHeight());
    //serialize pixels, possibly along with width, height and imageType of BufferedImage
    //Servlet side
    int[] pixels;
    //deserialize pixels and possibly width,height and imageType
    BufferedImage img=new BufferedImage(width,height,imageType);
    img.getRaster().setPixels(0,0,width,height);Hope it helps

  • High performance writing Chinese from an Applet to a Servlet

    Hi,
    I am using DataOutput/InputStreams to wrtie UTF (Chinese Characters from an Applet to a servlet) Now, I already HAVE the chinese characters in the applets memory and I need to write them to the servlet. I am using the "writeUTF()" and "readUTF" methods in the Input and output Streams. Now I want to replace the Data Streams with buffered Streams to improve performance. What is the equivalent method for buffereed Streams?
    DataOutputStream output = new DataOutputStream(connection.getOutputStream());
    output.writeUTF(chineseString);
    output.close();
    DataInputStream input = new DataInputStream(connection.getInputStream());
    String response = input.readUTF();
    input.close();
    Thanks.
    Regards,
    Carlos

    Hi Carlos,
    I don't think there is a method for buffered streams that is exactly equivalent to writeUTF, but you could use the character stream reader/writer pair as follows:
    OutputStreamWriter osw = new  OutputStreamWriter(connection.getOutputStream (), "UTF8");
    Writer output = new BufferedWriter(osw);     
    InputStreamReader  isr = new InputStreamReader(connection.getInputStream (), "UTF8");
    Reader input = new BufferedReader(isr);     now, however, since these classes don't have a read/write String method you will need to write out your string character by character followed by an end of Line:
    loop through characters in output String:
         output.write(aChar)
    output.newline ()and then read it back in as a line using:
    input.readLine() Post back if it's unclear.
    Regards,
    Joe

  • Applet that calls servlet

    How to achieve something like this: i ve got a simple applet that calls servlet or JSp. when i get the response i would like to show it like a new page canceling the previous one with applet. Please Help. I have no idea how to using the data from response produce a new page. Nay resources hints??

    In the second case:
    You want to use the URL and URLConnection to POST or GET information to the server
    that the applet came from (if not you have to sign the applet or set up policy).
    The response from the server should be opened in a new window.
    To post the data:
    http://javaalmanac.com/egs/java.net/Post.html
    This will get you a string, after you got that string you can use JSObject to call a javascript
    method.
    for example your applet:
    import netscape.javascript.*; // either in jaws.jar or plugin.jar in your lib dir
    ..... extends Applet{
    public Sting newpage;
    ... method that opens URLConnection and receives response in strRes
    this.newpage = strRes
    JSObject win;
    win = JSObject.getWindow(this);
    win.eval("methodThatOpensWindow()");
    The html page looks like
    <object ...... id="myapplet" myascript="true">
    function methodThatOpensWindow(){
    var win = window.open('','','');
    win.document.write(document.getElementById("myapplet").newpage);
    ...

Maybe you are looking for