Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Clients can invoke servlets too

Launch a servlet with a Java app rather than a JSP

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone

January 18, 2002

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

AYes, 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("<html>");
        out.println("<head>");
            out.println("<title>HelloWorld</title>");
        out.println("</head>");
        out.println("<body bgcolor=\"white\">");
        out.println("<body>");
        out.println("<h1> Hello " + username + "!</h1>");
        out.println("</body>");
        out.println("</html>");
    } 
}


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.

About the author

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).
  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comments (3)
Login
Forgot your account info?

ThanksBy Anonymous on October 5, 2009, 10:44 amThanks for everything, this article solve my doubt.

Reply | Read entire comment

What about server sessions?By Anonymous on August 22, 2009, 4:07 pmWhat about server sessions? If I call url.openConnection() twice, the server recognizes the calls as coming from different clients. request.getSession() returns...

Reply | Read entire comment

Useful Article.By Anonymous on January 6, 2009, 1:41 pmThanks

Reply | Read entire comment

View all comments

Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources