springboot的restcontroller

spring boot 基于spring MVC的基础上进行了改进, 将@Controller 与@ResponseBody 进行了合并成一个新的注解 @RestController。

当用户请求时,需要有视图渲染的,与请求数据的请求分别使用@Controller与@RestController 。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import org.springframework.boot.SpringApplication;  
  2.   
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  4.   
  5. /** 
  6.  
  7.  * Hello world! 
  8.  
  9.  */  
  10.   
  11. //其中@SpringBootApplication申明让spring boot自动给程序进行必要的配置,等价于以默认属性使用@Configuration,@EnableAutoConfiguration和@ComponentScan  
  12.   
  13. @SpringBootApplication  
  14.   
  15. publicclassApp {  
  16.   
  17.               publicstatic void main(String[] args) {  
  18.   
  19.                  SpringApplication.run(App.class, args);  
  20.   
  21.        }  
  22.   
  23. }  

请求数据:


[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import org.springframework.web.bind.annotation.RequestMapping;  
  2.   
  3. import org.springframework.web.bind.annotation.RestController;  
  4.   
  5.    
  6.   
  7. @RestController// 标记为:restful  
  8.   
  9. public class HelloController {  
  10.      
  11.   
  12.     @RequestMapping(value={"/",""},method={RequestMethod.POST,RequestMethod.GET},produces = "application/json; charset=UTF-8")  
  13.   
  14.     public String hello(){  
  15.   
  16.        return"Hello world!";  
  17.   
  18.     }  
  19.   
  20. }  
返回数据:
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. Hello world!  

如果返回类型的是一个 Class, value 是请求的映射集合, method是请求格式的集合,produces 是返回数据格式。


请求包含数据的视图:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import org.springframework.stereotype.Controller;  
  2. import org.springframework.web.bind.annotation.RequestMapping;  
  3.   
  4. @Controller  
  5. @RequestMapping("/demo")  
  6. public class DemoController {  
  7.     @RequestMapping("/getDemo")  
  8.     public String getDemo() {  
  9.         Map map=new HashMap();  
  10.         map.put("key","value");  
  11.          return "demo";  
  12.     }  
  13. }  

页面会跳转到 对应的 demo.html 或者 demo.jsp 页面。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值