小编典典

Servlet:处理许多可选参数

java

只是想知道是否有一种更优雅或更标准的方式来处理可选参数,或者是否必须检查每个参数是否为空。我有10多个可选参数,因此变得有点难看。

理想情况下,我想是这样的bash命令: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 ...
}

阅读 221

收藏
2020-11-19

共1个答案

小编典典

编写这样的实用程序

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;
    }
}
}
2020-11-19