SpringBoot定义URL处理方法:@Controller和@RequestMapping
@Controller标注的类表示的是一个处理HTTP请求的控制器(即MVC中的C),该类中所有被@RequestMapping标注的方法都会用来处理对应URL的请求。
在SpringMVC框架中,使用@RequsetMapping标注可以将URL与处理方法绑定起来,例如:
@RestController
public class HelloworldRestController {
@RequestMapping("/")
public String helloworld(){
return "hello world";
}
@RequestMapping("/hello")
public String hello(){
return "fpc";
}
}
HelloworldRestController类被@Controller标注,其中的两个方法都被@RequestMapping标注,当应用程序运行后,在浏览器中访问:localhost:8089,请求会被SpringMVC框架分发到hellworld()方法进行处理。同理输入localhost:8089/hello会交给hello()方法处理。
@ResponseBody标注表示处理函数直接将函数的返回值传到浏览器端显示。
@RequestMapping标注类
@RequestMapping标注同样可以加在类上:
@RestController
@RequestMapping("/index")
public class HelloworldRestController {
@RequestMapping("/")
public String helloworld(){
return "hello world";
}
@RequestMapping("/hello")
public String hello(){
return "fpc";
}
}
提示:每一个类都可以包含一个或者多个@RequestMapping标注的方法,通常我们会将业务逻辑相近的URL放在同一个Controller中处理。