Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 10 total  RSS 

Ruby Servlets

This WEBrick example demonstrates a basic servlet which displays the current time. Source code copied from At the Forge - Getting Started with Ruby [linuxjournal.com].

#!/sw/bin/ruby
require 'webrick'
include WEBrick

# ---------------------------------------------
# Define a new class
class CurrentTimeServlet
  < WEBrick::HTTPServlet::AbstractServlet

  def do_GET(request, response)
    response['Content-Type'] = 'text/plain'
    response.status = 200
    response.body = Time.now.to_s + "\n"
  end
end

# ----------------------------------------------
# Create an HTTP server
s = HTTPServer.new(
  :Port            => 8000,
  :DocumentRoot    => "/usr/local/apache/htdocs/"
)

s.mount("/time", CurrentTimeServlet)

# When the server gets a control-C, kill it
trap("INT"){ s.shutdown }

# Start the server
s.start

e.g. http://localhost:8001/time
output
Mon Mar 10 23:06:58 +0000 2008

Reference: http://www.webrick.org/

Example file download servlet

// description of your code here

  /**
     *  Sends a file to the ServletResponse output stream.  Typically
     *  you want the browser to receive a different name than the
     *  name the file has been saved in your local database, since
     *  your local names need to be unique.
     *
     *  @param req The request
     *  @param resp The response
     *  @param filename The name of the file you want to download.
     *  @param original_filename The name the browser should receive.
     */
    private void doDownload( HttpServletRequest req, HttpServletResponse resp,
                             String filename, String original_filename )
        throws IOException
    {
        File                f        = new File(filename);
        int                 length   = 0;
        ServletOutputStream op       = resp.getOutputStream();
        ServletContext      context  = getServletConfig().getServletContext();
        String              mimetype = context.getMimeType( filename );

        //
        //  Set the response and go!
        //
        //
        resp.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
        resp.setContentLength( (int)f.length() );
        resp.setHeader( "Content-Disposition", "attachment; filename=\"" + original_filename + "\"" );

        //
        //  Stream to the requester.
        //
        byte[] bbuf = new byte[BUFSIZE];
        DataInputStream in = new DataInputStream(new FileInputStream(f));

        while ((in != null) && ((length = in.read(bbuf)) != -1))
        {
            op.write(bbuf,0,length);
        }

        in.close();
        op.flush();
        op.close();
    }

'ant' build file for HelloWorldServlet and JettyLauncher

A pretty straightforward 'ant' build file. You will need to edit the jetty.home property to indicate where you installed Jetty.

<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="compile" name="hello-servlet">
  <property name="build.dir"	location="classes" />
  <property name="src.dir"	location="src/main/java" />
  <property name="jetty.home"	location="/home/mrw/projects/jetty-6.1.3" />
  <property name="jetty.lib"	location="${jetty.home}/lib" />

  <path id="jetty.lib.path">
    <pathelement path="${jetty.lib}/jetty-6.1.3.jar" />
    <pathelement path="${jetty.lib}/jetty-util-6.1.3.jar" />
    <pathelement path="${jetty.lib}/servlet-api-2.5-6.1.3.jar" />
  </path>

  <target name="compile" description="Compile the project">
    <mkdir dir="${build.dir}" />
    <javac debug="true" destdir="${build.dir}" srcdir="${src.dir}"
	classpathref="jetty.lib.path">
      <compilerarg value="-Xlint:unchecked" />
      <compilerarg value="-Xlint:deprecation" />
    </javac>
  </target>

  <target name="all"  depends="clean,compile"
      description="Recompile from scratch"/>

  <target name="server" depends="compile" description="Launch the server">
    <java classname="com.babblemind.JettyLauncher" fork="true"
	classpathref="jetty.lib.path">
      <classpath>
	<pathelement path="${build.dir}" />
      </classpath>
    </java>
  </target>

  <target name="clean" description="Delete all files created by compile">
    <delete dir="${build.dir}" />
    <delete dir="docs/api" />
  </target>
</project>

Minimal Java servlet

There is nothing particularly original here -- there are variations of this all over the place. This works nicely with my JettyLauncher class (see my other posts on DZone Snippets).


package com.babblemind;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HelloWorldServlet extends HttpServlet{
    protected void doGet(HttpServletRequest httpServletRequest,
	HttpServletResponse httpServletResponse)
	    throws ServletException, IOException {

        httpServletResponse.setContentType("text/plain");
        PrintWriter out = httpServletResponse.getWriter();
        out.println("Hello World!");
        out.close();
    }
}

Minimal Jetty http server with Java servlet

This will start a Jetty http server with a single Java servlet at the root. See http://www.mortbay.org/ for Jetty downloads. This needs HelloWorldServlet from one of my other posts. Make life easier by downloading my ant build.xml as well.


package com.babblemind;

import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;

public class JettyLauncher {
    public static void main(String[] args) throws Exception {
	Server server = new Server(8080);    
	Context root = new Context(server, "/", Context.SESSIONS);
	root.addServlet(new ServletHolder(new HelloWorldServlet()), "/*");
	server.start();
    }
}

Retrieving all Parameters to a Java Servlet

//
// Ref: http://forum.java.sun.com/thread.jspa?threadID=405328&messageID=2184836
//
// The getParameterMap() returns a Map that has Strings as keys and String[] as
// values. That's so you can have ?x=1&x=2&x=3 in your URL query string. The
// keys in the Map must be unique but there can be multiple values for each
// key.
//
// So.. when you pull a value out of a Map created by the getParameterMap()
// method you must cast it to a String[] or else you'll get the value's
// location in memory instead of it's actual value. If you're writing the
// code and know for a fact that you'll always have only one value for each
// param then you can just use yourVar[0] but if there may be multiple
// values for each key then you'll need to loop over each value array.
//

    Map params = request.getParameterMap();
    Iterator i = params.keySet().iterator();
    
    while ( i.hasNext() )
      {
        String key = (String) i.next();
        String value = ((String[]) params.get( key ))[ 0 ];
      }

Simple Java Servlet

// Simple Servlet Skeleton

package net.tvs.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MyServlet extends HttpServlet
{
  private static Log _logger = LogFactory.getLog( MyServlet.class );

  public void init(ServletConfig config) throws ServletException
  {
    super.init( config );
    try
      {
        // Initialization
      }
    catch ( Exception e )
      {
        _logger.fatal( e.getMessage() );
      }
    _logger.info( "MyServlet initialized" );
  }
  
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException
  {
    processRequest( request, response );
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException
  {
    processRequest( request, response );
  }

  protected void processRequest(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException
  {
    response.setContentType( "text/html;charset=UTF-8" );
    String param = request.getParameter( "param" );
    _logger.debug( "Received param: " + param );

    // Implementation...

    PrintWriter out = response.getWriter();
    response.setContentType( "text/xml" );
    response.setHeader( "Cache-Control", "no-cache" );

    out.println( "<response>" );
    out.println( "<param>" + param + "</param>" );
    out.println( "</response>" );
    out.close();
  }

}

avoid web caching

// Set to expire far in the past.
response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");

A Client For the XML-RPC Servlet

// When combined with the Apache XML-RPC library this code
// will let you call the servlet in the snippet "An XML-RPC
// Servlet". Of course, since XML-RPC is pretty ubiquitous
// you can also use this code to call servers in dozens of
// other languages as well.

import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlrpc.XmlRpcClient;

public class XMLRPCTestClient {
    private static final String serverAddress = 
	"http://localhost:8080/lol/remoteapi";
    private static Log log = LogFactory.getLog(XMLRPCTestClient.class);
    
    /** Creates a new instance of XMLRPCTestClient */
    public XMLRPCTestClient(String address) {
        try {
            XmlRpcClient xmlrpc = new XmlRpcClient(address);

            Vector params = new Vector();
            params.addElement("Hello World! Hello!");

            try {
                // this method returns a string
                String result = (String) xmlrpc.execute("echo.echo", params);
                System.out.println(result);
            } catch (Exception e) {
                log.error("The remote procedure call failed.", e);
            }
        } catch (java.net.MalformedURLException mue) {
            log.error(
                "The address given for the XML-RPC interface is bad: " + address);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        XMLRPCTestClient xmlRPCTestClient = new XMLRPCTestClient(
            serverAddress);
    }
}

An XML-RPC Servlet

// This depends upon the Apache XML-RPC library.

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlrpc.XmlRpcServer;

public class XmlRpcServlet extends HttpServlet {
    public class EchoHandler {
        public String echo(String input) {
            return input;
        }
    }
	
    private XmlRpcServer server = new XmlRpcServer();

    private static Log log = LogFactory.getLog(XmlRpcServlet.class);

	@Override
	public void init(ServletConfig config) throws ServletException {
        server.addHandler("echo", new EchoHandler());
	}

	@Override
	protected void doGet(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
        byte[] result = server.execute(request.getInputStream());
        
        response.setContentType("text/xml");
        response.setContentLength(result.length);
        
        OutputStream output = response.getOutputStream();
        output.write(result);
        output.flush();
    }
}


// The following needs to be added to your web.xml file to
// expose the servlet so it may be called remotely.
  <servlet>
    <servlet-name>XmlRpcServlet</servlet-name>
    <servlet-class>XmlRpcServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>XmlRpcServlet</servlet-name>
    <url-pattern>/remoteapi</url-pattern>        
  </servlet-mapping>    

« Newer Snippets
Older Snippets »
Showing 1-10 of 10 total  RSS