如何从表单传递html输入值到数据库(Springboot)

时间:2017-02-08 14:09:38

标签: java html spring spring-boot

我有一个本地Oracle数据库,我已经建立了一个可靠的连接。现在我只想使用Controller从HTML输入表单中发布数据来处理所述数据。

我的表单如下:

<form action="/request/save" method="post">
    <input type="text" id="dateInput" name="requestDate" value="1" style="display: none;"/>
    <input type="text"  name="description" value="This is a test request." style="display: none;"/>
    <input type="text" name="status" value="false" style="display: none;"/>
    <div style="width: 200px;"><input type="submit" value="Submit Request" style="display: block;"></div>
 </form>

控制器:

@RequestMapping(value = "/save", method = RequestMethod.POST)
    String saveRequest(Principal principal, @ModelAttribute Request request, Model model) {
        // Set UserId to Request Field USER_ID
        Users user = usersRepository.findOneByInitialName(principal.getName());
        Request requestObj = new Request(user, new Date());
        requestObj.setId(user.getId());

        // Set Additional Request Fields
        requestObj.setDescription("Test");
        requestObj.setStatus(false);
        requestObj.setRequestDate(new Date());

        // Save Request Object
        requestRepository.save(requestObj);
        return "requests";
    }

实体(完成):

@Entity
public class Request {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="request_id")
    private Long id;
    private Date requestDate;
    private String description;
    private Boolean status;
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id", nullable = false)
    private Users users;

    public Request() {}

    public Request(Users user, Date requestDate) {
        this.setUsers(user);
        this.setRequestDate(requestDate);
    }

    @Override
    public String toString() {
        return String.format(
                "Request[id=%d, inital='%s', requestDate='%s']",
                getId()
                , getUsers().getInitialName()
                , getRequestDate());
    }


    public Date getRequestDate() {
        return requestDate;
    }

    public void setRequestDate(Date requestDate) {
        this.requestDate = requestDate;
    }

    public Boolean getStatus() {
        return status;
    }

    public void setStatus(Boolean status) {
        this.status = status;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Users getUsers() {
        return users;
    }

    public void setUsers(Users users) {
        this.users = users;
    }
}

如何将表单中的数据发送到我的数据库?

错误:

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.

1 个答案:

答案 0 :(得分:1)

您可能已在web.xml中配置了csrf过滤器,因此您需要在请求标头中传递“X-CSRF-TOKEN”。