content top

Render and capture the output of a JSP as a String

In this tutorial, we will use Spring 3 to render a JSP and capture the output to a String.  Why might you want to do this?  Specifically this need comes up in two instances:

  1. You want to use parameterized JSP pages to send emails to end-users.  You may want to do this in a separate Thread that doesn’t have access to the original user request. Yes, you could use Freemarker or Velocity to build a dynamic email system.  But you have an investment in JSP technology, and would like to use it to produce emails on the fly.
  2. You want to conditionally include a JSP, but you want to render it in the background for speed reasons.  Yes, you could use AJAX for this, but for some reason you can’t or don’t want to.

The goals of this tutorial are:

  • To render an arbitrary JSP, and return the rendered page as a String.
  • To render the JSP without access to any end-user HttpServletRequest, as it might not be available when we need it.
  • To be able to render any normal JSP.  This includes: using normal taglibs in the JSP such as JSTL and Spring tags, being able to render a full HTML page or just a fragment JSP, and being able to include other JSP pages inside our JSP if we need to (that is, use jsp:include), and the use of message bundles (that is, spring:message).
  • The JSP that we render should be Locale-aware, for both messages and numeric formats.

Full source code for this tutorial is available on GitHub.

Continue to the tutorial….

Read More

BigInteger as unsigned long in Java

I’m working on processing video files in Java.  Often, video files will have "unsigned int" or other types that don’t exist in Java.  Unsigned int is easy enough to simulate (using a long), but what about an unsigned long?  No Java primitive integer type is large enough to hold the value of an unsigned long.  Double could do it, but then you lose the ability to use bitwise shift operators and have them do what you expect.

Enter java.math.BigInteger.  BigInteger is a standard, but often overlooked, part of the Java.  The following sample shows how I use BigInteger to simulate an unsigned long in Java.

import java.math.*;

public class ReadUnsignedLong {

    public static void main(String[] args) {
        byte input[] = {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff}; // 64 bits, signed long = -1
        BigInteger signed = new BigInteger(input);
        BigInteger unsigned = new BigInteger(1, input);
        System.out.println("Max Long : " + Long.MAX_VALUE);
        System.out.println("Min Long : " + Long.MIN_VALUE);
        System.out.println("Signed   : " + signed);
        System.out.println("Unsigned : " + unsigned);
        System.out.println("Unsigned > Long.MAX_VALUE ? " + ((unsigned.compareTo(BigInteger.valueOf(Long.MAX_VALUE))==1) ? "true" : "false"));
        System.out.println("Signed == -1 ? " + (signed.compareTo(BigInteger.valueOf(-1)) == 0 ? "true" : "false"));
        System.out.println("Signed * 2 : " + (signed.multiply(BigInteger.valueOf(2))));
        System.out.println("Unsigned * 2 : " + (unsigned.multiply(BigInteger.valueOf(2))));



Note that the trick here is to use the BigInteger(signum, byte[]) constructor.  By forcing the signum to positive (using a 1), you get the unsigned value of the byte array.

The output:

Max Long : 9223372036854775807

Min Long : -9223372036854775808

Signed   : -1

Unsigned : 18446744073709551615

Unsigned > Long.MAX_VALUE ? true

Signed == -1 ? true

Signed * 2 : -2

Unsigned * 2 : 36893488147419103230

Read More

Spring and Hibernate with Annotations

I have to admit it. I had the worst time with Hibernate when I first started learning it a few years ago.  Although I could see the power, the configuration inside Spring was a bit of a nightmare back then.

Today, both Spring and Hibernate support annotation-based configuration, which makes the whole process easier.  Combine this with Hibernate’s Auto-DDL ability (that is, automatic table creation), and it is quite simple to use Hibernate with Spring as long as you follow a few conventions.

The purpose of this article is to build a Hibernate managed Spring web application.  Here are the primary goals:

  • No SQL scripts, not even table creation scripts
  • Minimum XML configuration
  • Relationships defined by Java Persistence API (JPA) annotations
  • Read, write and edit two related classes
  • Make the framework extensible for adding other classes with minimal work

Full source code for this tutorial is available here.

UPDATE March 2014: This code is also available in GitHub at

Interested? Read on…

Read More

Spring Welcome File without redirect

If you use Spring MVC for sites, you have likely run into a problem when you deploy.  How do you make the "welcome file" (for example, index.html) go through Spring and not your web server?  There is an easy way, and it does not involve extra files, javascript, or meta tags.

Let’s say you have a Spring web application called "mywebapp" on your site "".  Your Spring dispatch servlet is mapped to capture *.html urls.  You want to have a welcome file of index.html, so that if a user just types in your webapp name, they go to your Spring handled index.html.  For example, you have these entries in your web.xml file:


<!-- other stuff here -->

<!-- more stuff -->      


But, if your user goes to url, you will get a 404 error.  The problem?  The welcome file redirect bypasses the normal dispatch servlet mapping, so it isn’t used.  This happens in most popular web application containers including Tomcat and Jetty.

There are lots of ways around this, the most common being to add a static index.html in your webapp that just redirects to your Spring home page.  That is annoying, and not search engine friendly.  Instead, there is an easy trick:  add a dispatch servlet mapping for the url of your welcome file (that is, /index.html).


<!-- other stuff here -->

<!-- more stuff -->      


Works like a charm!  Now  will properly go to your mapped Spring controller.

Note: This article originally appeared in my Java blog (  I’m shutting that one down, so I’m moving the good stuff that is left over here!

Read More

Storing the contents of a URL to a file

This example shows how to store the contents of a URL to a File.


public class URLFetcher {
  private String urlString;
  private String fileName;
  public URLFetcher(String urlString, String fileName) {
    this.urlString = urlString;
    this.fileName = fileName;

  public void fetch() throws Exception {
    byte buffer[] = new byte[1024]; // change 1024 to better match your needs
    int numRead = 0;
    URL url = new URL(this.urlString);
    OutputStream os = new FileOutputStream(new File(this.fileName));
    InputStream is = url.openStream();
    while ( (numRead =,0,1024)) != -1) {
      os.write(buffer, 0, numRead);

Using the URLFetcher:

URLFetcher urlFetcher = new URLFetcher("myUrl", "myFileName");
try {
} catch(Exception e) {


Note: This article originally appeared in my Java blog (  I’m shutting that one down, so I’m moving the good stuff that is left over here!

Read More

Strip HTML Tags in Java

I came upon a situation in which I needed to find out if String was "really" empty (not just spaces and junk).  The problem was that the String might have empty HTML tags, like <p></p>.  This handy function removes all the HTML tags, leaving any real content.

function removeHtmlTags(String original) {
    return original.replaceAll("\<.*?>", "");

The results?

removeHtmlTags("<p></p>")  returns the empty string, but

removeHtmlTags("<p>foo</p>")  returns "foo"

Note: This article originally appears in my Java blog (  I’m shutting that one down, so I’m moving the good stuff that is left over here!

Read More

Using the @PathVariable annotation in Spring MVC 3.0

Let’s say that you are creating an user account-based web application in Spring 3.0.  You would like to create a controller that would allow users to see each other’s profile by using a URL such as http://mysite/profile/username.  For example:

http://mysite/profile/Adam  would show user Adam’s profile.

http://mysite/profile/Baker would show user Baker’s profile.

Spring 3.0’s annotated controllers make this kind of mapping easy with the new @PathVariable mapping.

package com.technologicaloddity.hellowebapp;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

public class ShowProfileController {

    public String showProfile(Model model, @PathVariable("username") String username) {
        model.addAttribute("username", username);
        return "showProfile"; // the view name

As you can see, the RequestMapping for the showProfile method has something a bit unusual: {username}.  This is a PathVariable, and it means that this method will serve any request of the format "/profile/someUserName".  We capture the actual username in the next line using the @PathVariable annotation, and store it in the String username.  Now we can use it however we want!

Read More
content top