How to extract request parameter into name value collection

809 views Asked by At

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.

2

There are 2 answers

0
David On BEST ANSWER

@Kali Try this

        for (String param : reqParams) {
            String name = param.split("=")[0];
            value = param.split("=").length == 1 ? "" : param.split("=")[1];
            requestParamMap.put(name, value);
        }
0
akshay nakhawa On

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