@RestController / @RequestMapping

@Controller 处理http请求

@Controller
//@ResponseBody
public class HelloController {

    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(){
        return "hello";
    }
}

 

如果直接使用@Controller这个注解,当运行该SpringBoot项目后,在浏览器中输入:local:8080/hello,会得到如下错误提示,

出现这种情况的原因在于:没有使用模版。

 

@RestController

Spring4之后新加入的注解,原来返回json需要@ResponseBody和@Controller配合。

即@RestController是@ResponseBody和@Controller的组合注解。

 

@RestController
public class HelloController {

    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(){
        return "hello";
    }
}

与下面的代码作用一样

@Controller
@ResponseBody
public class HelloController {

    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(){
        return "hello";
    }
}

 

@RequestMapping 配置url映射

@RequestMapping此注解即可以作用在控制器的某个方法上,也可以作用在此控制器类上。

例子一:@RequestMapping仅作用在处理器方法上

@RestController
public class HelloController {

    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(){
        return "hello";
    }
}

以上代码sayHello所响应的url=localhost:8080/hello。

 

例子二:@RequestMapping仅作用在类级别上


@Controller
@RequestMapping("/hello")
public class HelloController {

    @RequestMapping(method= RequestMethod.GET)
    public String sayHello(){
        return "hello";
    }
}

以上代码sayHello所响应的url=localhost:8080/hello,效果与例子一一样,没有改变任何功能

 

例子三:@RequestMapping作用在类级别和处理器方法上

@RestController
@RequestMapping("/hello")
public class HelloController {

    @RequestMapping(value="/sayHello",method= RequestMethod.GET)
    public String sayHello(){
        return "hello";
    }
    @RequestMapping(value="/sayHi",method= RequestMethod.GET)
    public String sayHi(){
        return "hi";
    }
}

这样,以上代码中的sayHello所响应的url=localhost:8080/hello/sayHello。

sayHi所响应的url=localhost:8080/hello/sayHi。

posted @ 2022-03-21 15:19  Jasper2003  阅读(116)  评论(0编辑  收藏  举报