Calling a servlet in a Java class

Source: Internet
Author: User

One, call the servlet description in Java:

We may sometimes need to invoke the servlet in the Java class to implement some special functionality, and a class of URLs is provided in Javaapi, where the OpenStream () method can open the connection to the URL and return a inputstream that is used for the connection to read in.

Second, Java calls the servlet application example:

Package com.solid.test;

Import java.io.BufferedReader;

Import java.io.IOException;

Import java.io.InputStreamReader;

Import java.net.MalformedURLException;

Import Java.net.URL;

public class Testcallservlet {

Servlet path

private static final String path = " Http://localhost:8080/test/servlet/TestServlet ";

/**

* Test Call servlet method

* @param args

*/

public static void Main (string[] args) {

try {

URL url = new URL (path);

Url.openstream ();

} catch (Malformedurlexception e) {

E.printstacktrace ();

} catch (IOException e) {

E.printstacktrace ();

}

}

}

third, to read a page source code application example:

Package com.solid.test;

Import java.io.BufferedReader;

Import java.io.IOException;

Import java.io.InputStreamReader;

Import java.net.MalformedURLException;

Import Java.net.URL;

Import java.net.URLConnection;

public class Testreadersource {

URL path

private static final String path = " http://www.google.cn ";

Read source code method test for page under path path

public static void Main (string[] args) {

BufferedReader br = null;

String source;

try {

URL url = new URL (path);

URLConnection conn = Url.openconnection ();

br = new BufferedReader (New InputStreamReader (Conn.getinputstream ()));

while ((Source=br.readline ())!=null) {

SYSTEM.OUT.PRINTLN (source);

}

} catch (Malformedurlexception e) {

E.printstacktrace ();

} catch (IOException e) {

E.printstacktrace ();

} finally {

try {

if (br! = null) {

Br.close ();

}

} catch (IOException e) {

E.printstacktrace ();

}

}

}

}

 

Calling Servlet in Java class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.