Clients can invoke servlets too

Launch a servlet with a Java app rather than a JSP

January 18, 2002

2077433Can I use a Java application (client) instead of a JSP (JavaServer Page) to invoke a servlet on an application server?

A: Yes, you can invoke a servlet from a Java client by simply using the java.net.URL and java.net.URLConnection classes.

Here's a simple servlet that takes one parameter, username, and prints out Hello username!:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloJavaWorld extends HttpServlet {
    private final static String _USERNAME = "username";
    
    protected void doPost( HttpServletRequest request, HttpServletResponse response )
        throws ServletException, IOException {
            
        PrintWriter out = response.getWriter();
        String username = request.getParameter( _USERNAME );
        
        response.setContentType("text/html");
        out.println("");
        out.println("");
            out.println("HelloWorld");
        out.println("");
        out.println("");
        out.println("");
        out.println("

Hello " + username + "!

");
        out.println("");
        out.println("");
    } 
}

ContactServlet contains a simple main method that creates a connection to the servlet, POSTs a request, and prints out the response:

import java.io.*;
import java.net.*;
public class ContactServlet {
    public static void main( String [] args ) {
        
        try {
            
            URL url = new URL("http://192.168.1.101:8080/javaworld/servlet/HelloJavaWorld");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            
            BufferedWriter out = 
                new BufferedWriter( new OutputStreamWriter( conn.getOutputStream() ) );
            out.write("username=javaworld\r\n");
            out.flush();
            out.close();
            BufferedReader in = 
                new BufferedReader( new InputStreamReader( conn.getInputStream() ) );
            
            String response;
            while ( (response = in.readLine()) != null ) {
                System.out.println( response );
            }
            in.close();
        }
        catch ( MalformedURLException ex ) {
            // a real program would need to handle this exception
        }
        catch ( IOException ex ) {
            // a real program would need to handle this exception
        }
    }
}

Use ContactServlet as a guide whenever you need to communicate with servlets that accept POSTs. If your servlet has more than one parameter, simply separate each key/value pair with an ampersand (&). Also be sure to pass each value of the key/value pair through URLEncoder.encode. I didn't do so here because the value would have remained unchanged. If your values contain special characters, you must encode them, otherwise the POST will fail!

In "Abstract Classes and Interface Practicum," I presented a reusable framework for key/value pair communication. Instead of reiterating those points here, below I simply present a message and a main method that fits into the framework and communicates with the HelloJavaWorld servlet:

public class HelloJavaWorldMessage extends AbstractMessage {
    private String _username;
    private final static String _KEY = "username";
    
    public HelloJavaWorldMessage( String username ) {
        setUsername( username );
    }
    
    public void setUsername( String username ) {
        _username = username;
    }
    
    protected String[][] values() {
        String [][] values = {
            { _KEY, _username }
        };
        return values;
    }
    
}
public class ContactServlet {
    public static void main( String [] args ) {
        
        Message message = new HelloJavaWorldMessage( "JavaWorld" );
        MessageBus bus  = new HttpMessageBus( "http://192.168.1.101:8080/javaworld/servlet/HelloJavaWorld" );
        
        try
        {
            String response = message.send( bus );
            System.out.println( response );
        }
        catch( BusException ex ) {
            // a real program would need to handle the exception
        }
    }
}

I encourage you to review the framework. It can save time when you're communicating with servers that communicate through key/value pairs.

Tony Sintes is an independent consultant and founder of First Class Consulting, Inc., a consulting firm that specializes in the bridging of disparate enterprise systems and training. Outside of First Class Consulting, Tony is an active freelance writer as well as author of Sams Teach Yourself Object-Oriented Programming in 21 Days (Sams, 2001; ISBN: 0672321092).

Learn more about this topic

Join the discussion
Be the first to comment on this article. Our Commenting Policies