简体   繁体   中英

Reading nested name-value pair in Servlet

I need to read the HTTP POST request data in servlet. Data is in name-value pair. Following is the data sent to server ( I picked this data from Network tab in google chrome's Inspect Element tool).

data1[roll_no]:32
data1[section]:A
data1[standard]:2
data1[marks][]:54
data1[marks][]:23

I am able to read all the values except list of marks . My attempt to read the values is:

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    log(this.getClass().getSimpleName());
    Enumeration<String> name = request.getParameterNames();
    while(name.hasMoreElements()){
        String param = name.nextElement();
        log(param+" = "+request.getParameter(param));
    }
}

And, here i need some clue to iterate over whole list of marks when param is data1[marks][]

Use getParameterValues()

String param = ...;
if(param.equals("data1[marks][]")) {
    String[] marks = request.getParameterValues(param);
    for(String m : marks) { //iterate over param data1[marks][]
        //do
    }

}

getParameterValues can also come in handy when obtaining values of a <select multiple> element

<select name="multiParams" multiple>
    ...
</select>

There are parameters which are not unique in this case data1[marks][] .

Can you try using request.getparameterValues(param) which is used for scenarios where there an non-unique parameter keys

request.getParameterValues(param) would return an array of Strings. Refer the ServletRequest API for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM