Error: java.lang.NoSuchMethodException: java.lang.Long.<init>() in spring MVC

The @ModelAttribute("studentId") Long studentId is the source of the problem, because spring doesn't find a method that can provide this Long object, so it tries to instantiate one and pass it as a method argument. To solve this problem you can either :

  • Delete @ModelAttribue from the method argument

    @RequestMapping(value = "/read.html")
    public String readStudent(Model model,Long studentId) {
        Student student = null;
        studentId = 2l;
        try {
            student = serviceFile.readStudent(studentId);
        } catch(Exception e){
            model.addAttribute("message", "Some thing went wrong !!!! Exception occured");
            return "message";
        }
        model.addAttribute("student", student);
        return "read";
    }
    
  • Create a method that will provide that Long Object in your controlle

    @ModelAttribute
    public void provideStudentId(Model model){
        model.addAttribute("studentId", new Long(1));
    }
    

Official Doc

@RequestMapping(path = "/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@ModelAttribute Pet pet) { }

Given the above example where can the Pet instance come from? There are several options:

  1. It may already be in the model due to use of @SessionAttributes — see the section called “Using @SessionAttributes to store model attributes in the HTTP session between requests”.
  2. It may already be in the model due to an @ModelAttribute method in the same controller — as explained in the previous section.
  3. It may be retrieved based on a URI template variable and type converter (explained in more detail below).
  4. It may be instantiated using its default constructor.

EDIT
If the studentId was the parameter name sent from the UI you can use @RequestParam like this

@RequestMapping(value = "/read.html")
public String readStudent(Model model, @RequestParam("studentId") Long studentId) {
    Student student = null;
    studentId = 2l;
    try {
        student = serviceFile.readStudent(studentId);
    } catch(Exception e) {
        model.addAttribute("message", "Some thing went wrong !!!! Exception occoured");
        return "message";
    }   
    model.addAttribute("student", student);
    return "read";
}