farvilain
farvilain

Reputation: 2562

Spring binding: how to work with something like map?

I have to write a WS that respects a contract I very don't like but that's the work.

For a given request, I have some simple named parameters like user(Integer).

For the moment, it's easy, I wrote a command object with this two field and my request is:

@RequestMapping("/")
public void request(Cmd cmd) {
    [impl]
}

Now the bad parts: I can have any couple of ID=blabla,blabla,blabla

For example, request could be /?user=4&10=ok&3432=Simple,effective

Do you have any solutions that could be nice as having a Map in object command, with one or two Spring binding annotations? Of course, it would be nice if user (and others like that) where not included in the map ^^

Cause I wrote something like this in the endpoint code, but I find it ugly:

final Enumeration<String> paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
    String paramName = paramNames.nextElement();
    String[] paramValues = request.getParameterValues(paramName);
    cmd.getMap().put(Integer.valueOf(paramName), paramValues[0]);
}

Edit

I'd like something like that (if possible)

public class SubmitTaskCmd {
private Integer userID;
private String hash;
    private Integer taskID;
    private Map<Integer, String> others = new HashMap<Integer, String>();

    public Map<Integer, String> getOthers() {
        return others;
    }

    public void setOthers(final Map<Integer, String> others) {
        this.test = test;
    }

    public Integer getUserID() {
        return userID;
    }

    public void setUserID(final Integer userID) {
        this.userID = userID;
    }

    public String getHash() {
        return hash;
    }

    public void setHash(final String hash) {
        this.hash = hash;
    }

    public void setTaskID(final Integer taskID) {
        this.taskID = taskID;
    }

    public Integer getTaskID() {
        return taskID;
    }
}

Upvotes: 0

Views: 89

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

Unless I misunderstood, yes, very simply

@RequestMapping("/")
public void request(@RequestParam MultiValueMap<String, String> allParams) {

Note that there is no name attribute for the @RequestParam annotation. This is explained in the javadoc of @RequestParam.

Upvotes: 2

Related Questions