A simple callback (example)

Source: Internet
Author: User

1. Declare a callback Interface:

Public interface CallBack {/*** execution CallBack Method * @ param objects return the processed result as a parameter to the CallBack Method */public void execute (Object... objects );}

 

2. The callback part inherits the callback and implements the callback method:

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLConnection;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.xml.ws.spi.http.HttpContext;public class testServlet extends HttpServlet implements CallBack{    NetTool netTool;    HttpServletResponse globalResponse;    String netResult;    /**     * Constructor of the object.     */    public testServlet() {        super();    }    /**     * Destruction of the servlet. <br>     */    public void destroy() {        super.destroy(); // Just puts "destroy" string in log        // Put your code here    }    /**     * The doGet method of the servlet. <br>     *     * This method is called when a form has its tag value method equals to get.     *      * @param request the request send by the client to the server     * @param response the response send by the server to the client     * @throws ServletException if an error occurred     * @throws IOException if an error occurred     */    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        globalResponse = response;        netTool = new NetTool();        netTool.sendGet("", this);    }    public void outPut(HttpServletResponse response){        response.setContentType("text/html");        response.setHeader("content-type", "text/html;charset=UTF-8");        PrintWriter out;        try {            out = response.getWriter();            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");            out.println("<HTML>");            out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");            out.println("  <BODY>");            out.print("  ");            out.print(this.getClass()+" : \n");            out.print(netResult);            out.println("  </BODY>");            out.println("</HTML>");            out.flush();            out.close();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }            }            /**     * The doPost method of the servlet. <br>     *     * This method is called when a form has its tag value method equals to post.     *      * @param request the request send by the client to the server     * @param response the response send by the server to the client     * @throws ServletException if an error occurred     * @throws IOException if an error occurred     */    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        response.setContentType("text/html");        PrintWriter out = response.getWriter();        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");        out.println("<HTML>");        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");        out.println("  <BODY>");        out.print("    This is ");        out.print(this.getClass());        out.println(", using the POST method");        out.println("  </BODY>");        out.println("</HTML>");        out.flush();        out.close();    }    @Override    public void execute(Object... objects) {        // TODO Auto-generated method stub        try {            String result = (String)objects[0];            netResult = new String(result.getBytes(), "UTF-8");        } catch (UnsupportedEncodingException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        outPut(globalResponse);    }}

 

3. Callback:

Import java. io. bufferedReader; import java. io. inputStreamReader; import java.net. URL; import java.net. URLConnection; public class NetTool {public NetTool () {super ();} public void sendGet (String url, CallBack callBack) {String result = ""; BufferedReader in = null; try {String urlNameString = "http://m.weather.com.cn/data/101010100.html"; URL realUrl = new URL (urlNameString); // enable URLConne from the URL Ction connection = realUrl. openConnection (); // set common request attributes // connection. setRequestProperty ("accept", "*/*"); // connection. setRequestProperty ("connection", "Keep-Alive"); // connection. setRequestProperty ("user-agent", // "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); // establish the actual connection. connect (); // obtain all response header fields/** Map <String, List <String> map = connection. getHeaderFields (); // * traverses all sounds Header field for (String key: map. keySet () {* System. out. println (key + "--->" + map. get (key);} * // defines the BufferedReader input stream to read the URL response in = new BufferedReader (new InputStreamReader (connection. getInputStream (); String line; while (line = in. readLine ())! = Null) {result + = line;} catch (Exception e) {System. out. println ("an Exception occurred when sending a GET request! "+ E); e. printStackTrace () ;}// use the finally block to close the input stream finally {try {if (in! = Null) {in. close () ;}} catch (Exception e2) {e2.printStackTrace () ;}} callBack.exe cute (result );}}

 

 

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.