1.@RequestMapping
@RequestMapping 是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径;用于方法上,表示在类的父路径下追加方法上注解中的地址将会访问到该方法,此处需注意@RequestMapping用在类上可以没用,但是用在方法上必须有。
RequestMapping注解有六个属性,下面我们把她分成三类进行说明。
value: 指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);
method: 指定请求的method类型, GET、POST、PUT、DELETE等;
consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
params: 指定request中必须包含某些参数值是,才让该方法处理。
headers: 指定request中必须包含某些指定的header值,才能让该方法处理请
/**
* 分页查询
*/
@RequestMapping(value = "/messageList", method = { RequestMethod.GET })
public Map messageList(HttpServletRequest request) {
int offset = Integer.valueOf(request.getParameter("page"));
int pageSize = Integer.valueOf(request.getParameter("limit"));
MessageBoard entity = new MessageBoard();
List<MessageBoard> MessageList = messageService.getMessageList(entity,((offset-1)*pageSize),pageSize);
Map List = new HashMap();
List.put("code", "0");
List.put("count",messageService.getCount(entity));
List.put("data", MessageList);
List.put("msg", "");
return List;
}
@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
// implementation omitted
}
}
方法仅处理request Content-Type为“application/json”类型的请求:
@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {
// implementation omitted
}
@ResponseBody
@Responsebody 注解表示该方法的返回的结果直接写入到response对象的body区,一般在异步获取数据时使用,通常用来返回JSON数据或者是XML
作用:
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区
返回的数据不是html标签的页面,而是其他某种格式的数据时使用;
/**
* 保存
*/
@SuppressWarnings("unlikely-arg-type")
@RequestMapping(value = "/save", method = { RequestMethod.POST })
public @ResponseBody boolean save( MessageBoard messageboard) {
ModelAndView view = new ModelAndView();
try {
messageService.save(messageboard);
} catch (Exception e) {
System.out.println(e);
}
return true;
}
@RequestBody
@RequestBody 注解则是将 HTTP 请求正文插入方法中,使用适合的 HttpMessageConverter 将请求体写入某个对象。
它接收的是一个Json对象的字符串,而不是一个Json对象。ajax请求的时候也要指定dataType: "json",contentType:"application/json" 这样就可以将一个对象传到Java端,使用@RequestBody即可绑定对象或者List.
$.ajax({
url:"/login",
type:"POST",
data:'{"userName":"admin","pwd","admin123"}',
content-type:"application/json charset=utf-8",
success:function(data){
alert("request success ! ");
}
});