Building Spring MVC application, Controller "Cannot find symbol" Model

14,272

I figured out the problem.

If we want the DispatcherServlet to inject the Model into the function, one of the things we should do is import the Model class.

import org.springframework.ui.Model;

So, I changed my controller class to the following and it worked!

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";
  }
}
Share:
14,272
KZcoding
Author by

KZcoding

Updated on June 05, 2022

Comments

  • KZcoding
    KZcoding almost 2 years

    I first built my Spring MVC project with gradle bootRun with the following controller class successfully:

    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";
      }
    }
    

    Then I changed it to pass data to my view class:

    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";
      }
    }
    

    When I build my project now, I get the following error:

    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.
    

    Any ideas what I'm doing wrong?

  • sanluck
    sanluck about 8 years
    Why the author must use it? It fixes the problem?