从java main方法调用servlet

时间:2014-01-06 10:43:36

标签: java jsp servlets servlet-3.0

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

我的Servlet正在调用另一个Jsp页面,如下所示,

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

我没有在浏览器中得到任何反应/输出,一旦调用servlet就必须执行它。

我错过了这个过程的任何基本步骤吗?请帮忙!!!

5 个答案:

答案 0 :(得分:2)

如果你想在浏览器中打开它,试试这个

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

答案 1 :(得分:1)

你的问题不明确。你真的想从Main方法调用Servlet,还是想向你的web应用程序发出HTTP请求?

如果你想发一个HTTP请求,我上面的代码看不到任何明显的问题,这让我相信问题在于Servlet。您还提到您在浏览器中没有得到任何内容,但上面运行您的程序不涉及浏览器。

你是说当你去

时没有得到回应
http://localhost:8080/WeighPro/CommPortSample

在浏览器中?

正如Suresh所说,你不能直接从main方法调用Servlet。 您的Servlet应该调用其他类的方法,而其他类应该可以从main方法或Test Cases中调用。您需要构建应用程序以使其成为可能。

答案 2 :(得分: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();
        }


    }

}

答案 3 :(得分:0)

使用查询参数调用Servlet Form Main方法

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 使用commons-~.jar {httpclientlogging}

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 使用 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 使用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主要方法

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

答案 4 :(得分:-2)

只是你做不到。

响应和请求对将由Web容器生成。您无法生成响应对象并发送到浏览器。

顺便提一下您希望获得响应的客户端/浏览器?不知道。对吗?

当容器收到来自客户端的请求时,它会生成响应对象,并且您可以在服务方法中访问该响应。

如果您想查看/测试回复,则必须从那里请求。