@RequestParam注解@RequestParam注解比较简单,它用于将请求参数区数据映射到功能处理方法的参数上,自SpringMVC4.2之后,@RequestParam注解内部有4个参数: String name String value boolean required String defaultValue 1.name与value属性,其中name和value分别是URL参数的名称,即二者没区别,我个人比较喜欢用name,因为在HTML的表单中我们都是用name属性来设置URL参数名称的,所以在注解上也使用name这个属性的话,会更直观一些。示例: package org.zero01.test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/test")
public class Test {
@RequestMapping("test.do")
public void test(@RequestParam(name = "username") String name) {
System.out.println(name);
}
@RequestMapping("user.do")
public void userAndAlias(@RequestParam(name = "username")String user, @RequestParam(name = "alias")String a) {
System.out.println(user);
System.out.println(a);
}
}
2.required属性,该属性用于指定某个参数是否是必须的,默认值为true,表示请求中一定要有相应的参数,否则将报404错误码,示例: package org.zero01.test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/test")
public class Test {
@RequestMapping("test.do")
public void test(@RequestParam(name = "username", required = true) String name) {
System.out.println(name);
}
@RequestMapping("user.do")
public void userAndAlias(@RequestParam(name = "username", required = false) String user, @RequestParam(name = "alias", required = false) String a) {
System.out.println(user);
System.out.println(a);
}
}
3.defaultValue属性,该属性用于指定参数的默认值,表示如果请求中没有同名参数时的默认值,默认值可以是SpEL表达式,如“#{systemProperties[‘java.vm.version’]}”。示例: package org.zero01.test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/test")
public class Test {
@RequestMapping("test.do")
public void test(@RequestParam(name = "username", defaultValue = "nothing") String name) {
System.out.println(name);
}
@RequestMapping("user.do")
public void userAndAlias(@RequestParam(name = "username", defaultValue = "nothing") String user, @RequestParam(name = "alias", defaultValue = "nothing") String a) {
System.out.println(user);
System.out.println(a);
}
}
|