我首先用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.
知道我做错了什么吗?
我想出了问题所在。
如果我们希望 DispatcherServlet 将模型注入到函数中,我们应该做的一件事就是导入 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";
}
}
您可以使用 ModelAndView API:
@RequestMapping("/")
public ModelAndView hello() {
ModelAndView modelAndView = new ModelAndView("resultPage");
modelAndView.addObject("message", "Hello from the controller");
return modelAndView;
}
模型和查看文档:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/ModelAndView.html