只是想知道是否有一种更优雅或更标准的方式来处理可选参数,或者是否必须检查每个参数是否为空。我有10多个可选参数,因此变得有点难看。
理想情况下,我想是这样的bash命令:getopts。
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 ... }
编写这样的实用程序
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; } } }