何为JavaSpringBoot Controller?

一、请求及路径映射部分注解介绍

 

注解名称

描述
@Controller处理http请求
@RestControllerSpring4之后新加的注解,原来返回json,需要@ResponseBody配合@Controller
@RequestMapping配置url映射

 

1、@Controller的使用(了解)

相当于serverlet的jsp,前后端不分离的开发,就模板而言很好性能,所以提倡前后端分离式的开发,

 

2、@RestController的使用

@RestController在实际开发中应用广泛,与@controller相比,不依赖于模板,前后端分离式的开发,开发效率也很高。

3、@RequestMapping的使用

该注解既可以在类上方使用,又可以方法上使用,在类上方使用,如在该处添加,接口访问时采取路径拼接方式访问,如:localhost:8888/spring/hellow

 

package com.rongrong.springboot.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author rongrong
 * @version 1.0
 * @description:
 * @date 2019/12/26 20:34
 */
@RestController
/**
 * 在类上方使用,如在该处添加,接口访问时采取路径拼接方式访问
 * 如:localhost:8888/spring/hellow
 */
@RequestMapping("/spring")
public class HellowController {


    @Autowired
    Person person;
    //在方法 上方使用
    @RequestMapping(value = "/hellow",method = RequestMethod.GET)
    public String say(){
        return person.getGName();
    }

}

二、请求参数及组合注解介绍

注解名称描述
@PathVariable获取url中的数据
@RequestParam 获取请求参数的值
@GetMapping组合注解

 

 

 

1、@PathVariable的使用

一般在restful风格接口使用居多,形式为:/路径/{变量}

    //Restful风格接口
    @RequestMapping(value = "/getID/{id}", method = RequestMethod.GET)
    public String getID(@PathVariable("id") Integer id) {
        return "Id:"+id;
    }

 2、@RequestParam使用

 为传统风格形式使用,

 

 3、组合注解及多个路径可以访问同一个接口

@GetMapping可以理解为@RequestMapping

 /**
     * 组合注解及多个路径可以访问同一个接口
     * @param id
     * @return
     */
    @GetMapping({"/getUserId","/sayhi"})
    //@RequestMapping(value = "/getMyId", method = RequestMethod.GET)
    public String getUserId(@RequestParam(value = "id",required = false,defaultValue = "0") Integer id) {
        return "getMyId: \t"+id;
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Roam-G

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值