Posts Tagged ‘Spring MVC’

Spring MVC 3.0 annotations and HTTP/1.1 Cache-Control headers

Friday, July 30th, 2010

Recently I re-experienced some classic but annoying problem we web developers all have run into at least once. And like for the most of those kind of problems, we do a quick google search, find the answer, implement it and try to remember it. Sometimes we succeed doing so, sometimes some other strange problem overwrites that spot on our hard disk or like for the most of these problems and their solutions, time starts switching bits randomly in our head so we first start fail at reconstructing the total story and eventually start forgetting the whole story..

That being said, the problem I ran into was disabling the browser cache for dynamic generated html pages. That’s easy I hear you thinking and your right, it is. Only, how do you achieve it with SpringMVC 3.0?

I remembered vaguely something about cache parameters in the header of the response. So I first tried adding the following parameters in the section of my html page.

<meta http-equiv="Expires" content="0"/>
<meta http-equiv="Cache-Control" content="no-cache"/>
<meta http-equiv="Pragma" content="no-cache"/>

A good attempt, but all of my browsers (Safari, Chrome, Firefox – didn’t try other ones) kindly ignored me. So I googled and I learned that most of the browsers ignore these settings and even if some browser would take them into account, proxy servers never will. Proxy servers don’t read the HTML itself, they look at the HTTP headers and see the HTML as some response stream they don’t look into.

Aha! Let’s see what kind of HTTP header parameters we can set. Again my friend Google learned me:

Pragma: no-cache
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Cache-Control: max-age=0, no-cache, no-store

So now the only problem remained how to get these parameters on the response stream of my SpringMVC 3.0 Controller objects. If you are using Spring MVC with xml bean declaration, your controllers will inherit from the org.springframework.web.servlet.support.WebContentGenerator class where you set some properties to enable the above mentioned parameters. But when you are using annotations like I do, you’ll have to figure out something else..

You could add the HttpServletResponse as a parameter to your @RequestMapping annotated method and manually add the parameters for each request. It will work. But I don’t like it. One of the ideas behind annotating the controller objects was to make unit testing easy by excluding all the HttpServletRequest/Response stuff so one doesn’t have to mock them. So I don’t want to pull them back in.

I fixed my problem by using the org.springframework.web.servlet.mvc.WebContentInterceptor. The interceptor extends the WebContentGenerator class so it has the setter methods again I need to enable the header parameters. In my spring config file I have now this:

    <context:component-scan base-package="com.idevelop.abc"/>
    <mvc:annotation-driven/>
    <mvc:interceptors>
        <bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor">
            <property name="cacheSeconds" value="0"/>
            <property name="useExpiresHeader" value="true"/>
            <property name="useCacheControlHeader" value="true"/>
            <property name="useCacheControlNoStore" value="true"/>
        </bean>
    </mvc:interceptors>

Again, it works, but I don’t like it.
Now I have enabled on all the requests that are handled by SpringMVC the ‘no cache’ parameters. Not something you would like to do in a real application. E.g. some pages can be cached, some can live for e.g. 1 hour, some for a week, and so on.

To resolve this, you could extend the WebContentInterceptor and write your own interceptor and tweak your cache management based on the incoming urls. But again, I don’t like it.

What I would really like is a new annotation: @Response And I would put it on my @RequestMapping methods. After all, if your handling the request with annotations, why not the response ?
The parameters it should take could be the same as the ones in the WebContentInterceptor to start with.
Such an annotation could look like this:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface Response {

    boolean useExpiresHeader = false;

    boolean useCacheControlHeader = true;

    boolean useCacheControlNoStore = true;

    int cacheSeconds = -1;
}

What do you think? Good enough to put it as a feature request on the SpringMVC jira ?

My web stack: Spring MVC + Velocity + jQuery

Tuesday, February 2nd, 2010

The last few weeks I have been exploring what’s living in the web development world. I looked at frameworks like Wicket, GWT & JSF but they couldn’t convince me.

For me, Web development is about generating HTML pages. And I like to do that in a transparent way. I.e. web pages should be able to be developed and maintained by… web developers. It happens a lot that web developers are involved in the project for creating and designing the look and feel of a website. But then, the jpg files (or if you are lucky, you already get a html page..) are hand over to the developer who can start modifying and hacking it into a JSP page or try to programmatically reproduce the HTML page. And face it, that just doesn’t work. The programmer knows HTML, but he’ll never be damn good at it. He struggles, fights with his rendering, but for some reason that stupid DIV won’t stay on its place. He’s loosing the battle. The web developer has to come over and help the Java developer. The web developer sees what a mess the Java developer made of his beautifully designed page and gets frustrated. The Java developer is already frustrated of all the time he lost in rendering a stupid HTML page.. you get the picture. So why not use the knowledge of the web developers? They are creative wizards, they know how to implement their designs in valid XHTML with DIV’s instead of tables etc.. And they just happen to be damn good at it.

That being said, what is out there that does match my needs?

I really like Velocity. Starting from the visual design a web developer makes his html page and then can cut into pieces himself. These pieces can be put into velocity templates and the only thing the Java developer has to do is merging the dynamic content and labels into it by replacing the static placeholders with variables and some for loops and stuff like that. Maintaining is also easy: the templates still look and feel like plain html and both the web developer and java developer can easy adapt the templates. So IMHO, a win-win situation.

And what about front end logic? I don’t like the magic of frameworks like GWT and Wicket. As long they do what you expect them to do, they are very handy. But once something doesn’t work as you expect, or something won’t render/behave in IE or Firefox like it should, you can start debugging and hacking to get it right. Secondly, I like to separate my view from my logic. That way, the GUI guys can do their thing without being annoyed of all the javascript in the html page. jQuery is the answer. Once the HTML page is loaded into the browser, the jQuery code attaches itself on the different DOM objects. So the glueing is done at runtime and not at design time. The only drawback is that it might seem harder to maintain the javascript as long the design of HTML page isn’t finalized. But isn’t that always the case? jQuery has also a very nice and powerful syntax. The $() notation uses CSS selectors and a fluent interface which makes it very pleasant to work with. And not to forget, jQuery is designed as a wrapper. I.e. it wraps the IE and Firefox javascript objects so one has not to worry about browser specific code. That’s something we all can appreciate :)

At the backend, I go for Spring MVC. In my opinion they implemented the MVC pattern very elegantly. To be honest, I never looked into Spring MVC before (I knew that it existed but that was it..) and started writing a web framework myself based on my .NET web development experience. So I came up with a DispatcherServlet (indeed, I even had the same name :) ), had some URL resolving/generating filter logic and a Page object that served as Controller. Thank god I stumbled on Spring MVC while googling for an other Spring issue. I would have came up with the same stuff, but it would never have been as complete and solid as Spring MVC already is. So what do I really like? Well, being able to use variables in URL patterns is a powerful thing. Or the fact one can render the same request in different ways depending on e.g. the extension of the request. And they have different view templates for e.g. JSON, Velocity, XSLT..

And what about Security? Well, for me there is only one option: Spring Security (formerly known as Acegi Security). It is very complete and easy to set up. And off course, it integrates nicely into the Spring application context, which I couldn’t miss anymore.

To complete my stack overview, on the Data layer, I choose Hibernate above JPA. IMHO, pure JPA is not useable in decent project. One almost always end up using Hibernate specific things, so I prefer to go Hibernate all the way from the beginning.

And that’s it. And what about Ajax I hear you think? Well, that’s covered. jQuery has a very good Ajax support and on the backend site, it’s just a matter of writing appropriate controllers and render the model into XHTML or JSON.