【问题标题】:Passing a model attribute from a jsp to controller Spring将模型属性从 jsp 传递到控制器 Spring
【发布时间】:2020-03-09 12:36:49
【问题描述】:

我在使用模型属性将用户输入的数据从 jsp 传递到控制器时遇到问题。该错误返回一个空指针异常,我不知道它为什么会抛出这个错误。该代码假设允许用户使用文本框输入数据,然后将输入的代码保存到数据库之前的存储库中。但是,代码返回一个空指针异常,我不知道它为什么会抛出这个错误。

我的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>

我的控制器代码:

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

【问题讨论】:

  • 您在哪一行得到异常?
  • 当我将作者添加到控制器中的模型时,它不会从 jsp 中传递任何内容。

标签: java spring jsp


【解决方案1】:

由于 Spring 在图片中,您必须为您的 bean 提供所有属性的路径,否则它将抛出空指针,因为它不知道您正在发送什么以及在哪里发送。所以为了克服它,更换你的

<input type ="text" name="author" />

用这个:

<form:input type ="text" path="author" name="author" />
and so on...

这里的“路径”是您在 ResearchPaper Bean 中的字段名称。希望它对你有帮助。

【讨论】:

  • 谢谢。但是,它现在既不返回 BindingResult 也不返回可用作请求属性的 bean 名称“文档”的普通目标对象。你知道如何解决这个问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
  • 2011-11-17
  • 2012-12-08
  • 1970-01-01
  • 1970-01-01
  • 2011-06-23
  • 2019-12-07
相关资源
最近更新 更多