简体   繁体   English

根据Spring请求的参数返回了不同的东西?

[英]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!" 如果使用?name=User请求,是否可以显示“正在测试新输出,这是测试!” is requested with ?test=test ?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. 我只是开始使用Spring做任何事情,因此如果不清楚或提供的信息不足,请告诉我,我将尽力进行解释。

You can simply add the if else conditions to return the proper greeting object as below: 您只需添加if else conditions即可返回正确的问候对象,如下所示:

@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;
    }

Per my comment, using PATH params: 根据我的评论,使用PATH参数:

@RequestMapping("/greeting/name/{name}")
public Greeting nameGreeting(@PathParam(value="name", defaultValue="World") String name) {

    return new Greeting(String.format(templateForName, name));

}

@RequestMapping("/greeting/test/{test}")
public Greeting testGreeting(@PathParam(value="test", defaultValue="TEST value") String name) {

    return new Greeting(String.format(templateForTest, test));

}

Just use one @RequestParam and test for the value you're looking for. 只需使用一个@RequestParam并测试所需的值即可。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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