ForInfinity ForInfinity - 1 month ago 8
Java Question

Different things returned based on a requested param with Spring?

I wonder if there's a possibility for a method to return different things based on what param was requested. An example:

@RestController
public class GreetingController {

private static final String templateForName = "Hello, %s!";
private static final String templateForTest = "Testing new output, which is %s!";

@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name
,@RequestParam(value="test", defaultValue="TEST value") String test
) {
//An if here that would decide which param was requested?
return new Greeting(String.format(templateForName, name));

}


This here would display, for example, "Hello, User!" if requested with
?name=User

Is it possible to display "Testing new output, which is test!" is requested with
?test=test


I am only just starting doing anything with Spring, so if something is unclear or information provided is insufficient, do let me know and I'll try to explain better.

Answer

You can simply add the if else conditions to return the proper greeting object as below:

@RequestMapping("/greeting")
    public String greeting(@RequestParam(value="name", defaultValue="World") String name
                            ,@RequestParam(value="test", defaultValue="TEST value") String test
                            ) {
         Greeting greeting = null;
        if(name.equals("User")) {
             greeting = new Greeting(String.format(templateForName, name));
        } else if(test.equals("test"))  {
              greeting = new Greeting(String.format(templateForTest, test));
        }
        return greeting;
    }
Comments