从html输入日期创建JSON资源

问题描述 投票:0回答:2

我想用HTML输入时间,

<form action="/createData">
<input type="date" name="startDate" placeholder="Enter Start Date." />
<input type="submit" value="Create" name="createLogin" />
</form>

@RequestMapping(value = "/createData")
    String createData(@("startDate") Date startDate, Model model) {
          String url = "http://localhost:9090/server/create";
          JSONObject json = new JSONObject();
          json.put("startDate", startDate.toString());
          Client client = new Client();
          WebResource resource = client.resource(url);
          ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, json.toString());
          response.getEntity(String.class);
          return "dateAdded";

我不是想获得响应,只想将信息保存到服务器的SQL数据库中。

但是,我正在解析错误。

我的资源接收服务器如下所示:

@POST
@Path("/create")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
    public Response create(String server) throws JSONException, BarsException, IOException, ParseException {
        JSONObject json = new JSONObject(server);
        SimpleDateFormat originalDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String StartDate = originalDateFormat
        dates.setStartDate(StartDate);
        billRepo.save(billing);
        JSONObject op = new JSONObject();
        return Response.status(200).entity(op.toString()).type(MediaType.APPLICATION_JSON).build();

我希望你能理解我想要做的事情。

java html json spring rest
2个回答
0
投票

在您的控制器中,您需要@Consumes(MediaType.MediaType.APPLICATION_FORM_URLENCODED_VALUE),因为通过表单发布通常以urlencoded形式发送。


0
投票

我能够使用你的评论找到我的答案。谢谢。

这是我的工作代码供其他人参考。

JSONObject jsonCreate = new JSONObject(server);
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd");

String stringStartDate = jsonCreate.getString("startDate");
String stringEndDate = jsonCreate.getString("endDate");

LocalDate localStartDate = LocalDate.parse(stringStartDate, format);
LocalDate localEndDate = LocalDate.parse(stringEndDate, format);

java.sql.Date sqlStartDate = java.sql.Date.valueOf(localStartDate);
java.sql.Date sqlEndDate = java.sql.Date.valueOf(localEndDate);

Billing bill = new Billing(sqlStartDate, sqlEndDate);
billRepo.save(bill);

再次感谢您的回答!干杯!

但是,此代码使用了太多的转换。

© www.soinside.com 2019 - 2024. All rights reserved.