mercoledì 27 gennaio 2010

JSP functions [ENG]

The usage of JSP scriptlets is discouraged, and for many good reasons. But just in case you didn't know you might add methods to the implicit class generated by Jasper from the JSP source file.

A couple of days ago I found this in our code base:

  try
  {
    strPagina = CString.isNullReplace(request.getParameter("pic_pagina")).trim();
    if (strPagina.length() == 0)
    {
      strPagina = CString.isNullReplace(authentBean.getString("pic_pagina")).trim();
    }
    authentBean.set("pic_pagina", strPagina);
    strDatePic = CString.isNullReplace(request.getParameter("pic_date")).trim();
    if (strDatePic.length() == 0)
    {
      strDatePic = CString.isNullReplace(authentBean.getString("pic_date")).trim();
    }
    authentBean.set("pic_data", strDatePic);    
    strEventPic = CString.isNullReplace(request.getParameter("pic_event")).trim();
    if (strEventPic.length() == 0)
    {
      strEventPic = CString.isNullReplace(authentBean.getString("pic_event")).trim();
    }
    authentBean.set("pic_event", strEventPic);    
  }
  catch (Exception e)
  {
    throw new Exception(param_error);
  }

and felt compelled to refactor it:

  try
  {
      set("pic_pagina", authentBean, request);
      set("pic_date", authentBean, request);
      set("pic_event", authentBean, request);
  }
  catch (Exception e)
  {
      throw new Exception(param_error);
  }

How did I implement the set method?

<%!
    void set(String parameterName, ArrayBean authentBean, HttpServletRequest request)
    {
       String strValue = CString.isNullReplace(request.getParameter(parameterName)).trim();
       if (strValue.length() == 0)
       {
         strValue = CString.isNullReplace(authentBean.getString(parameterName)).trim();
       }
       authentBean.set(parameterName, strValue);
    }
%>

Please note the <%! opening tag.

See also this JSP Tutorial.

Nessun commento: