Java 新手如何使用Spring MVC 中的查询字符串和查询参数
warning:
这篇文章距离上次修改已过442天,其中的内容可能已经有所变动。
在Spring MVC中,你可以通过@RequestParam注解来获取查询字符串或查询参数。以下是一个简单的例子:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@GetMapping("/greet")
@ResponseBody
public String greet(@RequestParam(name = "name", required = false, defaultValue = "World") String name) {
return "Hello, " + name + "!";
}
}在这个例子中,当你访问/greet路径,并带上查询参数name,例如/greet?name=John,greet方法会接收到name的值,并返回一个问候字符串。如果没有提供name查询参数,它会使用默认值World。
确保你的Spring MVC配置正确,并且有一个DispatcherServlet来处理请求映射。
评论已关闭