SpringBoot @RestController详解

了解@RestController我们可以先来了解一下其他几个注解

@Controller

@Controller是Spring框架提供的注解,通过它标识的类,代表控制器类(控制层/表现层)。这里控制层里面的每个方法,都可以去调用@Service标识的类(业务逻辑层),而@Service标识的类中的方法可以继续调用@Resposity标识的接口实现类(Dao层/持久层)。

@Controller用于标记在一个类上,使用它标记的类就是一个SpringMVC的Controller类,分发处理器会扫描使用该注解的类的方法,并检测该方法是否使用了@RequestMapping注解。@Controller只是定义了一个控制器类,而使用@RequestMapping注解的方法才是处理请求的处理器。@RequestMapping给出外界访问方法的路径,或者说触发路径,触发条件。

用@ResponseBody标记Controller类中的方法。把return的结果变成JSON对象返回。如果没有这个注解,这个方法只能返回要跳转的路径,即跳转的页面。有这个注解,可以不跳转页面,只返回JSON数据。

@RestController

@RestController是Spring4.0之后新增的注解。相当于@Controller+@ResponseBody合在一起的作用。

Controller类中的方法返回值,默认是JSON对象,也就是相当于@Controller里面的方法上添加了@ResponseBody,如果方法返回值,需要跳转,那么方法的返回类型必须是View或者ModelAndView。

import com.example.studentsys.entiy.User;
import com.example.studentsys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/login")
    public String login(User user){
        return userService.login(user);
    }

    @PostMapping("/regist")
    public String regist(User user){
        return userService.regist(user);
    }

    /**
     * 解决查询数据库中文出现乱码问题
     * @return
     */
    @RequestMapping(value = "/alluser", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<User> findAll(){
        return userService.findAll();
    }
}

猜你喜欢

转载自blog.csdn.net/li_w_ch/article/details/108937337
今日推荐