@RequestMapping 是 Spring Web 应用程序中最常被用到的注解之一。这个注解会将 HTTP 请求映射到 MVC 和 REST 控制器的处理方法上。可以修饰类,也可以修饰方法
类定义处:提供初步的请求映射信息,相当于,WEB应用的根目录
方法定义处,提供进一步的细分的映射信息
如果没有定义类定义处标注@RequestMapping,那么方法处定义的URL就相当于WEB应用的根目录
@Controller
@RequestMapping("/springmvc")
public class DemoController {
@Autowired
private McDOMapper mapper;
/**
* 返回一个json字符串
*/
@RequestMapping("index")
@ResponseBody
public Object index(@RequestParam(name = "id") int id) {
return mapper.selectByPrimaryKey(id);
}
}
类定义处定义了,请求的地址为ip/springmvc/index
只有方法处定义了,请求的地址为ip/index
@Controller
@RequestMapping("/springmvc")
public class DemoController {
@Autowired
private McDOMapper mapper;
/**
* 返回一个json字符串
*/
@RequestMapping("index")
@ResponseBody
public Object index(@RequestParam(name = "id") int id) {
return mapper.selectByPrimaryKey(id);
}
}
@RequestParam 注解配合 @RequestMapping 一起使用,可以将请求的参数同处理方法的参数绑定在一起,请求时需要带上指定的param
@Controller:Controller控制器是通过服务接口定义的提供访问应用程序的一种行为,它解释用户的输入,将其转换成一个模型然后呈献给用户。可以返回页面。
@RequestBody:是指方法参数应该被绑定到HTTP请求Body上。
@ResponseBody:与@RequestBody类似,它的作用是将返回类型直接输入到HTTP response body中。给controller方法加上@ResponseBody后,返回任意一个对象,总能被自动转换成对应的Json数据
@RestController:Spring 4 新加入的注解,作用类似于@RestController和@ResponseBody组合,会直接返回json
@Controller
@RequestMapping("/")
public class DemoController {
@Autowired
private McDOMapper mapper;
/**
* 返回一个json字符串
*/
@RequestMapping("index")
@ResponseBody
public Object index(@RequestParam(name = "id") int id) {
return mapper.selectByPrimaryKey(id);
}
/**
* 返回一个SUCCESS
*/
@ResponseBody
@RequestMapping(value = "/hello/success")
public String helloSuccess() {
return "SUCCESS";
}
/**
* 返回resource下的page.html页面
*/
@RequestMapping(value = "/hello/page")
public String helloPage() {
return "page";
}
}