使用spring boot将jsp表单插入数据库

时间:2017-08-05 16:27:49

标签: spring jsp spring-mvc spring-boot

我是春季启动的初学者我开始创建一个将数据发送到数据库的联系表单。这是形式:

<form:form method="POST" id="contactform" modelAttribute="message">
            <div class="form">
                <div class="six columns noleftmargin">
                <label name="name">Name</label>
                <form:input path="name" type="text"  class="smoothborder" placeholder="Your name *"/>
                </div>
                <div class="six columns">
                <label name="email">E-mail address</label>
                <form:input path="email" type="text"  class="smoothborder" placeholder="Your e-mail address *"/>
                </div>
                <label name="comment">Message</label>
                <form:textarea path="comment" class="smoothborder ctextarea" rows="14" placeholder="Message, feedback, comments *"></form:textarea>
                <input type="submit" id="submit" class="readmore" value="Submit"/>
            </div>
            </form:form>

这是我的控制器:

 @Autowired
  private MessageRepository messageRepository ;

  @RequestMapping(value= "/newmessage", method = RequestMethod.GET)
  public String newMessage(ModelMap model) {
     Message message = new Message();
     model.addAttribute("message", message);
      return  ("/contact");
    }

  @RequestMapping(value="/newmessage",method=RequestMethod.POST)
  public String saveMessage( Message message, BindingResult result, ModelMap model)
  {

      if (result.hasErrors()) {
            return "/contact";
        }

      messageRepository.save(message);
      model.addAttribute("success", "Message " + message.getName() + " "+ message.getEmail() + " "+ message.getComment()+ " registered successfully");
        //return "success";
        return "/homepage";

文件夹结构

Folder Structure

1 个答案:

答案 0 :(得分:0)

您需要设置表单的操作。如果您想在提交表单时点击/newmessage,则需要更改如下:

<form:form method="POST" id="contactform" action="/newmessage" modelAttribute="message">
     <!-- The elements of the form -->
</form:form>

此外,您需要将modelAttribute添加到控制器方法中。而且您应该只返回jsp页面的名称。如果您的网页名称为homepage.jsp,那么您只应从控制器方法返回homepage。当然,homepage.jsp文件必须位于WEB-INF文件夹中。

@RequestMapping(value="/newmessage",method=RequestMethod.POST)
public String saveMessage(@ModelAttribute("message") Message message, BindingResult result, ModelMap model) {
    // Rest of the code

    return "homepage";
}