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

Storing the contents of a URL to a file

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

URLFetcher.java:

import java.io.*;
import java.net.URL;

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 = is.read(buffer,0,1024)) != -1) {
      os.write(buffer, 0, numRead);
    }
    is.close();
    os.close();
  }
}

Using the URLFetcher:

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

 

Note: This article originally appeared in my Java blog (javanature.com).  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 (javanature.com).  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;

@Controller
public class ShowProfileController {

    @RequestMapping("/profile/{username}")
    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

Hello World Web App using Spring Annotations Part 6

In part 6, the final part of this series, we’ll create the View to display our message to the end-user.  We’ll also run the whole app under Tomcat and Sysdeo, and even show a bit of Java class hot-swapping.  Lastly, we will create a WAR file from our project.

If you have missed the previous parts of this series, you can find them here: part 1, part 2, part 3, part 4, part 5.  You’ll need to setup your environment from parts 1-4 if you want to follow along with the examples here.

You can download the full source of this project from http://technologicaloddity.com/code/general/HelloWebApp.zip.

Read More
content top