Just wondering if there is a more elegant or standard way to handle the optional parameters or if you have to check if every one is null. I have 10+ optional parameters so it is getting somewhat 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 Servlet开发者_高级运维Exception, 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 ...
}
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;
}
}
}
Aren't you looking for: ServletRequest#getParameterMap?
Generally, I have used Apache beanutils to pull information from request 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 little extra work setting up the javabean but easy to use going forward.
If you are developing this from scratch I suggest you go with a framework like Spring MVC or Struts. These frameworks capture the input and provide you with a ready to use bean with all the form data.
精彩评论