码迷,mamicode.com
首页 > 移动开发 > 详细

SpringBoot-URL路由:@Controller和@RequestMapping

时间:2017-11-12 19:19:08      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:分享   函数   http请求   ppi   img   code   es2017   应用程序   tco   

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中处理。

SpringBoot-URL路由:@Controller和@RequestMapping

标签:分享   函数   http请求   ppi   img   code   es2017   应用程序   tco   

原文地址:http://www.cnblogs.com/fangpengchengbupter/p/7822398.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!