Invoking servlet from java main method

放肆的年华 提交于 2020-01-13 05:54:21

问题


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!!!


回答1:


If you want to open it in browser try this

java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://localhost:8080/WeighPro/CommPortSample"));



回答2:


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.




回答3:


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


    }

}



回答4:


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



回答5:


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.



来源:https://stackoverflow.com/questions/20948218/invoking-servlet-from-java-main-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!