Tag Archives: Spring

Getting Logged On User in a Spring-Web Application

In a web application, it can be useful to get the logged on user’s name and display it within a web page, for example as a link to allow the user to edit their profile.  In a Spring Web application the username can easily be obtained in a controller and passed via a map to the user interface.

To get the username in a controller class, we would use theSecurityContextHolder.getContext().getAuthentication().getPrincipal() method to get hold of the principal. We can then call the .getUsername() method to get the username of the currently logged on user.

@Controllerpublic class PageController {
 
  @RequestMapping(method = RequestMethod.GET)
 
  public ModelAndView handleRequest() {
    User user = (User) SecurityContextHolder.getContext()
       .getAuthentication().getPrincipal();
    Map userModel = new HashMap();
    userModel.put("username", user.getUsername());
    return new ModelAndView("page", "model", userModel);
  }
}

The username can then be displayed in an HTML page as:

<c:out value="${model.username}" />

Spring 3.1.0 M2 Released

The second milestone release of Spring 3.1 has been released.

The software can be obtrained from SpringSource’s Maven repository ( http://maven.springframework.org/milestone) or from the SpringSource community download page.

New features in this release include:

  • Code equivalents for Spring’s XML namespaces
  • Builder-style APIs for code-based Hibernate configuration
  • TestContext framework support for @Configuration classes and bean definition profiles
  • Support for injection against non-standard JavaBeans setters
  • Support for Servlet 3 code-based configuration of Servlet container
  • Support for Servlet 3 MultipartResolver
  • JPA EntityManagerFactory bootstrapping without persistence.xml
  • New HandlerMethod-based Support Classes For Annotated Controller Processing
  • Consumes and Produces @RequestMapping Conditions
  • Working With URI Template Variables In Controller Methods
  • Validation For @RequestBody Method Arguments

Spring 3.1.M1 @Cacheable Doesn’t Evict – A Workaround

Spring 3.1 introduces a new feature to allow methods to be cached and evicted thus allowing resource heavy methods to be avoided where possible. Caching is enabled via the new @Cacheable and @CacheEvict annotations. For full details of Spring caching have a look at Costin Leau’s blog post.

One example of caching would be, for example, database activity. We can apply the @Cacheable annotation to a find operation and then apply the @CacheEvict to an update / delete operation. In this sense, caching would work much like a second level cache in Hibernate or JPA.

To enable caching on a find method, the method needs to be annotated with the @Cacheable annotation identifying which cache to use. Spring allows multiple caches to be defined each of which can be backed by a
different caching abstraction.

@Cacheable("items")
public Item find(long itemId) {
     Item item = entityManager.find(Item.class, itemId);
     return item;
}

When it is time to invoke the find method, Spring checks in the specified cache to see if the results of the operation have already been cached and if the results can be therefore be returned from cache instead of invoking the method. Spring uses the method arguments as the key, so in this case the itemId parameter.

To evict an entry from the cache when an object is updated in the database, the @CacheEvict annotation can be used. Again, this annotation takes a parameter identifying which cache to use.

@CacheEvict(value = "items", key = "#item.id")
public void updateItem(Item item) {
     entityManager.merge(item);
}

You can see in this sample code, that Spring Expression Language has been used to define the key for items in the cache. This is necessary as a long is not being used as the key as in the previous example so cache entries would not be found.

This all looks pretty straightforward, but unfortunately due to bug SPR-8015 it does not work.

To quote the bug report:

… it’s not working because the DefaultKeyGenerator simply hashes the given parameters as is. In case no key attribute is configured (just like in the above example) the parameters will be handed in as single-element-Object[] causing a different hash to be created than if the single object would be handed to the key generator directly

This is fixed in Spring 3.1.M2, but in the meantime, can be worked around by explicitly specifying the key on the @Cacheable annotation, i.e.

@Cacheable(value = "items", key = "#itemId")
public Item find(long itemId) {
     Item item = entityManager.find(Item.class, itemId);
     return item;
}

Using Spring for J2EE apps

There’s an interesting thread going on over at The Server Side based upon a comment made by Ugo Cei – “I seriously wonder why anyone would want to develop anything substantial in Java nowadays without using Spring.”

Having done J2EE applications using both “traditional” approaches (i.e. EJB 2.x) and more lightweight approaches (e.g. Spring), I’d choose the more lightweight approach every time. Probably the majority of J2EE applications don’t need the full J2EE stack and Spring provides all the tools necessary to get the job done. As I mentioned in a previous post, when I’ve done projects without using Spring, I’ve missed not having dependency injection (why should I really care about getting a database connection?).

EJB 3 looks interesting however, yet there is a large momentum with Spring at the moment, so I don’t see either technology toppling the other. I think both technologies will co-exists side by side.

I Miss Dependancy Injection

I’ve just started working on a fairly small web application project that uses Struts as its web framework. I like Struts, its fairly simple to use and covers just about everything I need for my application.

Since I’m now using NetBeans 5 Beta 2 (eventually!), I though I would have a read of Geertjan’s series of articles on how to use Struts with NetBeans. These are good articles if you are new to Struts or want to see how NetBeans handles Struts development.

However, since I’ve used Spring in the past, Geertjan’s method of grabbing database connections seems odd. I’m not detracting in any way from the series of articles (which are great) which are intended to discuss struts development with NetBeans – this is more of a problem I have with Struts.

Once you get into the rhythm of using DI, it seems strange going back to explicitly setting things up. For example datasources – injecting datasources directly into DAOs is one of the best things that I like about Spring and something that seems completely unnecessary now when using Struts.