我在使用模型属性将用户输入的数据从 jsp 传递到 Controller 时遇到问题。该错误返回空指针异常,我不知道为什么会抛出此错误。该代码假设允许用户使用文本框输入数据,然后将输入的代码保存到数据库之前的存储库中。但是,代码返回空指针异常,我不知道为什么会抛出此错误。
我的jsp代码:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add Paper</title>
</head>
<body>
<form:form
action="/addResearchPapers" modelAttribute="Document">
<p>Author: </p>
<input type ="text" name="author" /> <br>
<p>Title: </p>
<input type ="text" name="title" /> <br>
<p>Short Title: </p>
<input type ="text" name="shortTitle" /> <br>
<p>CPL: </p>
<input type ="text" name="CPL" /> <br>
<p>RBMA: </p>
<input type ="text" name="RBMA" /> <br>
<p>Editor: </p>
<input type ="text" name="editor" /> <br>
<p>Other Reps: </p>
<input type ="text" name="otherReps" /> <br>
<p>Item Type: </p>
<input type ="text" name="itemType" /> <br>
<p>Location: </p>
<input type ="text" name="location" /> <br>
<p>Language: </p>
<input type ="text" name="language" /> <br>
<p>Genre: </p>
<input type ="text" name="genre" />
<br><br>
<input type= "submit" value="Save Paper To Database" />
</form:form>
</body>
</html>
我的 Controller 代码:
@PostMapping("/addResearchPapers")
public String newResearchPaper(@ModelAttribute("Document") ResearchPaper Document, BindingResult result, ModelMap model) {
model.addAttribute("Author", Document.getauthor());
model.addAttribute("Title", Document.getTitle());
model.addAttribute("Short Title", Document.getshortTitle());
model.addAttribute("CPL", Document.getCPL());
model.addAttribute("RBMA",Document.getRBMA());
model.addAttribute("Editor", Document.geteditor());
model.addAttribute("Other Reps", Document.getotherReps());
model.addAttribute("Item Type", Document.getitemType());
model.addAttribute("Location", Document.getlocation());
model.addAttribute("Genre", Document.getgenre());
RPrepo.save(model);
return "homepage";
}
最佳答案
由于 Spring 已在图片中,因此您必须提供 Bean 的所有属性的路径,否则它将抛出空指针,因为它不知道您发送的内容和位置。因此,为了克服它,请替换您的
<input type ="text" name="author" />
这样:
<form:input type ="text" path="author" name="author" />
and so on...
这里的“path”是您的 ResearchPaper Bean 中的字段名称。希望可以帮助你。
关于java - 将模型属性从 jsp 传递到 Spring Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60600723/