@PathVariable绑定URI模板变量值
@PathVariable用于将请求URL中的模板变量映射到功能处理方法的参数上。
@RequestMapping(value="/users/{userId}/topics/{topicId}")
public String test(
@PathVariable(value="userId") int userId,
@PathVariable(value="topicId") int topicId)
如请求的URL为“控制器URL/users/123/topics/456”,则自动将URL中模板变量{userId}和{topicId}绑定到通过@PathVariable注解的同名参数上,即入参后userId=123、topicId=456。
代码在PathVariableTypeController中。
@RequestParam(参数绑定到控制器)和@PathVariable(参数绑定到url模板变量)
spring mvc:练习 @RequestParam和@PathVariable
@RequestParam
: 注解将请求参数绑定到你的控制器方法参数@PathVariable
: 注释将一个方法参数绑定到一个URI模板变量的值
@RequestParam: 注解将请求参数绑定到你的控制器方法参数
@RequestMapping(value="/example/user")
public String UserInfo(Model model, @RequestParam(value="name", defaultValue="Guest") String name)
实例:
package springmvc;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class RequestParamExampleController {
@RequestMapping(value="/example/user")
public String UserInfo(Model model,
@RequestParam(value="name", defaultValue="Guest") String name)
{
model.addAttribute("name", name);
if("admin".equals(name))
{
model.addAttribute("email", "admin@google.com");
}else {
model.addAttribute("email", "not set");
}
return "example_user";
}
}
@PathVariable: 注释将一个方法参数绑定到一个URI模板变量的值
@RequestMapping(value="/example/info/{language}/{id}/{name}")
public String userInfo2(Model model,
@PathVariable(value="language") String language,
@PathVariable(value="id") Long id,
@PathVariable(value="name") String name)
实例:
package springmvc;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.PathVariable;
@Controller
public class RequestParamExampleController {
@RequestMapping(value="/example/person/{name}/{age}")
public String userPerson(Model model,
@PathVariable(value="name") String name,
@PathVariable(value="age") Long age)
{
model.addAttribute("name", name);
model.addAttribute("age", age);
String desc = "";
if(age > 20)
{
desc = "oldman";
}else {
desc = "yongman";
}
model.addAttribute("desc", desc);
return "example_person";
}
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。