Servlet: handling many optional parameters

It's just interesting if there is a more elegant or standard way to handle optional parameters or if you need to check if each of them is null. I have 10+ extra options, so it gets a little ugly.

Ideally, I would like something like the bash: command getopts.

public class MapImageServlet extends HttpServlet {
    ... constructor and other methods ...
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // OPTIONAL PARAMETERS
        if(request.getParameter("boarderSize") != null){
            double boarderSize = Double.valueOf(request.getParameter("boarderSize");
        }

        if(request.getParameter("boarderThickness") != null){
            double boarderThickness = Double.valueOf(request.getParameter("boarderThickness");
        }

        if(request.getParameter("boarderColor") != null){
            double boarderColor = Double.valueOf(request.getParameter("boarderColor");
        }
        ... do stuff with the parameters ...
    }
    ... other methods ...
}
+3
source share
4 answers

Write a utility like this

public class MapImageServlet extends HttpServlet {
//... constructor and other methods ...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    // OPTIONAL PARAMETERS
     boarderSize = ParamUtil.getDoubleValue(request,"boarderSize", defaultValue);

     boarderThickness = ParamUtil.getDoubleValue(request, "boarderThickness", defaultValue);

     boarderColor = ParamUtil.getDoubleValue(request,"boarderColor" , defaultValue);
     //... do stuff with the parameters ...
}

}
public class ParamUtil
{
public static double getDoubleValue(ServletRequest request, String paramName, double defaultValue)
{
     if(request.getParameter(paramName) != null){
        return Double.valueOf(request.getParameter(paramName));
    } else{
        return defaultValue;
    }
}
}
+1
source

You are not looking for: ServletRequest # getParameterMap ?

+2
source

Typically, I used Apache beanutils to extract information from a query parameter map. BeanUtils provides a nice interface that hides all this information from you ...

MyJavaBean mjb = new MyJavaBean();
BeanUtils.copyProperties(mjb, request.getParameterMap());

.... 
// do stuff with mjb properties
logger.debug(mjb.getBorderThickness());
logger.debug(mjb.getBorderSize());
// etc

A bit of extra work, setting up javabean, but easy to use in the future.

0
source

If you are developing this from scratch, I suggest you go with a framework like Spring MVC or Struts. These structures capture input and provide you with a ready-to-use bean with all form data.

0
source

All Articles