SpringBoot-URL路由:@Controller和@RequestMapping

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")
    @ResponseBody
    public String hello(){
        return "fpc";
    }
}

HelloworldRestController类被@Controller标注,其中的两个方法都被@RequestMapping标注,当应用程序运行后,在浏览器中访问:localhost:8089,请求会被SpringMVC框架分发到hellworld()方法进行处理。同理输入localhost:8089/hello会交给hello()方法处理。

@ResponseBody标注表示处理函数直接将函数的返回值传到浏览器端显示。

运行结果:

输入localhost:8089:

技术分享

输入loalhost:8089/hello:

技术分享

@RequestMapping标注类

@RequestMapping标注同样可以加在类上:

@RestController
@RequestMapping("/index")
public class HelloworldRestController {
    @RequestMapping("/")
    public String helloworld(){
        return "hello world";
    }
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        return "fpc";
    }
}

hello()方法绑定的URL路径是/index/hello

运行结果:
如果直接访问:localhost:8089/hello:

技术分享

如果访问:localhost:8089/index/hello:

技术分享

提示:每一个类都可以包含一个或者多个@RequestMapping标注的方法,通常我们会将业务逻辑相近的URL放在同一个Controller中处理。

文章来自:http://www.cnblogs.com/fangpengchengbupter/p/7822398.html
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3