Thursday, December 29, 2011

Spring 3 mvc, web page resource loading optimization

I was working on page loading optimization and found good tools and code to improve page loading speed.

Tools: Firefox YSlow, FireBug, Chrom, Chrom plugin PageSpeed this is how usually looks web page loading in chrom or firefox for java web application. It is because we render page after servlet or action processed request.

That means browser will spend some time on loading resources from your html. It could be 200 ms or it could 500 ms.

Solution is to send send html header part to browser as early as possible.  In Spring 3 mvc xml add interceptor for all your pages.
Spring 3 MVC xml changes:
    <mvc:mapping path="/word/*">
    <bean class="com.wdict.web.controller.HeaderInterceptor" id="interceptor.header"></bean>

Interceptor code:
public class HeaderInterceptor  implements HandlerInterceptor{

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  ServletContext context = request.getSession().getServletContext();
  String url = response.encodeRedirectURL("/WEB-INF/tags/header.jsp");
  RequestDispatcher dispatcher = context.getRequestDispatcher(url);

  /* must use include. With forward the RequestDispatcher seems to hold an internal state
   which prevents to do a forward after this to return to the webclient */
  response.setContentType("text/html; charset=UTF-8");
  dispatcher.include(request, response);
  return true;

public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
After this coding page loading will look like this


  1. Great post for web developers.I have bookmarked your page for the further reference
    Thanks for coding post.
    Professional Web Design

  2. I have read this post. collection of post is a nice one ..that am doing website designing company chennai india and website development company chennai india. That I will inform about your post to my friends and all the best for your future posts..

  3. Wonderful blog & good post.Its really helpful for me, awaiting for more new post. Keep Blogging!

    Web Development New Jersey

  4. Thanks ! for sharing this wonderful news with us. I really like your post as it is informative as well as interesting for making task very easy. so please keep writing.

    java application development

  5. This paragraph will assist the internet people for creating new website or even a weblog from start to end. Thanks for sharing important points in Java development. Keep up the great work!

    14 Best Medical Website Samples, Designed by Optimized360.Com