2
import java.net.*; 
import java.io.*; 
public class sample
{  
    public static void main (String args[]) 
    { 
        String line;
        try 
        { 
            URL url = new URL( "http://localhost:8080/WeighPro/CommPortSample" ); 
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 
            line = in.readLine(); 
            System.out.println( line ); 
            in.close(); 
        }
        catch (Exception e)
        { 
            System.out.println("Hello Project::"+e.getMessage());
        } 
    } 
}

My Servlet is invoking another Jsp page like the below,

 RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
 rd.forward(request, response);

I am not getting any reaction/output in the browser, where the servlet has to be executed once it is invoked.

Am I missing any basic step for this process? Please Help!!!

enocom
  • 1,496
  • 1
  • 15
  • 22
Mathu
  • 84
  • 1
  • 12
  • how does your servlet look like? what happens if you enter the address into a seperate browser? – nano_nano Jan 06 '14 at 10:47
  • My servlet just dispacth to other jsp page,RequestDispatcher rd=request.getRequestDispatcher("index.jsp"); rd.forward(request, response); – Mathu Jan 06 '14 at 10:55
  • the browser is not loading!! Actually My jsp to which it is dispatching consist of a Table,and it will be shown in the browser – Mathu Jan 06 '14 at 10:56
  • To show a response in a browser, you must make the request in the browser. – NickJ Jan 06 '14 at 11:14

5 Answers5

2

If you want to open it in browser try this

java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://localhost:8080/WeighPro/CommPortSample"));
Sinto
  • 920
  • 5
  • 10
  • Thank You,I tried your code, which actually invoke a browser to open up the given URL, but in servlet I am setting the attribute to get disply in the index.jsp,so this operation would miss when I am trying the above code. – Mathu Jan 06 '14 at 12:10
  • @Mathu Opening up the URL will just invoke your servlet, so how that operation is getting missed.? – Sinto Jan 06 '14 at 12:22
  • Thank You So much,It's working-It's invoking servlet now,It wasn't working,since I didn't pass the required value in the URL. – Mathu Jan 06 '14 at 13:38
  • Happy to see it helped you. Mark it as answer if it really solved your question so that it will help other people as well. – Sinto Jan 09 '14 at 04:07
1

You question is not clear. Do you actually want to invoke a Servlet from the Main method, or do you want to make an HTTP request to your web application?

If you want to make an HTTP request, I can't see any obvious problems with your code above, which makes me believe that the problem is in the Servlet. You also mention that you don't get anything in the browser, but running your program above does not involve a browser.

Do you mean that you don't get a response when you go to

http://localhost:8080/WeighPro/CommPortSample

in a browser?

As Suresh says, you cannot call a Servlet directly from a main method. Your Servlet should instead call methods on other classes, and those other classes should be callable from the main method, or from Test Cases. You need to architect your application to make that possible.

NickJ
  • 9,380
  • 9
  • 51
  • 74
  • Better answer , but he is requesting a resource at URL "http://localhost:8080/WeighPro/CommPortSample" whose end result is container invoking the Servlet. – AllTooSir Jan 06 '14 at 11:02
  • 'http://localhost:8080/WeighPro/CommPortSample' When i m entering this URL it's showing me the output! From Main method I m actually passing a value to the servlet,from servlet the same value has to be passed to the index.jsp page using request.setAttribute. So from Main method can I invoke a servlet which do the dispatcher in the browser. – Mathu Jan 06 '14 at 11:04
  • When I am executing a main method can I expect an output in the browser just by invoking the servlet? – Mathu Jan 06 '14 at 11:06
  • When you execute the main method, nothing happens in the browser. The web application will send a response back to whatever made the request. If the request came from the main method, the response is returned to the main method. If the request was made in a browser, the response is returned to the browser. – NickJ Jan 06 '14 at 11:11
0
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class OutBoundSimul {

    public static void main(String[] args) {

        sendReq();

    }

    public static void sendReq() {
        String urlString = "http://ip:port/applicationname/servletname";

        String respXml = text;

        URL url = null;

        HttpURLConnection urlConnection = null;
        OutputStreamWriter out = null;
        BufferedInputStream inputStream = null;
        try {
            System.out.println("URL:"+urlString);
            url = new URL(urlString);
            urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setRequestMethod("POST");
            System.out.println("SendindData");
            out = new OutputStreamWriter(urlConnection.getOutputStream());
            System.out.println("Out:"+out);
            out.write(respXml);
            out.flush();
            inputStream = new BufferedInputStream(urlConnection.getInputStream());
            int character = -1;
            StringBuffer sb = new StringBuffer();
            while ((character = inputStream.read()) != -1) {
                sb.append((char) character);
            }
            System.out.println("Resp:"+sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}
Rahul K R
  • 11
  • 3
  • I'm sure that code is lovely, but you could add some explanation as to what it does? I can see what it's for, but someone less experienced might not. Also, are your sure you want a POST request? – NickJ Jan 06 '14 at 11:09
  • @RahulJi 'String respXml = "text";' What should be the input for this variable?Web.xml Path? or? – Mathu Jan 06 '14 at 11:32
  • You can set request method as GET or POST...In respXml you can put what data you need to pass to servlet... – Rahul K R Jan 06 '14 at 11:50
  • You can set value for respXml for eg: respXml="Rahul"; – Rahul K R Jan 06 '14 at 12:33
0

Invoking Servlet with query parameters Form Main method

Java IO

public static String accessResource_JAVA_IO(String httpMethod, String targetURL, String urlParameters) {
    HttpURLConnection con = null; 
    BufferedReader responseStream = null;
    try {
        if (httpMethod.equalsIgnoreCase("GET")) {
            URL url = new URL( targetURL+"?"+urlParameters ); 
            responseStream = new BufferedReader(new InputStreamReader( url.openStream() )); 
        }else if (httpMethod.equalsIgnoreCase("POST")) {
            con = (HttpURLConnection) new URL(targetURL).openConnection();
            // inform the connection that we will send output and accept input
            con.setDoInput(true);   con.setDoOutput(true);  con.setRequestMethod("POST");
            con.setUseCaches(false); // Don't use a cached version of URL connection.
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
            con.setRequestProperty("Content-Language", "en-US");  

            DataOutputStream requestStream = new DataOutputStream ( con.getOutputStream() );
            requestStream.writeBytes(urlParameters);
            requestStream.close();

            responseStream = new BufferedReader(new InputStreamReader( con.getInputStream(), "UTF-8" ));
        }

        StringBuilder response = new StringBuilder(); // or StringBuffer if not Java 5+ 
        String line;
        while((line = responseStream.readLine()) != null) {
            response.append(line).append('\r');
        }
        responseStream.close();
        return response.toString();
    } catch (Exception e) {
        e.printStackTrace();        return null;
    } finally {
        if(con != null) con.disconnect(); 
    }
}

Apache Commons using commons-~.jar {httpclient, logging}

public static String accessResource_Appache_commons(String url){
    String response_String = null;

    HttpClient client = new HttpClient();

    GetMethod method = new GetMethod( url ); 
//  PostMethod method = new PostMethod( url );
    method.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
    method.setQueryString(new NameValuePair[] { 
        new NameValuePair("param1","value1"),
        new NameValuePair("param2","value2")
    });  //The pairs are encoded as UTF-8 characters. 
    try{
        int statusCode = client.executeMethod(method);
        System.out.println("Status Code = "+statusCode);

        //Get data as a String OR BYTE array method.getResponseBody()
        response_String = method.getResponseBodyAsString();
        method.releaseConnection();
    } catch(IOException e) {
        e.printStackTrace();
    }
    return response_String;
}

Apache using httpclient.jar

public static String accessResource_Appache(String url) throws ClientProtocolException, IOException{
    try {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        URIBuilder builder = new URIBuilder( url )
                                .addParameter("param1", "appache1")
                                .addParameter("param2", "appache2");

        HttpGet method = new HttpGet( builder.build() );
//      HttpPost method = new HttpPost( builder.build() );

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            @Override
            public String handleResponse( final HttpResponse response) throws IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                }
                return "";
            }
        };
        return httpclient.execute( method, responseHandler );
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return null;
}

JERSY using JARS {client, core, server}

public static String accessResource_JERSY( String url ){
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource( url );
    ClientResponse response = service.accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);
    if (response.getStatus() != 200) {
        System.out.println("GET request failed >> "+ response.getStatus());
    }else{
        String str = response.getEntity(String.class);
        if(str != null && !str.equalsIgnoreCase("null") && !"".equals(str)){
             return str;
        }
    }
    return "";
}

Java Main method

public static void main(String[] args) throws IOException {

    String targetURL = "http://localhost:8080/ServletApplication/sample";
    String urlParameters = "param1=value11&param2=value12";

    String response = "";
//      java.awt.Desktop.getDesktop().browse(java.net.URI.create( targetURL+"?"+urlParameters ));
//      response = accessResource_JAVA_IO( "POST", targetURL, urlParameters );
//      response = accessResource_Appache_commons( targetURL );
//      response = accessResource_Appache( targetURL );     
    response = accessResource_JERSY( targetURL+"?"+urlParameters );
    System.out.println("Response:"+response);
}
Yash
  • 9,250
  • 2
  • 69
  • 74
-2

Simply you cannot do that.

A response and request pair will generated by web container. You cannot generate a response object and send to the browser.

By the way which client/browser you are expecting to get the response ? No idea. Right ?

When container receives a request from client then it generates response object and serves you can access that response in service method.

If you want to see/test the response, you have to request from there.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • I'm not the downvoter but please explain me this line :"You cannot generate a response object and send to the browser." ! What are you trying to convey ? – AllTooSir Jan 06 '14 at 10:51
  • And secondly by stating "Simply you cannot do that." , what are you trying to say -"You cannot invoke Servlet from a POJO" ??? – AllTooSir Jan 06 '14 at 10:52
  • The Servlet container generates the Response object. You cannot create one yourself, you only get to see an Interface. There are no Response implementations in the Servlet specification. – NickJ Jan 06 '14 at 10:52
  • @NickJ And in what language the Servlet Container was written? If the author of the Container code can generate the Response object based on specs , why cannot OP? – AllTooSir Jan 06 '14 at 10:55
  • @TheNewIdiot I explained in my last sentence. – Suresh Atta Jan 06 '14 at 10:56
  • @TheNewIdiot Without browser requesting , how can you send a response to that particular browser ?? How can you even detect that browser receives it ? – Suresh Atta Jan 06 '14 at 10:57
  • Yes but you didn't mention that in your earlier post, now that you have added the last line it makes more sense. – AllTooSir Jan 06 '14 at 10:58
  • @TheNewIdiot Yes, strictly speaking, it is possible to write your own class to implement HttpServletResponse. But not recommended. Each different Servlet Container (Tomcat, JBoss etc) has its own implementations of HttpServletResponse, but the developer should NOT write anything implementation-specific in their application, and does not need to know about the implementation. They should only use the HttpServletResponse interface itself. – NickJ Jan 06 '14 at 11:04
  • Yes, I'm editing my post while you are downvoting. A little late. No issues. Thanks for the points though. – Suresh Atta Jan 06 '14 at 11:27
  • @NickJ I know, you are not :) Reffering to TheNewIdiot. – Suresh Atta Jan 06 '14 at 11:44