0

I have a request parameter like

usrInfo:fname=firstname&lname=lastname&company=&addressLine1=wewqe&addressLine2=wqewqe&city=qweqwe&country=United+States

I want to extract values for each name.

I have written below method but it is failing when there is no value for its corresponding name pair.

private String getRequestParamavalue(SlingHttpServletRequest request, String requestParameter, String requestParamName) {

        String reqParamValue = null;

        if (StringUtils.isNotBlank(request.getParameter(requestParameter))) {

            String[] reqParams = request.getParameter(requestParameter).split("&");
            Map<String, String> requestParamMap = new HashMap<>();
            String value;
            for (String param : reqParams) {
                String name = param.split("=")[0];
                value = StringUtils.isEmpty(param.split("=")[1]) ? "" : param.split("=")[1];
                requestParamMap.put(name, value);
            }

            reqParamValue = requestParamMap.get(requestParamName);

        }

        return reqParamValue;

    }

Please, give me an advice on this. Thanks.

user1211
  • 1,507
  • 1
  • 18
  • 27
Kali
  • 21
  • 1
  • 6
  • 1
    When no corresponding name pair. Check the length of param.split("="). – Tom Grylls Dec 23 '16 at 07:39
  • Possible duplicate of [Parse a URI String into Name-Value Collection](http://stackoverflow.com/questions/13592236/parse-a-uri-string-into-name-value-collection) – Misha Dec 23 '16 at 07:50

2 Answers2

0

@Kali Try this

        for (String param : reqParams) {
            String name = param.split("=")[0];
            value = param.split("=").length == 1 ? "" : param.split("=")[1];
            requestParamMap.put(name, value);
        }
David
  • 504
  • 5
  • 21
0

Why not simply do request.getParameter(requestParamName), the HTTPServlet Parent class does the parsing for you.