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….

Continue reading Render and capture the output of a JSP as a String

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 https://github.com/technologicaloddity/departments

Interested? Read on…

Continue reading Spring and Hibernate with Annotations

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 "mywebsite.com".  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:

<web-app>

<!-- other stuff here -->

    <servlet-mapping>
        <servlet-name>dispatch</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
  
<!-- more stuff -->      
    
</web-app>    

 

But, if your user goes to url http://mywebsite.com/mywebapp/, 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).

<web-app>

<!-- other stuff here -->

    <servlet-mapping>
        <servlet-name>dispatch</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    
    <servlet-mapping>
        <servlet-name>dispatch</servlet-name>
        <url-pattern>/index.html</url-pattern>
    </servlet-mapping>    
    
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
  
<!-- more stuff -->      
    
</web-app>    

 

Works like a charm!  Now http://mywebsite.com/mywebapp/  will properly go to your mapped Spring controller.

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!

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!

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.

Continue reading Hello World Web App using Spring Annotations Part 6