7
\$\begingroup\$

I have a form that submits to a servlet that has optional parameters. If they are empty they are just ignored. This is the template I am using:

if (!(param = (String)params.get("httpParam")).equals("")) {
 // Handle parameter
}

It doesn't quite feel right. It works, but I think it could be more readable. Any suggestions?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Apr 18, 2011 at 13:54
\$\endgroup\$
0

2 Answers 2

4
\$\begingroup\$

I suggest extract code for getting parameter to separate method (see extract method refactoring's tehnique):

param = getOptionalParameter("httpParam");
if (! param.isEmpty()) {
 // Handle parameter
}
answered Apr 18, 2011 at 14:24
\$\endgroup\$
3
\$\begingroup\$

You can populate a map containing all your parameters and than convert that map into POJO:

 HashMap map = new HashMap();
 Enumeration names = request.getParameterNames();
 while (names.hasMoreElements()) {
 String name = (String) names.nextElement();
 map.put(name, request.getParameterValues(name));
 }
 BeanUtils.populate(data, map);

Where 'data' is your POJO class with attributes corresponding to your parameter names.

answered Apr 19, 2011 at 8:45
\$\endgroup\$
1
  • 1
    \$\begingroup\$ How about request.getParameterMap() instead of while loop? \$\endgroup\$ Commented Dec 3, 2011 at 11:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.