Spring MVC and WebFlow – Released!

Well, it took a while but I’m relieved that the course is now out. Full details available at the virtualpairprogrammers.com site

And you can preview the opening chapter over at YouTube

I’ll be uploading some more previews of the more interesting chapters later this week, and for those of you needing the DVD edition, it will be available on Amazon as soon as we get the stock to them.

One of the reasons for the delay was the sheer amount of information in Spring-MVC. Despite a long running time (8 hours), there are still one or two topics that I wish had made the final cut, so keep an eye out for a few blog posts over the next few weeks that will fill in some gaps.

Another reason was the last minute decision to add WebFlow – I’m very glad I did this because although I love WebFlow, there’s not that much out there to help beginners.

I hope you like the course!

Changes to the Spring-MVC Course – now with added WebFlow!

We’re getting closer to releasing the Spring-MVC course and as we reach the end it’s becoming clear that some juggling is needed to the back end of the course.

Many people have contacted me to ask about Spring WebFlow, and whether we’ll be doing a course on it. I’d always planned to do a separate standalone course on this topic, but on reflection I’ve decided it would fit more naturally as a chapter on the Spring-MVC course itself.

The revised running order is now:

1: Introduction
2: An overview of MVC
3: First steps in Spring MVC
4: Mapping Parameters, Accessing Sessions
5: Internationalization (i18n)
6: Form Handling and Validation
7: Validation and JSR-303
8: Alternative views and Ajax
9: Spring WebFlow – the Basics
10: Going further with WebFlow

The chapter on Post-Redirect-Get was too small to stand on it’s own and is now part of the form handling chapter.

I think this outline is a bit tighter and more focussed, and with WebFlow included, will be much better value.

It does, however, mean a slight delay to allow time for scripting and recording of the more advanced material, but not a big one, we’re now on for Friday 6 August.

Working with Ajax and JSON in Spring-MVC

I’m now working on the final major chapter of the Spring-MVC course, how to use Ajax with Spring.

I must say I’m pretty shocked (in a good way) at just how simple the support for Ajax in Spring-MVC is.

On the course, we’re going perform a search against a database of books, and produce a list of near matches on the fly, as the user types into a text box on the web form. Something like this, with the results updating as soon as I type a letter in the search box…

I’d like to be able to send the list of matching books back to the web browser in JSON form. Although in the early days of Ajax, data was sent in XML form (the X in Ajax), these days JSON is a more natural choice as it is more compact and much easier to manipulate on the JavaScript client.

For details of what JSON looks like, see here. For example, a collection of book data might look something like:

[{"author":"Will Self","title":"Great Apes"},
 {"author":"Charles Dickens","title":"Great Expectations "},
 {"author":"Ken Kesey","title":"Sometimes a Great Notion "},
 {"author":"F. Scott Fitzgerald","title":"The Great Gatsby "}]

So I’d like my controller to be able to send back the results in the form of JSON. You might be thinking that I need to convert my Java objects manually – but in fact Spring-MVC makes it almost trivial:

  1. Annotate your controller method with @ResponseBody. This annotation tells Spring that the response to the browser should be serialised (ie converted from plain Java Objects into some kind of flattened, encoded structure).
  2. Add the JAR files from the Jackson project into your lib directory. Jackson is capabale of transforming object graphs into JSON form.
  3. You also need the <mvc:annotation-driven/> directive in your Spring wiring. By the time we do Ajax on the course, we’ll have added this already, but if you’re reading the blog separately from the course, you’ll need to make sure you’ve done this.

These three things combined tells Spring that we want to send the response back from the method annotated with @ResponseBody in the form of a JSON graph.

So, the controller looks wonderfully simple:

@RequestMapping("/looseSearch")
public @ResponseBody List<Book> performLooseSearch(@RequestParam("CHARS")String chars)
{
    return bookService.searchBooksByLooseMatch(chars);
}

In terms of Spring-MVC, that’s all there is to know. You now just need to code a front end capable of making an Ajax call. Until recently, the recommended approach in Spring was to use a framework like DWR – a framework that allowed us to call Java code as if it were a JavaScript method.

These days, however, the amazing jQuery library is the preferred choice. jQuery is a library that makes everyday JavaScript tasks such as making Ajax calls almost trivially easy.

Now, jQuery is beyond the scope of Spring-MVC so I can’t provide a tutorial here, but I can show a code fragment that demonstrates how to call our loose search:

<head>
   <script type="text/javascript" src="/scripts/jquery-1.4.2.min.js" />
  
   <script type="text/javascript"> 
 
  function doSearch() {   
     $.getJSON("looseSearch.do", { CHARS: $('#searchBox').val() }, function(data) 
               {   
                  $('#results').text('');
    
                  for (var index in data) {
                     $('#results').append('<p>' + data[index].title + '</p>'); 
                  }
               });
 }
   </script>
</head>

<h1>Loose Search Test</h1>

<input type="text" id="searchBox" onKeyUp="doSearch();"/>

<div id="results">
 Results will appear here...
</div>

All you need to do is download the jquery JavaScript file from here and make sure it is picked up by your page.

All references to $ are jQuery calls.

On line 7, getJSON performs an Ajax call to the URL “looseSearch.do” – hence our controller will be run. The request parameter CHARS is populated with whatever is contained in the “searchBox” input field.

When (and if) a response is received by the server, the callback function that I’ve provided is invoked (lines 8-14). In the callback function, I simply clear the “results” div (line 9), and then I loop around the JSON results. For each element in the results, I extract the title and wrap it around a paragraph tag.

Line 21 ensures that the doSearch() function is called everytime I release a key in the input field.

If you’re interested in seeing this full example coded, the Spring-MVC video course is released on 30 July 2010. You can register an interest by sending a blank email to subscribe@virtualpairprogrammers.com, and don’t worry, we won’t use your email address for any purpose except for keeping you updated with new courses.

The Spring IDE has a New Update Site

Edit July 2011: It seems the springide.org address is back up and running again, please post a comment on this post and I’ll monitor the situation. As of today, you can do the following:

  1. Help/Install New Sofware
  2. Add… button, then “http://springide.org/updatesite” (without the quotes) for both the name and location
  3. Click “Core/Spring IDE”
  4. Click “Next”, “Next” and accept the licence, then finish.

On the Spring Fundamentals course, we look at the Spring IDE. The name is a bit misleading, it’s really just a plug in for Eclipse rather than a full blown IDE.

Nonetheless, it is still a powerful plug in. As well as validating your XML configuration (so you can trap wiring errors without running the application), you can also see a very well presented graph of your beans, making it very easy to spot wiring problems.

However, since we recorded the course the URL of the update site has changed (springide.org now gives 404 errors).

The correct update site is now http://dist.springframework.org/release/IDE.

(I should note that SpringSource, the company founded by the creators of the Spring Framework also supply a full IDE based around Spring and Eclipse called the SpringSource Tool Suite. We didn’t cover this on the course, so see http://www.springsource.com/products/sts for full details).

Java Web Application Security – Part Two, Form Based Authentication

In Part One of this series on Java Security, we made our “add-new-book.jsp” page accessible only to those logged in as administrators. At present, we’re using so-called “BASIC Authentication” which in essence is asking the browser to handle the login challenge.

This is acceptable in some applications, but in general it is rather weak. The login box presented by the browser is very basic. Let’s look at how it looks on Firefox first.

Basic but functional. Particularly cute is the challenge: “The site says ‘Please log in'”. Recall that ‘Please log in’ was the string we used in the <realm-name>. Yet Google Chrome presents our <realm-name> differently:

Ugly. BASIC Authentication is ok for quick and dirty apps, but we can do better. We’ll now upgrade to “Form Based Authentication”. To do this, we provide a JSP page with a username/password box.

Step 1: Write the Login Form

I won’t bother writing a pretty form – I’ll leave it to you to make it look gorgeous.

File: login.jsp

<h1>Please Login</h1>

<form method="post" action="j_security_check">
 <p><label>Username:</label> <input type="text" name="j_username"/></p>
 <p><label>Password:</label> <input type="password" name="j_password"/></p>
 
 <input type="submit" value="Login"/>
</form>

Note firstly the name of the action – j_security_check. I haven’t made this name up – it’s a part of the Java Web standard, and is a predefined servlet. It is responsible for performing the authentication check.

Also part of the standard are the two parameters that the security check servlet demands – j_username and j_password.

Now the form is built, we need one further JSP (or HTML) page. If the user fails to login correctly, we need to tell them they have failed, so we need a “failed login” page.

File: failed-login.jsp

<h1>Sorry, please try again</h1>

Again, I’ll leave it to you to make this page look good!

Step 2: Configure

We now need to upgrade our web.xml to point to our form and failure page. As always, the XML is a bit verbose but routine…

File: web.xml

<login-config>
   <auth-method>FORM</auth-method>
   <form-login-config>
      <form-login-page>/login.jsp</form-login-page>
      <form-error-page>/failed-login.jsp</form-error-page>
   </form-login-config>
</login-config>

Don’t forget to remove your existing <login-config> with the BASIC <auth-method>.

Step 3: Test

The most important thing to remember is that we don’t need to navigate to the login page directly. As before, we try to navigate to the “add-new-book.jsp” page, and the server now knows that before access is allowed, the login.jsp page must be presented first.

So let’s deploy and see what happens – the screenshot shows what happens when we navigate to “add-new-book.jsp”.

Notice that the URL in the browser bar is the name of the target page, even though it is actually login.jsp that has been presented.

And after we type invalid credentials into the form…

So, thanks to the predefined j_security_check servlet, you can get a reasonable security system up and running in a Java Web Application without writing a single line of code. Remember that this is all part of the standard and will work on any server you choose to use.

At the moment, our usernames and passwords are hardcoded into a file on Tomcat. This is fine for development but we need better for production.

There are actually many different ways you can authenticate users – using single sign on, Facebook Authentication, OpenID and so on, but the most common approach at first would be to provide a database table of usernames and passwords.

I could talk in detail about how to do this, but it is specific to your application server and it is fairly well documented by most servers.

If you are using Tomcat, then the documentation for setting up your table is available here

Don’t be put off by the term “Realm”. A Realm is just a “strategy for authenticating users”.

Java Web Application Security – Part One, Basic Authentication

One topic that we didn’t cover in the Java Web Development course was how to secure your application.  In this post, I’ll show that every Java webserver comes with a basic security model that will address many project’s requirements.

I’ll assume that you’re already familiar with Java Web development, and are able to build and deploy to a server such as Apache Tomcat.

Let’s start with a regular webapp. Any Java web application will do. I’m using the application we build on the Java Web Development course.

At the moment, all users can access every page in the application. The aim is for the page “add-new-book.jsp” to be accessible to logged-in administrators only.

Step 1: Switch security “on”

The first step is to declare in the web.xml file that we want to use security in our application. We’re going to start with the simplest form of web security, BASIC authentication. You’ll be familiar with this even if you don’t realise it – this is where the browser pops up a simple username and password box.


   BASIC
   Please log in

“realm-name” is just a string that will appear in the login dialog box.

This config tells Tomcat to instruct your browser to pop up a username/password challenge if a secured resource is accessed.

Step 2: Declare Your Secure Resources

A secured resource is just a URL, and we declare a URL to be secure with the following addition to web.xml:


 
  Admin Pages
  /add-new-book.jsp
 

 
  admin
 
 

It’s rather verbose XML (as usual with web.xml), but it is fairly straightforward. The URL ending with “add-new-book.jsp” will require the user is logged into the role of “admin”.

Now we’ve added this protection, let’s deploy the app and try to add a new book.

As we haven’t set up a valid administrator, whatever we enter here will result in failure. This is reported as a HTTP error status 401, and by default we see the following page:

Step 3: Authentication

So we’ve locked down part of our app – but how can we open it up to the administrators?

Authentication is the mechanism a web site uses to determine who the user is and to which role they belong. unfortunately, authentication is not part of the Java web specification, so different servers implement authentication in different ways. I’ll describe how authentication is done in Tomcat – for other servers such as Resin or Jetty, you’ll need to check their reference manuals.

The easiest way to set up users and roles in tomcat is to edit the file in {tomcat_home}/conf/tomcat-users.xml. I’ve edited the contents of the file to look like this:

<tomcat-users>
   <role rolename="admin"/>

   <user username="rich"
         password="TooCoolForSchool" 
         roles="admin"/>
</tomcat-users>

So the server will recognise a user called “rich” as being a member of the “admin” role.

After making the edit, we then need to restart Tomcat. We can now visit the page add-new-book.jsp – as long as we enter the username and password above. Notice that it isn’t necessary to implement a separate login page or to have to go to a login page first – when we try to visit the protected resource, the process is handled automatically by Tomcat.

You may be horrified that we have hardcoded a user into a file on the server. Of course, in a real application we would want a more sophisticated authentication strategy such as a database lookup. In part three of the series I’ll show you how to do that on Tomcat. But changing the strategy is just a configuration change, so using this hardcoded file of usernames and passwords is perfect for your development environment. You can always switch to something more robust once you go live.

The next problem is that the login dialog box is not very professional looking. Basic authentication is just that – basic. In part two of this series, I’ll be showing you how to add Form Based Authentication to your web app.