当@RestController存在时,@ Controller不起作用

时间:2016-11-28 10:00:50

标签: java spring spring-mvc

由于某种原因,我的项目必须同时使用@Controller和@RestController,并且@RestController具有api前缀。但是当我访问属于@Controller的url时,它返回404页面和没有api前缀的根页面返回: root page @RestController和@Controller能够站在一起吗?

Controller.java

 @Controller
public class HomeController {

  private final CourseRepository courseRepository;

  @Autowired
  public HomeController(CourseRepository courseRepository) {
    this.courseRepository = courseRepository;
  }

  @RequestMapping("/")
  public String home(Model model) {
    model.addAttribute("courses", courseRepository.findAll());
    return "home";
  }

  @RequestMapping("/hello")
  public String hello() {
    return "hello";
  }

  @RequestMapping("/login")
  public String login() {
    return "login";
  }

  @RequestMapping("/403")
  public String error() {
    return "403";
  }
}

RestController.java

@org.springframework.web.bind.annotation.RestController
@RequestMapping("/api")
public class RestController {

  private final UserRolesRepository userRolesRepository;
  private final CourseRepository courseRepository;

  @Autowired
  public RestController(UserRolesRepository userRolesRepository, CourseRepository courseRepository) {
    this.userRolesRepository = userRolesRepository;
    this.courseRepository = courseRepository;
  }

  @RequestMapping("/courses")
  List<Course> readCourses() {
    return courseRepository.findAll();
  }
}

0 个答案:

没有答案