user9239399
user9239399

Reputation:

Correct way to put parameters in a function

I have a huge form with around 30 parameters and I don't think it's a good idea to do what I usually do. The form will be serialized and pass all the parameters via ajax post to spring controller.

I usually do like this:

 @RequestMapping(value = "/save-state", method = RequestMethod.POST)
public @ResponseBody
void deleteEnvironment(@RequestParam("environmentName") String environmentName, @RequestParam("imageTag") String imageTag) {
    //code
}

but if I have 30 parameters I will have a huge parameter list in the function.

What is the usual and correct way to avoid this?

EDIT: What if I pass the HttpServlet request only?? The request will have all the parameters and I can simple call request.getParameters("").

Upvotes: 3

Views: 101

Answers (4)

Andrew
Andrew

Reputation: 49626

There are two options I would suggest:

  1. Take an HttpServletRequest object and fetch needed properties separately.

The problem is Spring's controllers are designed to eliminate such low-level API (Servlets API) calls. It's could be the right fit if a controller was too abstract (operates on abstract datasets), which means you wouldn't be able to define a DTO with a fixed-length number of parameters.

  1. Construct a DTO class with the properties needed and take it as a parameter.

The advantage is you completely delegate low-level work to Spring and care only about your application logic.

Upvotes: 2

nick318
nick318

Reputation: 575

Correct way is to serialize all parameters as Json and call back end api with one parameter.

On back-end side get that json and parse as objects. Example:

` @RequestMapping(method = POST, path = "/task")
    public Task postTasks(@RequestBody String json,
                          @RequestParam(value = "sessionId", defaultValue = "-1") Long sessionId)
            throws IOException, AuthorizationException {

Task task = objectMapper.readValue(json, Task.class);
`

Upvotes: 0

Marcos Tanaka
Marcos Tanaka

Reputation: 3336

You can do something like this:

@RequestMapping(value = "/save-state", method = RequestMethod.POST)
public void deleteEnvironment(@RequestBody MyData data) {
    //code
}

Create a class containing all your form parameters and receive that on your method.

Upvotes: 1

davidxxx
davidxxx

Reputation: 131396

but if I have 30 parameters I will have a huge parameter list in the function.

In your request, pass a JSON object that contains these information and create its counterpart in Java.

RequestMethod.POST is not design to perform deletion.
Usr rather RequestMethod.DELETE.

@RequestMapping(value = "/save-state", method = RequestMethod.DELETE)
public @ResponseBody
void deleteEnvironment(MyObject myObject) {
    //code
}

Upvotes: 0

Related Questions