Call servlet from javascript

Hi,
In my web application , i must call a servlet from javascript.
At present i am calling the servlet by using the following syntax:
document.location.href ="sample?startTime="startTime+"&endTime="+Time;+*
The above syntax is working fine, but the problem is ,a new page is created whenever a request is made.
Is there any way to call the servlet without creating any new page.
kindly provide me an alternative, it will be of great help for me.

Is there any way to call the servlet without creating any new page.Ajax. Or load it in a hidden (not visible) iFrame.

Similar Messages

  • How do i call servlet from javascript after validation the javascript

    Hi ,
    Can anyone tell me how to call a servlet after the javascript is being validated. Here is my code to validate javascript i need to call a servlet inorder to save the data into the same form. I tried calling through the action method in the form but its directly taking me to the servlet but not validating the form. Is there any way that i can validate the form first then call the servlet.
    Thanks in advance.
    <html>
    <head>
    <title>Online Blog</title>
    <script language ="javascript" type ="text/javascript">
    function myfunction()
    var mesg = "";
    var dmesg = "";
    var dnumber = 0;
    var number = 0
    var Blogstr = document.onlineblog.BlogName;
    var Fnamestr = document.onlineblog.FirstName;
    var Lnamestr = document.onlineblog.LastName;
    var Datestr = document.onlineblog.Dateformat;
    var Imagestr = document.onlineblog.uploadimage;
    var Imageval = Imagestr.value;
    var flength = parseInt(Imageval.length) - 3;
    var fext = Imageval.substring(flength,flength + 3);
    var Dateval = Datestr.value;
    var Dformat = /^\d{2}\/\d{2}\/\d{4}/; //checks the date format.
    //splits date into mm, dd , yyyy format.
    var m = Dateval.split("/")[0];
    var d = Dateval.split("/")[1];
    var y = Dateval.split("/")[2];
    //Get today's date (removes time).
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1;
    var yyyy = today.getFullYear();
    //checks if month and date are displayed in mm, dd format and if not sets to mm,dd.
    if (mm <10)
    mm = '0'+mm;
    if (dd <10)
    dd = '0'+dd;
    //checks if name of the blog is empty
    if(Blogstr.value == "")
    number = number+1;
    mesg += "\n" + number + "Name of the blog";
    //checks if value of Frist Name is empty;
    if(Fnamestr.value == "")
    number = number+1;
    mesg += "\n" + number + "First Name";
    //checks if value of Last Name is empty;
    if(Lnamestr.value == "")
    number = number+1;
    mesg += "\n" + number + "Last Name";
    //checks if value of date is empty;
    if(Datestr.value == "")
    number = number+1;
    mesg += "\n" + number + "Date of mm/dd/yyyy format";
    //checks if value of image field is empty;
    if(Imagestr.value == "")
    number = number+1;
    mesg += "\n" + number + "select an image";
    //displays all the error messages.
    if (number > 0)
    alert ("Please enter the following" + mesg);
    return false;
    //checks if entered date format is mm/dd/yyyy
    if(!Dformat.test(Dateval))
    dnumber = dnumber +1;
    dmesg += "\n" + dnumber + "please enter a valid date(mm/dd/yyyy)";
    //checks if date is greater than 12 and is 2 digits.
    if ((m>12 && m<100) || (m> = 100 && m<1000) || (m==0))
    dnumber = dnumber+1;
    dmesg += "\n" + dnumber + "Enter valid month(mm)";
    //checks if month has 31 or 30 days and is in dd format.
    if (((d>30) && (d<100) && (m == 04 || m == 06 || m == 9 || m == 11)) || ((m == 01 || m == 03 || m == 05 || m == 07 || m == 08 || m == 10 || m==12) && (d >31) && (d<100)) || d == 0)
    dnumber = dnumber+1;
    dmesg += "\n" + dnumber + "Enter valid date(dd)";
    //checks if month has 28 or 29 days and wheather is a leap year or not.
    if((m == 02 && d>29 && y%4 == 0) || (m == 02 && d>28 && y%4 != 0))
    dnumber = dnumber+1;
    dmesg += "\n" + dnumber + "Enter valid date(dd)";
    //checks if entered date is prior to the current date.
    if((m == mm && d == dd && y == yyyy) || (y > yyyy)|| (d>=dd && m>=mm && m<=12 && y==yyyy) || (d<=dd && m>mm && y == yyyy && m<=12))
    dnumber = dnumber + 1;
    dmesg += "\n" + dnumber + "Please enter a date prior to the current date";
    if (y == 0 || y < 1000 || y>9999) //checks if year is zero and is a 4 digit number.
    dnumber = dnumber + 1;
    dmesg += "\n" + dnumber + "Enter a valid year(yyyy)";
    //checks if image format is jpg or gif.
    if(fext != "jpg" && fext != "gif")
    dnumber = dnumber + 1
    dmesg += "\n" + dnumber + "You can only upload gif or jpg images.";
    if(dnumber>0)
    alert("please check the followin error messages"+dmesg);
    return false;
    </script>
    <style type="text/css">
    .style1 {color: #FF0000}
    body {
         background-color: #FFCCFF;
    h2 {
         color: #CC3399;
    h1 {
         color: cc3399;
    .style2 {
         font-family: Arial, Helvetica, sans-serif;
         font-weight: bold;
    .style5 {color: #000000; font-family: "Times New Roman", Times, serif;}
    </style>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><body>
    <h1 align="center">Webloggers space</h1>
    <p align="center">Home
    <p>
    <h4> Please enter the following details to register.</h4>
    <p> <b>Note:</b> All fields marked with <span class="style1">*</span>(astrick)
    are compulsory.</p>
    <form action="servlet/BlogServlet" name="onlineblog" onsubmit = "return myfunction()" method="post">
    <table width="60%" border="0" cellspacing="5" cellpadding="2">
    <tr>
    <td><span class="style1">*</span>Name of the Blog</td>
    <td><input type="text" name="BlogName"/></td>
    </tr>
    <tr>
    <td><span class="style1">*</span>First Name</td>
    <td><input type="text" name="FirstName"/></td>
    </tr>
    <tr>
    <td><span class="style1">*</span>Last Name</td>
    <td><input type="text" name="LastName"/></td>
    </tr>
    <tr>
    <td><span class="style1">*</span>Date(mm/dd/yyyy)</td>
    <td><input type="text" name="Dateformat"/></td>
    </tr>
    <tr>
    <td>Category</td>
    <td><select name="catagory" size="1">
    <option></option>
    <option>Business</option>
    <option>Education</option>
    <option>Entertainment</option>
    <option>Food</option>
    <option>Hobbies</option>
    <option>Personal</option>
    <option>Politics</option>
    <option>Sports</option>
    </select></td>
    </tr>
    <tr>
    <td>Enter your text here:</td>
    <td><textarea name="textarea" cols="45" rows="5"></textarea></td>
    </tr>
    <tr>
    <td><span class="style1">*</span>Upload Image <span class="style5">(.jpg
              or .gif)</span></td>
    <td><input type="file" name="uploadimage" /></td>
    </tr>
    <tr>
    <td></td>
    <td><input type="submit" value="save">
    <input type="reset" name="reset" value="Reset" /></td>
    </tr>
    </table>
    </form>
    </body>
    </html>

    Your javascript code contains a syntax error. That's why the function isn't being called. Take a look at this line in your code.
    if ((m>12 && m<100) || (m> = 100 && m<1000) || (m==0))Notice the space between > and =. Remove that space.
    m >= 100

  • Calling servlet from a java program

    Hi
    I need to call a servlet's doPost() method from a java program. I have a specific situation, where I need to call servlet from a java program. DUring this call I need to pass a file and two string to the servlet. Servelt after receiving the file and string uploads the file to the server at a specified location. I am stuck up as how to call servlet from a java program instead of a HTML or JSP.
    Can anyone help me to start with this.
    any suggestion is welcome.

    You have to establish a URLConnection with servlet from your java program.
    URL servletURL = new URL("http://localhost:8080/Myservlet?str1=abc&str2=def");
    URLConnection servletConnection = servletURL.openConnection();you can get the objectOutputStream
    ObjectOutputStream oos = new ObjectOutputStream (servletConnection.getOutputStream());
    oos.writeObject(your file object);-------------------------------------------------
    In the servlet u can get the strings using request.getParameter("str1");
    In the servlet u can get the strings using request.getParameter("str2");
    file = new ObjectInputStream (request.getInputStream()).readObject()a lot of resources are available on this ...
    hope this helps :)

  • Calling Servlet from a java prog?

    Hi all,
    I am calling servlet from a java prog (Java Agent in Lotus Notes) by using URL and URLConnection object. how can i trigger the Servlet By using doPost method .I have to send some parameter also.
    Thanx
    Muthu

    you need to open a connection to the servlet. Then you must call getInputStream() and getOutputStream() and use them in any way you see fit. I was trying this before and could not get POST to work unless I openned the input stream from the servlet. Strange... but doGet worked without openning the input stream???
    // open a connection....
    // write to the servlet
    servletConnection.getOutputStream().write("whatever");
    servletConnection.getOutputStream().flush();
    servletConnection.getOutputStream().close();
    // grab what the servlet sends back, required to do a post.
    byte [] in = new byte[100];
    servletConnection.getInputStream().read(in);
    servletConnection.getInputStream().close();

  • Wot all ways are there to call servlet from jsp

    hi all
    i want to know wot all methods are available
    so that i can call servlet from jsp
    the one which i know is using RequestDispatcher
    wot are others ?
    thanx

    hi all
    i want to know wot all methods are available
    so that i can call servlet from jsp
    the one which i know is using RequestDispatcher
    wot are others ?
    thanxhi here are few ways... to call servlet from jsp...
    these are just generic syntax.
    Form:     
    <form action="ServletPath">
    Link:     
    Directives & Action tags :
    <%@ page import="ServletPath" %>
         <%@ taglib uri="ServletPth" %>
         <jsp:include page="ServletPath">
         <jsp:forward page="ServletPath">
         <jsp:useBean class="ServletPath"> (Not sure about this useBean)
    hope you got your answer.
    regards,
    immu

  • How to call Servlet from jsp page and how to run this app using tomcat..?

    Hi ,
    I wanted to call servlet from jsp action i.e. on submit button of JSP call LoginServlet.Java file.
    Please tell me how to do this into jsp page..?
    Also i wanted to execute this application using tomcat.
    Please tell me how to do this...? what setting are required for this...? what will be url ..??
    Thanks.

    well....my problem is as follows:
    whenever i type...... http://localhost:8080/appName/
    i am getting 404 error.....it is not calling to login.jsp (default jsp)
    but when i type......http://localhost:8080/appName/login.do........it executes servlet properly.
    Basically this 'login.do' is form action (form action='/login.do').....and i wanted to execute this from login jsp only.(from submit button)
    In short can anyone please tell me how to diaplay jsp page using tomcat 5.5
    plz help me.

  • Calling servlets from main()?

    Hi
    I would like to know that while calling servlets from another class having main(), how can we set the type of request i.e. put, post or get?
    Thanks

    use the method - setRequestMethod( "POST") of HttpURLConnection for setting the method to POST.Similarly for other methods..
    You could find [url http://java.sun.com/developer/JDCTechTips/2004/tt0210.html#2]this useful

  • Calling Taskflow from javascript

    Hi,
    Can any one help me on calling taskflow from javascript.
    Thanks in advance,
    Regards,
    Lavanya.

    hi Lavanya,
    All I did was a simple search and found this
    Javascripts and ADF Taskflows
    See if this is helpful to you too :)
    Regards,
    Neha..

  • How to call servlet from jsp

    i m trying to call it from jsp using
    <a href="../purchaseP?orderno=<%=pno%>"><%=pno%></a>
    but its giving error..
    type Status report
    message HTTP method GET is not supported by this URL
    description The specified HTTP method is not allowed for the requested resource (HTTP method GET is not supported by this URL).

    i m trying to call it from jsp using
    <a href="../purchaseP?orderno=<%=pno%>"><%=pno%></a>
    but its giving error..
    type Status report
    message HTTP method GET is not supported by this URL
    description The specified HTTP method is not allowed
    for the requested resource (HTTP method GET is not
    supported by this URL).Are you implementing the doGet or doPost method in your servlet? If you are calling from a hyperlink then it needs to be implementing the GET method. To access the POST method use a html form.

  • Error while calling applet from Javascript via LiveConnect and WebDriver

    Hi all,
    I am trying to call applet Java code from Javascript via WebDriver.
    Given the following two cases:
    - calling a static method: Integer.parseInt("42")- constructing a new object: new String("Hello world")My Javascript code looks like this:
    document.appletId.Packages.java.lang.Integer.parseInt("42");
    new document.appletId.Packages.java.lang.String("Hello world");When executing this code in Firefox via the Firebug Javascript console everything works fine and I get the expected results. However, when executing this code via the JavascriptExecutor from WebDriver only the call to the static method succeeds, the construction of the new object leads to the following error: "Attempt to call a default method on object with no invokeDefault method."
    I don't have any idea what is going wrong here, so any help would be greatly appreciated.
    Thanks!

    Hello Gerard, Hello Krishna,
    -> The liveCache application failed with COM error::
                                   40028 Illegal timestamp in rough timegrid
    More details about COM error 40028 you will see in TA /n/sapapo/om10
         -> Return code: 40028 -> execute ::
    Invalid time stamp in the time buckets profile relation     
    ( om_ts_tgrelinvalidstamp )     
       < click on '?' mark >
    -> Open an OSS message in accordance with SAP note 167280 if further help
         needed to solve the issue on your system.
    Thank you and best regards, Natalia Khlopina

  • Problem while calling servlet from java bean

    I am trying to call a servlet from java bean in cep.
    My java bean:
    package com.bea.wlevs.example.algotrading;
    import com.bea.wlevs.ede.api.StreamSink;
    import com.bea.wlevs.example.algotrading.event.MarketEvent;
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Unmarshaller;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.StringReader;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    public class MarketEventBean implements StreamSink {
         String s=null;
         public void onInsertEvent(Object event) {
              if (event instanceof MarketEvent) {
                   MarketEvent marketEvent = (MarketEvent) event;
                   try {
                        JAXBContext cxt = JAXBContext.newInstance(MarketEvent.class);
                        Unmarshaller unmarsh = cxt.createUnmarshaller();
                        StringReader strReader = new StringReader(marketEvent.getString_1());
                        MarketEvent obj = (MarketEvent) unmarsh.unmarshal(strReader);
                        s=obj.getSymbol();
                        System.out.println("data: " + s);
                   } catch(Exception e) {
                        e.printStackTrace();
                   try {
                        System.out.println("test1");
         URL url = new URL("http://172.18.21.94:7001/AppServletrecv-Model-context-root/ReceiveServlet");
         URLConnection conn = url.openConnection();
              System.out.println("test2");
         conn.setDoOutput(true);
              System.out.println("test3");
         BufferedWriter out =
         new BufferedWriter( new OutputStreamWriter( conn.getOutputStream() ) );
         out.write("symbol="+s);
              System.out.println("test4");
         out.flush();
         System.out.println("test5");
         out.close();
         System.out.println("test6");
         BufferedReader in =
         new BufferedReader( new InputStreamReader( conn.getInputStream() ) );
              System.out.println("test7");
         String response;
         while ( (response = in.readLine()) != null ) {
         System.out.println( response );
         in.close();
         catch ( MalformedURLException ex ) {
         // a real program would need to handle this exception
         catch ( IOException ex ) {
         // a real program would need to handle this exception
    My servlet code:
    package model;
    import javax.servlet.http.HttpServlet;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class ReceiveServlet extends HttpServlet {
    private final static String _SYMBOL = "symbol";
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
    * Get the value of form parameter
    // private final static String USERNAME = "username";
    String symbol = request.getParameter( _SYMBOL );
    * Set the content type(MIME Type) of the response.
    response.setContentType("text/html");
    * Write the HTML to the response
    try {
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title> A very simple servlet example</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Hello " + symbol +"</h1>");
    out.println("</body>");
    out.println("</html>");
    out.close();
    } catch (IOException e) {
    Web.xml:
    <?xml version = '1.0' encoding = 'windows-1252'?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">
    <servlet>
    <servlet-name>ReceiveServlet</servlet-name>
    <servlet-class>model.ReceiveServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>ReceiveServlet</servlet-name>
    <url-pattern>/ReceiveServlet</url-pattern>
    </servlet-mapping>
    </web-app>
    My servlet is running in weblogic server.
    But when I am running this program in weblogic server side there is no log.
    Edited by: 856272 on Jun 23, 2011 6:43 AM

    I would run both sides in a debugger and see what code is getting invoked

  • Very urgent: call servlet from JSP

    Hello,
    I'm facing a problem in invoking a servlet from a JSP having the JSF components.
    The application has a text field to implement ajax for search functionality in the database .I have written a servlet to make the database connection and fire the querry.
    Ajax implementation in a js file is called on every keyup event in the jsp file,and
    a call is given to the servlet from the ajax methode.
    The function in the js file is as follows:-
    function getPersonByFirstNameXML( firstName ) {
        if (!firstName) {
            clearPersonByFirstNameXML();
        } else {   
            var url = BASE_URL + "/servlet/get_PersonsXML";
            alert(url);
            return new AJAXRequest("post", url, "firstName=" + encode(firstName), processGetPersonByFirstNameXML);
    }Im getting the myAJAX.status value as 500.
    I think I'm not able to access the servlet properly.
    what changes do i need to make in the we.xml file ?
    and what should be the url to be passed.
    Please provide me a sloution to the above problem as it is very urgent else if anybody is aware of a readymade JSF componet with search functionality freely available please let me know.
    PS:
    The sample application named RedirectionExample which makes use of a servlet and would be of help to you. You can find the tutorial on the following page:
    http://developers.sun.com/prodtech/javatools/jscreator/reference/codesamples/sampleapps.html
    is not available as stated in some of the suggestions by Author: mayagiri
    Thanks for any help.
    Abhi

    the status 500 generally means either HTTP server internal error or that execution of CGI script or servlet aborted with error.
    It can be reasonably supposed that the request reaches the servlet, ie. that "url" value points to some existing servlet, otherwise most probably the status value would be 404.
    To test that the servlet is working i'd try to access it using some simple html page with form like this (with {BASE_URL} replaced by real value):
    <form method=post action={BASE_URL}/servlet/get_PersonsXML>
    <input type=text name=firstName>
    <input type=Submit>
    </form>

  • Calling servlet from a backing bean

    hi guys i need to call a servlet from a backing bean in JSF. how do i do that ?
    The scenario is i have to call servlet on a different machine from my backing bean . I also need to pass an object to the servlet .
    This object contains data which must be manipulated and inserted in the database by the calling servlet.
    I also want that after insertion in the db the control must be passed to the backing bean .
    Is this all possible???
    Please help

    You may want to investigate the built in java.net.URL class. For advanced needs, Apache has a Java HTTP client library.

  • Problem calling servlet from doget method of another servlet

    hi,
    Iam trying to post an html form written in the doGet() method
    of a servlet to pass this information to another servlet's doPost() method. Iam giving the following URL:
    "<FORM ACTION=http://localhost:8080/examples/servlet/UpdateProcessServlet" +
    "METHOD=POST>"
    But its not happening,the error says that "the page cannot be found" The servlet is not getting called at all. would someboy please help me in this regard.
    Thanks

    #1 Iam calling servlet 2 from here
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    session=request.getSession(false);
    out.println
    (ServletUtilities.DOCTYPE +
    "<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.0 Transitional//EN>"+
    "<HTML>" +
    "<BODY>" +
    "<P CLASS=LARGER>" +
    "<FORM ACTION=http://localhost:8080/examples/servlet/UpdateProcessServlet METHOD=POST>"
    "<INPUT TYPE=SUBMIT NAME=submitButton Value=submit>" +
    "</BODY> " +
    "</HTML>" );
    #2 This should get called and print me "Iam in doPost method
    public void doPost(HttpServletRequest request,HttpServletResponse response)
    throws ServletException,IOException
    url = "jdbc:odbc:Resume";
    System.out.println("Iam in doPost method");
    response.setContentType("text/html");
    out = response.getWriter();
    out.println("This is the last servlet for this project:");
    bool=false;
    check=false;
    Thank...:)

  • Problem calling servlet from within a jsp

    I have a servlet which obtains images for a page
    http://bychance.ca/servlet/ImageServlet?PhotoId=AJ-LA-4008
    I use the servlet from within a jsp
    <img src="servlet/ImageServlet?PhotoId=<%=rs.getObject("ID")%>" border="0">
    for some reason it does not work, the images are never called. I have another servlet which is called the same way and it works fine
    <img src="servlet/ImageServletLarge?PhotoId=<%=strPhotoId%>" border="0">
    Thank you all for your time

    this is my servlet code. Like I said it works fine in another servlet
    rs.next();
    byte[] bytearray = new byte[rs.getInt(1)];
    int size=0;
    InputStream sImage;
    sImage = rs.getBinaryStream(2);
    response.reset();
    response.setContentType("image/jpeg");
    while((size=sImage.read(bytearray))!= -1 )
    response.getOutputStream().write(bytearray,0,size);
    response.flushBuffer();
    sImage.close();

Maybe you are looking for

  • File Approach -File to proxy

    Hi Frnds, i have scenario. Where i get header ,Detail and Footer. Header contains few of the fields including with identifier. Trailor record contains record count and line count with identifier But where we dont have an identifier in detail.But deta

  • Upgrading the DVD drive in a Quicksilver 733 MHz?

    If I purchase a Sonnet PCI SATA controller, can I upgrade my built-in DVD R-W to a SATA DVD R-W? If so, which DVD brand/model has most people had success with? Thanks!

  • Is everyone else not able to connect via FaceTime?

    I can't seem to use FaceTime on any of my devices?   Is this a system problem?

  • Consistency checks in APO

    Can anybody please explain the reasons for doing the 1.Model consistency check 2. Re-org Consistency check(/SAPAPO/TS_LCM_REORG) What would be the frequency for these consistency checks?

  • Training in Sun access manager

    Looking for training in sun access manager. If any one of you interested in giving me training send me email at [email protected] I will pay for it. Thx