如何在Spring-MVC中正确发出Post请求?

How to correctly make a Post request in Spring-MVC?

提问人:JohnEdwards-8 提问时间:11/14/2023 更新时间:11/14/2023 访问量:28

问:

我有一个页面视图,其中包含用户订单、控制器、模型和使用 DAO 概念访问数据库的类。但是,当我尝试“添加订单”时,我的请求没有得到正确处理。我做错了什么?PostMapping

订单.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">

<head>
    <meta charset="ISO-8859-1">
    <title>My Orders</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>

<body>
    <div th:include="frags/headerUser"></div>

    <div class="container mt-5">
        <h2>User Orders</h2>
    
        <table class="table table-bordered">
            <thead>
            <tr>
                <th>Date</th>
                <th>Status</th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="order : ${ordersList}">
                <td th:text="${order.date}"></td>
                <td th:text="${order.status}"></td>
            </tr>
            </tbody>
        </table>

        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addOrderModal">
            Add new order
        </button>

        <div class="modal" id="addOrderModal">
            <div class="modal-dialog">
                <div class="modal-content">

                    <div class="modal-header">
                        <h4 class="modal-title">New order</h4>
                        <button type="button" class="btn btn-secondary close" data-dismiss="modal">&times;</button>
                    </div>

                    <div class="modal-body">
                        <form th:action="@{/addOrder}" method="post">
                            <!-- My form -->
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

</body>

</html>

订单 .java

//imports
public class Order {
    private int id;
    private Date date;
    private String status;
    
    //get- and set- funcs

}

jdbcOrderDAO.java

//imports
@Repository
public class JdbcOrderDAO implements OrderDAO {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public JdbcOrderDAO(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void addOrder(Order order) {
        String sql = "INSERT INTO indent (indent_date, indent_status) VALUES (?, ?)";
        jdbcTemplate.update(sql, order.getDate(), order.getStatus());
    }
    //...
}

控制器用户.java

//imports
@Controller
public class ControllerUser {
    private final JdbcOrderDAO oDAO;

    public ControllerUser(JdbcOrderDAO oDAO) {
        this.oDAO = oDAO;
    }

    //GetMappings
    
    @PostMapping("/addOrder")
    public String addOrder(@RequestParam("orderDate") Date orderDate,
                           @RequestParam("orderStatus") String orderStatus) {

        Order order = new Order();
        order.setDate(orderDate);
        order.setStatus(orderStatus);
        oDAO.addOrder(order);
        
        return "user/orders";
    }
}

数据库配置.java

//imports
@Configuration
public class DatabaseConfig {

    @Value("${spring.datasource.url}")
    private String databaseUrl;

    @Value("${spring.datasource.username}")
    private String databaseUsername;

    @Value("${spring.datasource.password}")
    private String databasePassword;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl(databaseUrl);
        dataSource.setUsername(databaseUsername);
        dataSource.setPassword(databasePassword);
        return dataSource;
    }
    
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}
java postgresql spring-mvc

评论


答:

0赞 Esteban Sifuentes Samaniego 11/14/2023 #1

您可以尝试创建一个 JPA 实体和存储库,而不是“DAO 概念”。

使用 Spring Data JPA,您可以创建一个 Order 类并相应地对其进行注释:

@Entity
public class Order {
    private Date orderDate;
    private String orderStatus;
    /* Constructors, getters, and setters */
}

然后,在 html 表单标记中,使用 th:object 引用实体,并使用 th:field 引用每个字段

<form action="#" th:action="@{/addOrder}" th:object="${order}" method="POST">
    <input type="text" th:field="*{orderStatus}"> 
    <!-- other fields -->
</form>

That way each field is set automatically. So in your controller you just have to pass it to the corresponding method.

@PostMapping("/addOrder")
public String addOrder(Order order) {
    orderRepository.save(order);
    return "user/orders";
}

In this case, I'm assuming you create a repository using JpaRepository. You can try that also instead of the way you are doing it right now. JPA automatically creates basic CRUD operations for you.

You just have to create an interface that extends JpaRepository like this:

@Repository
public interface OrderRepository extends JpaRepository<Order, Long>{}

And in order to call it from your Controller you just @Autowire it:

@Autowired
private OrderRepository orderRepository;

评论

0赞 JohnEdwards-8 11/14/2023
This is a learning project where I want to try out the DAO concept. Maybe you can tell me what's wrong in my code?
0赞 Esteban Sifuentes Samaniego 11/14/2023
What's the error message?
0赞 JohnEdwards-8 11/14/2023
The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
0赞 Esteban Sifuentes Samaniego 11/15/2023
I think it has to do with the mapping of the fields from the html to the controller. In your orders.html you are not specifying any entity or fields; but in your controller you are expecting 2 fields (orderDate and orderStatus). In the example I showed you I specify the entity and fields with th:object and th:field, respectively and then I used them in the controller with the Order object.