构建Spring MVC应用程序,Controller"找不到符号"模型

时间:2016-04-26 00:12:09

标签: spring spring-mvc model-view-controller spring-boot thymeleaf

我首先使用gradle bootRun成功构建了我的Spring MVC项目,并成功完成了以下控制器类:

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

@Controller
public class HelloController {

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

然后我更改了它以将数据传递给我的视图类:

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

@Controller
public class HelloController {

  @RequestMapping("/")
  public String hello(Model model) {
    model.addAttribute("message", "Hello from the controller");
    return "resultPage";
  }
}

当我现在构建我的项目时,我收到以下错误:

HelloController.java:13: error: cannot find symbol
    public String hello(Model model) {
                        ^
  symbol:   class Model
  location: class HelloController
1 error
:compileJava FAILED

FAILURE: Build failed with an exception.

任何想法我做错了什么?

2 个答案:

答案 0 :(得分:4)

我发现了问题。

如果我们希望DispatcherServlet将Model注入函数中,我们应该做的一件事是导入Model类。

import org.springframework.ui.Model;

所以,我将我的控制器类更改为以下内容并且它有效!

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;

@Controller
public class HelloController {

  @RequestMapping("/")
  public String hello(Model model) {
    model.addAttribute("message", "Hello from the controller");
    return "resultPage";
  }
}

答案 1 :(得分:0)

您可以使用ModelAndView API:

@RequestMapping("/")
public ModelAndView hello() {
    ModelAndView modelAndView = new ModelAndView("resultPage");
    modelAndView.addObject("message", "Hello from the controller");
    return modelAndView;
}

ModelAndView docs:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/ModelAndView.html