Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280179

JSP/Servlet getting post form data

I have a JSP created from a Map < String, Double> map that may have different values on different requests.

The JSP displays:

key --> Mutable input field with value for that key

by iterating through the elements of the map. At the bottom of the form, I have a submit button that calls (POST) a servlet that updates all the values in the map.

How would I go about getting the variable list of parameters, since I don't know their names, from the post request?

Right now I'm thinking of doing the following (in pseudo-code and ignoring formatting exceptions):

    Map params = request.getParameterMap();
    Set<Entry<String, Double>> set = params.entrySet();
    Iterator<Entry<String, Double>> it = set.iterator();

    while (it.hasNext()) {
        Entry<String, Double> e = it.next();
        if (map.containsKey(e.getKey()));
            map.put(e.getKey(), e.getValue());
    }

Is there a faster or better way to get dynamic data from the jsp in the servlet?

Upvotes: 0

Views: 2250

Answers (1)

bsimic
bsimic

Reputation: 926

I don't know if it's faster or better, but you could convert the map to JSON and then pass that string back to your servlet as a single parameter instead of having to retrieve the parameter map. Then in your servlet, you can load the parameter string into a JSON Array or something and then iterate through it.

The reason I think that this is a better approach is because then you could pass more parameters to your servlet in the future without having to put conditions in your while loop to not count those as Entry sets.

    //Create array 
    Map map = new LinkedHashMap();
    JSONArray jArray = new JSONArray();

    map.put("id", "asdf");
    map.put("name", "bbbdasfadsbb");
    map.put("address", "sadfasdfasdf");
    map.put("phone", "asdfdsafsdf");
    map.put("details", "asdasdf");
    map.put("randomText", "sdafasdfs");

    jArray.put(map);

    //You can write this string out to a hidden field
    //called mapAsJSONArray
    String mapAsJSONArray = jArray.toJSONString();

    //.......
    //Then in your servlet....   
    String mapAsJSONArray = request.getParameter("mapAsJSONArray");
    JSONArray jsonArray = new JSONArray(mapAsJSONArray);

    for (int i = 0; i < jsonArray.length(); ++i) {
        JSONObject obj = jsonArray.getJSONObject(i);
        String id = obj.getString("id");
        // ...
    }

Upvotes: 1

Related Questions