我需要将JSON格式的javascript日期对象提交给JSP,在JSP中, 我正在使用Jackson包将传入的JSON字符串解析为Java GregorianCalendar对象。 Jackson包成功地将传入的JSON字符串解析为Java GregorianCalendar对象,没有任何错误消息,但是,我发现javascript日期对象和Java GregorianCalendar对象之间存在1天的差异。 以下JSP页面可以说明问题,那么如何解决该问题?
这是我的java对象:
public class Shift {
private String ito_id;
private String shift;
private GregorianCalendar shift_date;
public Shift(){
}
public String getItoId() {
return ito_id;
}
public void setItoId(String ito_id) {
this.ito_id = ito_id;
}
public String getShift() {
return shift;
}
public void setShift(String shift) {
this.shift = shift;
}
public GregorianCalendar getShiftDate() {
return shift_date;
}
public void setShiftDate(GregorianCalendar shift_date) {
this.shift_date = shift_date;
}
}
这是我的前端JSP页面:
<%@page contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF8">
<title>Insert title here</title>
<script type="text/javascript" src="<%=request.getContextPath() %>/webjars/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="clientSideDateValue">
Client side date value:
</div>
<div id="serverSideDateValue">
Server side date value:
</div>
<script>
var shiftDate=new Date(2018,6,1);
$("#clientSideDateValue").html("Client side date value:"+shiftDate.getFullYear()+"/"+shiftDate.getMonth()+"/"+shiftDate.getDate());
itoRosterString="{\"itoId\":\"999-01-01\",";
itoRosterString+="\"shift\":\"b\",";
itoRosterString+="\"shiftDate\":"+JSON.stringify(shiftDate);
itoRosterString+="}";
jQuery.ajax({"url": "saveShift.jsp",
dataType: 'text',
data:itoRosterString,
method:"POST",
success:function(requestResult){
$("#serverSideDateValue").html("Server side date value:"+requestResult);
},
error:function(jqXHR, textStatus, errorThrown)
{
console.log(jqXHR,textStatus);
}
});
</script>
</body>
</html>
这是我的后端JSP页面(即saveShift.jsp):
<%@page contentType="text/html; charset=UTF-8"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="com.Shift"%>
<%@ page import="com.fasterxml.jackson.databind.ObjectMapper"%>
<%
ObjectMapper objectMapper = new ObjectMapper();
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
Shift shift=objectMapper.readValue(br.readLine(),Shift.class);
out.println(shift.getShiftDate().get(Calendar.YEAR)+"/"+shift.getShiftDate().get(Calendar.MONTH)+"/"+shift.getShiftDate().get(Calendar.DAY_OF_MONTH));
%>