spring boot 处理请求的方式 Controller 与RestController

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

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

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

/**

 * Hello world!

 */

//其中@SpringBootApplication申明让spring boot自动给程序进行必要的配置,等价于以默认属性使用@Configuration,@EnableAutoConfiguration和@ComponentScan

@SpringBootApplication

publicclassApp {

              publicstatic void main(String[] args) {

                 SpringApplication.run(App.class, args);

       }

}

请求数据:


import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

 

@RestController// 标记为:restful

public class HelloController {
   

    @RequestMapping(value={"/",""},method={RequestMethod.POST,RequestMethod.GET},produces = "application/json; charset=UTF-8")

    public String hello(){

       return"Hello world!";

    }

}
返回数据:
Hello world!

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


请求包含数据的视图:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/demo")
public class DemoController {
	@RequestMapping("/getDemo")
	public String getDemo() {
        Map map=new HashMap();
        map.put("key","value");
         return "demo";
	}
}

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

下一章讲用户配置的几种模板支持。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大巨魔战将

如果对您有帮助,请打赏1分钱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值