Post parameters to a JSP from an applet

Hello,
Is there a way to send a post request to a JSP page from an applet ? Here is the scenario I am looking for :
In Test.jsp, I invoke an applet. The applet should then do a POST request to the JSP. Currently, I am able to send a JSP request by appending parameters to the query string as
getAppletContext().showDocument(new URL(getDocumentBase(),"Test.jsp?querystring")); in the applet. But this will be showing the parameters in the URL. I would like to have the parameters sent as "POST". I tried doing something like
String data = "All URL encoded parameter names and values";
URL postURL = new URL("Test.jsp");
conn = (HttpURLConnection)postURL.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
But how do I pass the control back to the JSP ? Any thoughts ?

Thanks for all your responses. I posted the request and still couldn't get it working. Here is my code
osDetection.jsp:
<%@ page contentType="text/html; charset=UTF-8" %>
<% // Get all the request parameters
String userOSVersion = request.getParameter("osVersion") == null ? "" : request.getParameter("osVersion");
String detect = request.getParameter("detect") == null ? "" : request.getParameter("detect");
%>
<% if(detect.equals("")) { %>
          <span>detect os version</span>
<% } %>
<%     if("os".equals(detect)) { %>
<div align="center">
<object width="250" height="75">
<param name="type" value="application/x-java-applet" />
<param name="code" value="Detection.class" />     
<comment>
<embed type="application/x-java-applet" code="Detection.class" width="1" height="2" />
<noembed>No OS detected</noembed>
</comment>
</object>
</div>     
<% } %>
OS Version: <%=userOSVersion%>
Detect:          <%=detect%>
Detection.java
import java.applet.*;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Detection extends Applet {
     public void init() {
          HttpURLConnection conn = null;
          try {
               String data = "osVersion=" + URLEncoder.encode(System.getProperty("os.version"),"UTF-8");
               URL postURL = new URL("http://localhost:8080/detection/osDetection.jsp");
               System.out.println("posting to the url :");
               conn = (HttpURLConnection)postURL.openConnection();
               conn.setRequestMethod("POST");
               conn.setDoOutput(true);
               System.out.println("connection open");
               OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
               wr.write(data);
               wr.flush();
               wr.close();
               // Get the response code
               int code = conn.getResponseCode();
               System.out.println("Response code of the object is "+code);
               if (code==200) {
               System.out.println("OK");
               // Get the response
               BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
               String line;
               while ((line = rd.readLine()) != null) {
               System.out.println(line);
               rd.close();
               conn.disconnect();
          } catch(Exception ex) {
               System.out.println("Error:" + ex.getMessage());
Am I missing something here ? I see the response being written to the Java console but how do I transfer the control back to JSP to do further processing in the JSP ?
Thanks much in advance.

Similar Messages

  • File Not found error when calling Form Post Method to a JSP from JSP Portlet

    I have built a set of JSP forms using post method to call other JSPs. Normally, the code looks like
    <form name="MyForm" action="MyJsp.jsp" method="post">
    I migrated the calling form containing this code to a portlet, but not the MyJsp.jsp. When I submit the form, I get a file not found in Jserv.log
    Exception:javax.servlet.ServletException: java.io.FileNotFoundException: D:\servlet\RegisterCompany.jsp (The system cannot find the file specified)
    [14/06/2001 13:59:59:679 PDT] JspServlet: unable to dispatch to requested page: Exception:javax.servlet.ServletException: java.io.FileNotFoundException: d:\oracle\isuites\apache\apache\MyJsp.jsp (The system cannot find the file specified)
    I notice that launching the calling jsp from a portlet, my opriginal context that uses ../Apache/Apache/htdocs is not being searched for the JSp. Why is this? Moreover, I try to set up an Alias in httpd.conf file to the this director and use it with the jsp in the action tag, but still get an error that my jsp servlets/Myjsp can't be found. Why is it insiting on looking at servlets context instead of htdocs.
    I have none of these issues outside of Portal30 using IAS.
    regard

    Initially, I couldn't do this unless I moved tghe jsp's up to the root directory of IAS, i.e ../Apache/Apache. Nomrally, htdocs is my doc directory for IAS. I could not do http:\\myUrl\htdocs\myJsp. If I tgried this, I got an error in Apache error logg that said can't find file ..\htdocs\htdocs\MyJsp.jsp.
    If I just tried the the URL http:\\myUrl\MyJsp.jsp with Jsp file in htdocs, I would get an error in the Jserve log that file d:\oracle\isuites\apache\apache\MyJsp.jsp could not be found. Once I moved the file MyJsp to Apache/Apache directory, it could be found using http:\\myUrl\MyJsp.jsp. Later, I delted these files and kept the ones in htdocs and they continued to work.
    I'm confused why launching pages through portal isn't consistant with Apache Standards. Where is the documentation that tells me how to configure context and aliases for pages launched from portal pages?
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Sue Vickers ([email protected]):
    David,
    Passing information using Portal is different than just using Apache/Jserv. Does it work in portal if you use the absolute path?
    <form name="MyForm" action="http://host.domain/MyJSP.jsp" method="post">
    Portal will not be on the same relative path as your Apache, so you may need to adjust your action somehow.
    Thanks,
    Sue<HR></BLOCKQUOTE>
    null

  • Opening a jsp from an applet in a frame?

    this is the code i'm using to open a new jsp and send some stuff in the header. it works fine but it does not support the frameset i am using... any ideas how i can open this page in the frame?
    thanks
    URL url = getCodeBase();
    try{
    getAppletContext().showDocument (new URL (url+"AcceptHousePos.jsphouse="+myHouse.getString()));
    catch(MalformedURLException e) {
    showStatus("URL not found");

    Do you want to open a jsp application in a frame when you click on the applet?If so, there is a programme in http://www.globalleafs.com -Java-Java Applets 's download section. Check it out.

  • Passing input parameters from an applet to a JSP page

    Hello all,
    Yes, its one of these questions which I have tried to find a solution from the already large number of postings but with no luck. I'm still a novice to Java/JSP so bear with me.
    Consider this scenario.
    1. An applet which has two input boxes (say First name and surname). 2. These parameters will be passed to a JSP page (so the applet will call a JSP page).
    3. The JSP will have have the necessary logic (or actually a JavaBean will) to connect to a database and add a new record with these parameters (first name and surname).
    I also need to consider editing/updating the record in the database. So a JSP page will connect to the database, retrieving the required record from the database and then display the parameters back in an applet in two input boxes (first name and surname) to be edited and saved again.
    I have been able to develop a similar application using simple HTML forms to add and update records in a database so I'm not worried about the database connectivity simply the issue of passing parameters from the applet to the JSP page and vice versa (for edit/update).
    Once i've managed to do this with input boxes, I can experiment with the other input types radios, checkboxes, select etc.
    Many thanks in advance,
    Assad

    create an URL object with u'r specified link of the java class and send the parameters..write trhis action in any buttonclick event in u'r applet.

  • Passing parameters from an applet to a URL

    I need to pass information from an applet to an html page or JSP page, is this possible? Thanks.

    Yes you can!
    The following code might works (with some modifications ;)):
    AppletContext context = this.getAppletContext();
    URL url = new URL("http://host:port/path?parameter=value");
    context.showDocument(url, "windowName");In addiction, consider java.net.URLEncoder.encode() method to encode properly your parameters.
    Regards
    Paolo

  • Using POST from an applet

    Hi,
    I need to connect to a URL from my applet and have the results show up in a new browser window. I have to use POST method since I need to submit a lot of parameters with the request. If I could have used GET method instead, this could have easily been accomplished using showDocument method. Even though applets can connect to a URL using POST, I could not locate any information on how to display the results in a new browser window. Anyone know how this can be accomplished?

    To POST data to servlet :
    - get data in applet by using getText() or getSelectedItem ...
    - Open connection by URL class
    - Open outputStream by BufferedWriter class
    - Using write(String) to write data then close the tream
    - to Receive data from servlet : getInputStream by BufferedReader class and then using readLine() to read data .
    - Notice : you must make a protocol for your Applet and Servlet able to interface with it other
    Good luck !

  • How can I return some values from an applet invoked by jsp:plugin tag

    My JSP is something like that:
    <html>
         <head>
                 <title> . . . </title>
         </head>
         <script>
              function getValueFromApplet()
                   var src = document.pinApplet.checkPin();
                   document.myForm.j_username.value = document.pinApplet.tokenizeName(src);
                   alert(document.myForm.j_username.value);
                   document.myForm.j_password.value = document.pinApplet.tokenizePassword(src);
                   alert(document.myForm.j_password.value);
         </script>
            <body>
                    <jsp:plugin type="applet"
                          code="PinApplet.class"
                       codebase="/idp"
                       name="pinApplet"
                                width="300"
                                height="300">
                         <jsp:fallback> Authentication Form is not supported by the browser </jsp:fallback>
              </jsp:plugin>
                    <form action="https://xxx.xxx.xxx"
                   name="myForm"
                   method="post" onSubmit="return getValueFromApplet()">
              <table>
                   <td><input type="submit" value="OK" >
                   <td><input type="hidden" id="j_username" name="j_username" value=""></td>
                   <td><input type="hidden" id="j_password" name="j_password" value=""></td>
              </table>
              </form>
         </body>checkPin() returns "alice--alice"
    tokenizeName() returns the first token: alice
    tokenizePassword() returns the second token: alice
    When I test the applet in the IDE, it returns the values properly, but not in the JSP invokation.

    evnafets wrote:
    javascript will not be executing on the server. You can rule that one out.
    Is your Applet being initialised correctly?
    Where have you got the classes for it? I think the applet doesn't need any kind of initialization, because it doesn't have any variables and all the process is made in the method called by onsubmit()
    The applet is composed only by one class and I'm totally sure that the class is placed in the correct place.
    evnafets wrote:
    I would say put in a couple more alerts - one before the call to the applet, one after.
    put some logging statements in your applet to see if it gets there.In the javascript, there are two alerts between the three calls to the applet. Where do you advise me to put more alerts?
    I don't understand what do you refer when you say "logging statements"
    I am going to test again the call to the applet in order to find some kind of code that can be invalid or that can make the function to "crash"

  • Call a JSP from applet and display the results in the browser

    Hello All,
    I have written an applet which performs some functionality at the clinets browser. When the applets method finishes exectution, I would like to call
    a jsp. The results of the JSP should be displayed like a normal page in the browser.
    I tried creating a HttpURLConnection and calling the jsp but two things happened
    1. The jsp call failed because the applet doesn't have a valid session id.
    2. even if I disable the valid user check at the jsp, the results of the jsp are returned as a set of bytes to the applet. They are not displayed in the browser window.
    Then I tried applet.getAppletContext().showDocument()... However with this api I cannot do a POST operation on the JSP with some input data because this takes only a URL as an input parameter.
    Please help me in this problem and I will be very gratefull to you.
    1. applet uses the same session id as the browser so that when applet makes a request to the jsp it does not get user invalid exception.
    2. the results of the jsp are displayed on the browser and not given to the applet.
    Thank you so much for your help.
    regards,
    Abhishek.

    I hope this can help you
    I made a package calls fun
    and a clsss calls JspTestingFun
    package fun;
    public class JspTestingFun{
      private String sample = "welcome to jsp";
      //Access sample property
      public String getSample() {
        return sample;
      //Access sample property
      public void setSample(String newValue) {
        if (newValue!=null) {
          sample = newValue;
    }then I make a jsp file
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
    <%@ taglib uri="http://java.sun.com/jstl/sql" prefix="sql" %>
    <%@ page import =  "fun.JspTestingFun"%>
    <html>
    <head>
    <title>
    jspTest
    </title>
    </head>
    <jsp:useBean id="mytest" scope="session" class="fun.JspTestingFun" />
    <jsp:setProperty name="mytest" property="*" />
    <body bgcolor="#ffffff">
    <%
    mytest.getSample();
    %>
    <h1>
    Just for testing
    </h1>
    <form method="post">
    <br>Enter anything   :  <input name="sample"><br>
    <br><br>
    <input type="submit" name="Submit" value="Submit">
    <input type="reset" value="Reset">
    <br>
    this what we get<jsp:getProperty name="mytest" property="sample" />
    </form>
    </body>
    </html> 

  • Redirecting browser from an applet with POST

    Hi,
    How can I cause an applet to redirect a browser window using a POST request?
    Thanx,
    Yaron

    redirect using postIf you mean send a post request and let the http resonese redirect the page then
    you have 2 options.
    1.
    set values of html object from the applet (calling javascript):
    this.getAppletContext().showDocument(
                             new URL("javascript: someJSFunction('param','param');"));Submit the form from the applet calling javascript (see above).
    Note that I don't use JSObject since that one makes mozilla crash since jre 1.5
    2.
    Use URL and URLConnection to POST your data.
    Then use this.getAppletContext().showDocument() to navigate the the redirected URL (according to response from the URLConnection)
    Using POST:
    http://forum.java.sun.com/thread.jspa?threadID=645830&messageID=3816955
    3rd post

  • Applet in jsp from servlet, but error: ClassNotFoundExcep

    The problem that I'm having is already mentioned a couple of times in this forum, but unfortunately I haven't found a solution, in thread http://forum.java.sun.com/thread.jspa?forumID=33&threadID=239405 is proposed solution but it's not working for me.
    I'm developing a project in IBM's Websphere Developer Studio 5.1.1. and JRE that I'm using for this project is 1.4.2. I have created servlet "CompanyDocument.java" and applet "SimpleApplet.java". Applet was created as single project and then imported into this one, that means that it's contained in current project as "SimpleAppletPackage.jar". I have placed jar in folder "Applets", Websphere automatically creates folder "simpleAppletPackage" and in it's root complied "SimpleApplet.class".
    When I put following code in the jsp page applet works correctly when application is runed.
    <APPLET code="simpleAppletPackage/SimpleApplet.class" codebase="Applets" archive="SimpleAppletPackage.jar" width="250" height="250"></APPLET>
    But I wanted to create jsp from servlet. So I used this code within servlet:
    out.print("<APPLET code=\"simpleAppletPackage/SimpleApplet.class\" codebase=\"Applets\"");
    out.print("archive=\"SimpleAppletPackage.jar\" width=\"250\" height=\"250\"></APPLET>");
    But I get an error (when running, no error when compiling). The error is copied from Java console:
    load: class simpleAppletPackage/SimpleApplet.class not found.
    java.lang.ClassNotFoundException: simpleAppletPackage.SimpleApplet.class
    at sun.applet.AppletClassLoader.findClass AppletClassLoader.java:162)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
    at sun.applet.AppletClassLoader.loadClass(AppletClassLoader.java:123)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
    at sun.applet.AppletClassLoader.loadCode(AppletClassLoader.java:566)
    at sun.applet.AppletPanel.createApplet(AppletPanel.java:619)
    at sun.plugin.AppletViewer.createApplet(Unknown Source)
    at sun.applet.AppletPanel.runLoader(AppletPanel.java:548)
    at sun.applet.AppletPanel.run(AppletPanel.java:299)
    at java.lang.Thread.run(Thread.java:534)
    Caused by: java.io.IOException: open HTTP connection failed.
    at sun.applet.AppletClassLoader.getBytes(AppletClassLoader.java:265)
    at sun.applet.AppletClassLoader.access$100(AppletClassLoader.java:43)
    at sun.applet.AppletClassLoader$1.run(AppletClassLoader.java:152)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.applet.AppletClassLoader.findClass(AppletClassLoader.java:149)
    ... 9 more
    In the same time I'm creating some more code from servlet and it works with no errors and is shown in browser properly (it consists of connection to Oracle, formatting table, and presenting data within that table).
    Any idea? I'm totally stuck.

    In your browser, look at the HTML code that gets sent to the browser and see if there is something wrong with it.
    Specifically, I would look at the code near the <APPLET ..></APPLET> tags, both before and after and look for stray quotes, brackets, or what not.
    Finally, I would look inside the <APPLET ...> tag. It appears to me that the output will probably be:
    <APPLET code="simpleAppletPackage/SimpleApplet.class" codebase="Applets"archive="SimpleAppletPackage.jar" width="250" height="250"></APPLET>See, you may be missing a space between the "Applets" and the archive=. Try making the second out.print look like this:
    out.print(" archive=\"SimpleAppletPackage.jar\" width=\"250\" height=\"250\"></APPLET>"); See the extra space at the start of the output?

  • Passing FORM parameters when opening form from a JSP

    Hi,
    is it possible to pass form parameters when opening the form from a JSP as a URL. If yes then what should be the way in which parameters has to be passed.
    thanks.

    Hi,
    Sorry there was some confusion.
    I want to pass parameters to a (D2K) form from a JSP. I'm able to open the D2K form but unable to pass the parameters into that form.
    Is it possible to pass parameters to D2k FORM from a JSP...
    Thanks

  • Set VM parameters from an applet

    Hi all,
    When I run an applet I need to start the VM with this parameter:
    -Djava.rmi.server.hostname=localhost
    How can I set this parameter from an applet to correctly start the VM?!?!?
    Thanks in advance!!

    Hi all,
    When I run an applet I need to start the VM with this
    parameter:
    -Djava.rmi.server.hostname=localhost
    How can I set this parameter from an applet to
    correctly start the VM?!?!?
    Thanks in advance!!You can't do it from the applet, since the vm is already started when you execute the applet. But I think you can do this after your applet has started.
    System.setProperty("java.rmi.server.hostname", "localhost");I'm not sure if an applet is allowed to do that (It can throw an security exception), but you could give it a try.
    /Kaj

  • Create a new file on server from an applet

    Hello!
    I 'm trying to create a text file on server from an applet, i have permissions to write on server and i'm running in apache, my code is
    public void write () {
    try{
    URL url = new URL("http://localhost/bnm/hello.txt");
    URLConnection urlcon = url.openConnection();
    urlcon.setDoOutput(true);
    urlcon.setUseCaches(true);
    PrintWriter pt = new PrintWriter
    (new OutputStreamWriter (urlcon.getOutputStream()));
    String str = new String(URLEncoder.encode("this is output applet ")) ;
    pt.print(str);
    pt.flush();
    catch(Exception e)
    e.printStackTrace();
    The result is nothing, the file isn�t created, but the code don't throw exceptions.
    Ah! in other example, i can read a file of server fro m the applet, the problem is to write
    Anybody, knows the matter??
    Excuse my poor english :P
    Thanks for all.

    I had the same needs and didn't know whether this was possible, due to applets security restriction. So I searched the Web and found some contradictory information. I will explain what I think is the situation, to give you an answer, but also so that other people can tell me whether I understood correctly.
    1) Unless you sign it, an applet cannot write files directly, either client-side or server-side. All what it can do to access a file server-side (except .jar files ?) is opening a http connection, which allows only to retrieve data. When I try to run code such as yours, I get this exception :
    java.net.UnknownServiceException: protocol doesn't support output
         at java.net.URLConnection.getOutputStream(URLConnection.java:679)
    2) As Ares_Man points out, what it can do is opening a http connection not directly with the file you want, but with a server-side script (JSP, PHP, CGI,...) which will be allowed to write files on the server. You can use POST or GET parameters to pass to the script what you are going to write.
    This simple code worked for me (it executed the script toto.php):
              try{
                   URL toto=new URL(getCodeBase(),"toto.php");
                   InputStream f=toto.openStream();
                   f.close();
              catch(Exception e){
                   e.printStackTrace();
    Probably it's a good idea to do a URLConnection.setCache(false) though, to be sure that the script toto.php will be executed.
    3) I don't know how you can pass serialized objects as parameters. So if more than text informations are to be written, I would tend to make the script store them into a database instead of files. That way, you could pass any SQL query as parameter, maybe along with a password parameter for security. I don't know whether this is secure enough.

  • Activate a Midlet from an Applet

    Hi,
    I am trying to activate a Midlet from an Applet? Is this possible in any of the latest J2ME releases?
    Using SATSA I am able to send APDU commands from the Midlet to the Applet and start a scenario where my Applet and Midlet exchange information.
    Is this available in the opposite direction. I want that my Applet, when triggered by an event, be able to Activate\Wake Up the Midlet.
    I am a newbie to J2ME and after researching the web, still couldn't find an answer. Thanks for your help.
    Bye.

    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());
    }

  • Absolute navigation using post parameters

    Hi All
    I am navigating from WD4A iview to WD4J iview through absolute navigation and passing some parameters.
    I am expecting that these parameters size might be large. Is there is any restriction on the size of the parameters that i can pass in these method.Can i use postparameters to  overcome this restriction on size. If i use postparameters is there any restrictions on that.
    Can someone please post some helpful info or code examples to work with post parameters (Retrieving the parameters in the receiving application). Is other any other work around apart from these options.
    Thanks,
    Karthik.

    Hi,
    Check the following Threads related with retrieval of Post parameters in WD:
    How to send data from Web dynpro App to JSP or vice versa
    Re: jsp and web dynpro
    Siddharth

Maybe you are looking for

  • Get error message when trying to sync through Blackberry Device Manager

    During the synchronization process, I get an error message: Error encountered. Error code - 0x80040fb3. Check documentation. This is during the Address Book synchronization. Help...I have no contacts and only a portion of my notes are syncing to my p

  • Error creating legal entities

    hi i am trying to create new legal entity but ended up with the following error: ORA-29273: HTTP request failed ORA-06512: at "SYS.UTL_HTTP", line 1674 ORA-12535: TNS:operation timed out in Package xle_legal_address_swi Procedure create_legal_address

  • Data missing in PDF output generated by RDF locally only for one time.

    Hi All, Could any one please help me in finding the reason of the below mentioned issue. I have downloaded an RDF onto local machine and changed only sorting of few columns required. After that I had generated PDf output on local machine for first fe

  • Indexfile creation fails with imp_pipe - any help!

    mknod /oracle/temp/imp_pipe p uncompress< /oracle/temp/file.dmp.Z > /oracle/temp/imp_pipe & nohup imp system/np11n fromuser=cfs touser=cfs file=/oracle/temp/imp_pipe indexfile=/oracle/temp/file.sql & Also log file is not created for the import mknod

  • Production Order  Start Date

    Hello All, I am facing a problem in a Production order.When I am trying to change the  Production order Start date  and saving the changes I am getting a termination error (program termination). The error message is as below Nested call of PERFORM ON