首页 > 解决方案 > 将数据从 Soring 启动应用程序添加到 Mondo DB

问题描述

我正在构建我的第一个 Spring 应用程序,现在,我想将配方对象保存在我的 Mongo 数据库中。我将 .jsp 文件用于“前端”部分。

我的问题是该对象保存在数据库中但具有空值。

我在这里想念什么?

应用控制器:

package era;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Controller
public class AppController {

    @Autowired
    private RecipeRepo repo;

    @RequestMapping("/")
    public String home() {
        return "home";
    }

    @RequestMapping("/addRecipe")
    public String addRecipe(Recipe recipe) {
        System.out.println(recipe.getName());
        repo.save(recipe);
        return "home";
    }
}

主页.jsp:

<%@ page language="java" contentType="text/html; charset=windows-1255"
pageEncoding="windows-1255"%>
<!DOCTYPE HTML>
<HTML>
<head>
<meta charset="windows-1255">
<title>Insert title here</title>
</head>
<body>
<h3 align="center">Recipe App</h3> <br><be>

<form action="addRecipe">
    ID: <input type="text" name="uid"/> <br><be>
    User Name: <input type="text" name="userName"/> <br><be>
    <input type="submit" value="Submit" />
</form>     
</body> 
</html>

食谱库:

package era;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface RecipeRepo extends MongoRepository<Recipe, Integer>{
}

食谱:

package era;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection  = "recipe")
public class Recipe {

    @Id
    private int uid;
    private String name;

    public int getId() {   return uid; }
    public void setId(int uid) {   this.uid = uid; }
    public String getName() {   return name; }
    public void setName(String name) {   this.name = name;}
}

输入 id 和 username 后,这是控制台中打印的行:

2020-05-20 17:48:33.057  INFO 4916 --- [nio-8080-exec-2] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:2, serverValue:36}] to localhost:27017

标签: springmongodbspring-boot

解决方案


我看到的是您没有将 jsp 表单绑定到 pojo。

一定要使用jsp形式的name来匹配pojo属性,使用value来抓取数据。

你可以尝试这样的事情:

<%@ page language="java" contentType="text/html; charset=windows-1255"
pageEncoding="windows-1255"%>
<!DOCTYPE HTML>
<HTML>
<head>
<meta charset="windows-1255">
<title>Insert title here</title>
</head>
<body>
<h3 align="center">Recipe App</h3> <br><be>

<form action="addRecipe">
    ID: <input type="text" name="uid" value="${recipe.uid}"/> <br><be>
    User Name: <input type="text" name="name" value="${recipe.name}"/> <br><be>
    <input type="submit" value="Submit" />
</form>     
</body> 
</html>

推荐阅读