【问题标题】:record is not added to the table记录未添加到表中
【发布时间】:2020-03-05 20:33:35
【问题描述】:

我想在表中保存一条新记录 - 正文。 我使用 Spring Boot 和 HTML。 所以它看起来在 HTML:

<select id="bodiesList" multiple="multiple" class="selector">
    <option th:each="b : ${bodies}"
    th:value="${b.id}"
    th:text="${b.name}"></option>
</select>

控制器:

@Controller
@RequestMapping("/general")
public class OrderController {

    @Autowired
    @Qualifier("orderServiceImpl")
    private OrderService orderService;

    @GetMapping(value = "/list")
    public String get(Model theModel) {

        theModel.addAttribute("orders", orderService.getOrders());

        return "general/index";
    }

    @GetMapping(value = "/showFormForAdd")
    public String add(Model theModel) {
        Orders orders = new Orders();

        List<Body> body = orderService.getBody();

        theModel.addAttribute("bodies", body);
        theModel.addAttribute("order", orders);

        return "general/create-orders";
    }

    @PostMapping(value = "/saveOrders")
    public String addOrders(@ModelAttribute("order") Orders orders, @RequestParam("picture") MultipartFile file) throws IOException {

        orders = orderService.uploadOrders(orders, file);
        orderService.save(orders);

        return "redirect:/general/list";
    }

}

但不在数据库中,不在我的列中,没有保存任何内容。

我的代码中需要修复什么?

【问题讨论】:

    标签: java html spring thymeleaf


    【解决方案1】:

    使用 th:field 将值从您的 html 页面发送到您的控制器。试试这样的 -

     <select th:field="*{body}" id="bodiesList" multiple="multiple" class="selector">
                        <option th:each="b : ${bodies}"
                                th:value="${b.id}"
                                th:text="${b.name}"></option>
                    </select>
    

    然后在表单提交后在您的控制器上捕获此信息(与您在 saveOrder 控制器上捕获 orders 相同。

    在 thymelead 官方文档中阅读更多关于 th:field 的信息 - https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html

    【讨论】:

    • 谢谢,有帮助。但现在我在表格中的列 Body 显示不正确。喜欢图片:link如何解决?
    • 我从图中了解到,你只需要body中的name的值,所以简单的提取的值body 对象中的 name 字段,然后保存到数据库中,例如 - body.getName();然后保存
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 2021-02-18
    • 2018-05-15
    • 1970-01-01
    相关资源
    最近更新 更多