美文网首页
spring boot之@RestController和@Con

spring boot之@RestController和@Con

作者: 山巅自相见 | 来源:发表于2022-07-01 17:08 被阅读0次

@Controller

该注解用于类上,代表该类是控制器类,常叫控制层或表现层。带有该注解的类可以调用@Service的实现类

@Controller
public class CustomerController {
    @Resource
    CustomerServiceI customerServiceI;
    @PostMapping("/")
    public String index() {
        return "list";
    }
}

以上代码可以实现跳转到list.jsp页面。

@RestController

该注解用法和@Controller用法一样,区别是该注解相当于@Controller+@ResponseBody(这个注解下面会讲到)。
注解源码:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Controller;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    @AliasFor(
        annotation = Controller.class
    )
    String value() default "";
}

在源码中可以看到这个接口上有@Controller@ResponseBody,所以用这一个注解可以代替两个注解。

@ResponseBody

该注解用于方法上,表示该方法的返回值是json格式的数据。一般只用于Controller层的方法

@Controller
public class CustomerController {
    @Resource
    CustomerService customerService;

    @PostMapping("/list")
    @ResponseBody
    public String index() {
        return customerService.queryCustomerAll();
    }
}

上述代码表示"/list"方法会返回customerService.queryCustomerAll()方法的返回值,是一个集合。

@RequestBody

该方法用于接口的参数前,用来接收json格式的参数。

@Controller
public class CustomerController {
    @Resource
    CustomerService customerService;

    @PostMapping("/list")
    @ResponseBody
    public String index(@RequestBody CidQO cidQO) {
        return customerService.queryCustomerByCid(cidQO.getCid());
    }
}

相关文章

网友评论

      本文标题:spring boot之@RestController和@Con

      本文链接:https://www.haomeiwen.com/subject/rlbcbrtx.html