@RequestMapping映射请求注解的属性使用方法
Spring MVC 使用 @RequestMapping 注解为控制器指定可以处理哪些 URL 请求, 在控制器的类定义及方法定义处都可标注。
基本使用
1.通过@RequestMapping注解方式实现路径到处理器方法的映射。
2.可以用在类或方法上。
3.用在方法上表示将该方法变为一个处理器,且和指定路径做映射。
4.用在类上则配置的路径会作为这个类中所有处理器的路径的父路径使用。
@RequestMapping 除了可以使用请求 URL 映射请求外,还可以使用请求方法、请求参数及请求头映射请求。
@RequestMapping 的 value、method、params、 headers及consumes和produces 分别表示请求 URL、请求方法、请求参数及请求头的映射条件,请求提交类型和返回值类型。他们之间是与的关系,联合使用多个条件可让请求映射更加精确化。
1.value属性
该属性将当前处理器绑定到哪个访问路径上 ,当url发出"hello"请求时,该方法才会调用。
@RequestMapping(value="hello")
public ModelAndView hello(String test)
{
System.out.println("test:"+test);
System.out.println("hello method");
return null;
}
2.method属性
该属性用来指定请求方式,默认get和post的方式都可以,也可以指定post还是get方式
例子为post请求方式
@RequestMapping(value="hello",
method= {RequestMethod.Post}
)
public ModelAndView hello(String test)
{
System.out.println("test:"+test);
System.out.println("hello method");
return null;
}
3. param属性
该属性用来限制传过来的参数名和值
3.1 例子表示请求中必须包含“name”参数,并且该参数的值必须是“小明”,否则不处理请求
例子表示请求中必须包含“name”参数,并且该参数的值必须是“小明”,否则不处理请求
@RequestMapping(value="hello",
method= {RequestMethod.Post}
param= {"name=小明"}
)
public ModelAndView hello(String test)
{
System.out.println("test:"+test);
System.out.println("hello method");
return null;
}
3.2 例子表示请求中必须包含“name”参数,并且该参数的值不能是“小明”,否则不处理请求
例子表示请求中必须包含“name”参数,并且该参数的值不能是“小明”,否则不处理请求
@RequestMapping(value="hello",
method= {RequestMethod.Post}
param= {"name!=小明"}
)
public ModelAndView hello(String test)
{
System.out.println("test:"+test);
System.out.println("hello method");
return null;
}
3.3 例子表示请求参数里面不能含有name参数,否则不处理请求
例子表示请求参数里面不能含有name参数,否则不处理请求
@RequestMapping(value="hello",
method= {RequestMethod.Post}
param= {"!name"}
)
public ModelAndView hello(String test)
{
System.out.println("test:"+test);
System.out.println("hello method");
return null;
}
4. consumes属性
该属性指定处理请求当中的提交内容类型(Content-Type):application/json, text/html等。
属性consumes="application/json"时,返回json数据
@RequestMapping(value="hello",
method= {RequestMethod.Post}
consumes="application/json"
)
public ModelAndView hello(String test)
{
System.out.println("test:"+test);
System.out.println("hello method");
return null;
}
5. produces属性
指定返回值类型,并且可以设置返回值类型和返回值的字符编码;
@RequestMapping(value="hello",
method= {RequestMethod.Post}
produces="application/json"
)
public ModelAndView hello(String test)
{
System.out.println("test:"+test);
System.out.println("hello method");
return null;
}
/***************************************************************************************************/
属性produces="MediaType.APPLICATION_JSON_VALUE;charset=utf-8"时,设置返回数据的字符编码为utf-8
@RequestMapping(value="hello",
method= {RequestMethod.Post}
produces="MediaType.APPLICATION_JSON_VALUE;charset=utf-8"
)
public ModelAndView hello(String test)
{
System.out.println("test:"+test);
System.out.println("hello method");
return null;
}