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

Similar Messages

  • 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.

  • 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.

  • 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 another method

    Hi,
    I am writing a program which requires executing another servlet from within
    thie main program. I do not care to return the information from the servlet
    request.
    http://usx500.crn.st.com:7000/TPMCenter_V2/insertAutomationValue.do?reqCode=confirmed
    Thanks for the help.

    The reason I continue posting this question, is because I cannot find a solution.
    I have looked through the link provided, as well as many other solutions on the web,
    none which have been successful. Following are two solutions which I have tried, and
    niether have worked. I still am in need of some help in resolving this. If you would like
    to assist me in this it would be greatly appreciated.
    Dr Clap--
    If you do not have a suggested solution, simply do not reply.
    Solution 1 ---
        try {
            // Construct data
            String data = URLEncoder.encode( "reqCode", "UTF-8") + "=" + URLEncoder.encode( "show", "UTF-8" ) ;
            // Create a socket to the host
            String hostname = "usx500.crn.st.com" ;
            int port = 7000 ;
            InetAddress addr = InetAddress.getByName( hostname );
            Socket socket = new Socket( addr, port );
            // Send header
            String path = "/TPMCenter_V2/insertAutomationValue.do";
            BufferedWriter wr = new BufferedWriter( new OutputStreamWriter( socket.getOutputStream(), "UTF8" ) ) ;
            wr.write( "POST " + path + " HTTP/1.0\r\n" );
            wr.write( "Content-Length: " + data.length() + "\r\n" ) ;
            wr.write( "Content-Type: application/x-www-form-urlencoded\r\n" ) ;
            wr.write("\r\n");
            // Send data
            wr.write(data);
            wr.flush();
            wr.close();
        } catch (Exception e) {
            e.printStackTrace() ;
        }Solution 2 ---
    try{
        URLConnection c = new URL("http://usx500.crn.st.com:7000/TPMCenter_V2/insertAutomationValue.do?reqCode=show").openConnection();
        c.connect();
    }catch(MalformedURLException murle){
        System.out.println(murle);
    }catch(IOException ioe){
        System.out.println(ioe);
    }

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

  • Calling servlet from java page flow

    Hi,
    I need to call servelt class from the <netui:anchor ..> tag of my jpf.
    i have mapped this servlet class in the web.xml.
    please tell us how to invoke servlet from the netui:anchor tag from the jpf action
    method.
    thanks
    shashi

    I am calling a Servlet from JAVA Class as I am using IDE: Eclipse. The Problem is below
    URL url = new URL(ServletPath);
    URLConnection connet = url.openConnection();Why should the Servlet running in different Runtime print on your Eclipse Runtime. Please be more clear about the question.

  • Calling servlet from Java

    Hello!
    I need to send XML file to servlet from Java. I generate XML in general java class.
    Is there any way how to call servlet directly from Java without using a page with form? I need to send it by post method. I need some java alternative to Microsoft.XMLHTTP object.
    Thanks

    Try this part of the Networking tutorial:
    http://java.sun.com/docs/books/tutorial/networking/urls/index.html
    It might be the answer to your question.

  • Calling Servlet from Java Class in eclipse

    Hi ,
    I am calling a Servlet from JAVA Class as I am using IDE: Eclipse. The Problem is below
    URL url = new URL(ServletPath);
    URLConnection connet = url.openConnection();
    I am using the above code in JAVA to Connect to Servlet I have given Print statement in Servlet such that whenever it calls it prints on Console but when I try to run the code the Statement is not printed in the Console of eclipse I think URL connection is not able to establish any connection ..... if any has solution for this please reply
    Thanks & Regards,
    Arvind

    I am calling a Servlet from JAVA Class as I am using IDE: Eclipse. The Problem is below
    URL url = new URL(ServletPath);
    URLConnection connet = url.openConnection();Why should the Servlet running in different Runtime print on your Eclipse Runtime. Please be more clear about the question.

Maybe you are looking for