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