我是java spring web mvc的新手,目前正在尝试使用spring控制器创建ajax响应。
这是我的代码:
控制器类
@Controller
@RequestMapping("/")
public class AppController {
@Autowired
EmployeeService service;
@Autowired
MessageSource messageSource;
@RequestMapping(value = { "/editAjax-{ssn}-employee" }, method = RequestMethod.GET, produces = "application/json")
public @ResponseBody Employee check1(@PathVariable String ssn,
HttpServletRequest request, HttpServletResponse response) {
Employee employee = service.findEmployeeBySsn(ssn);
return employee;
}
}
模型类
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Size(min = 3, max = 50)
@Column(name = "NAME", nullable = false)
private String name;
@Size(min = 5, max = 200)
@Column(name = "ADDRESS", nullable = false)
private String address;
@NotNull
@Digits(integer = 8, fraction = 2)
@Column(name="SALARY", nullable = false)
private BigDecimal salary;
@NotEmpty
@Column(name="SSN", unique = true, nullable = false)
private String ssn;
@NotNull
@DateTimeFormat(pattern = "dd/MM/yyyy")
@Column(name = "JOINING_DATE", nullable = false)
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
private LocalDate joiningDate;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((ssn == null) ? 0 : ssn.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (id != other.id)
return false;
if (ssn == null) {
if (other.ssn != null)
return false;
} else if (!ssn.equals(other.ssn))
return false;
return true;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", address=" + address
+ ", salary=" + salary + ", ssn=" + ssn + ", joiningDate="
+ joiningDate + "]";
}
// Empty Constructor
public Employee() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public LocalDate getJoiningDate() {
return joiningDate;
}
public void setJoiningDate(LocalDate joiningDate) {
this.joiningDate = joiningDate;
}
}
这是我在jsp中的脚本
<script>
/* This function provide response from controller retrieving employee
* detail via ssn id.
*/
function searchViaAjax(obj) {
var stringResponse;
var id = obj.id;
$.ajax({
/* Controller Request Mapping */
url : "${pageContext.request.contextPath}/editAjax-${'" + id
+ "'}-employee",
type : "GET",
contentType : "application/json",
dataType : "json",
success : function(response) {
/* Convert response into String */
stringResponse = JSON.stringify(response, [ 'id', 'name',
'address', 'salary', 'ssn', 'joiningDate' ]);
console.log(stringResponse);
},
error : function(e) {
console.log("ERROR: ", e);
}
});
}
</script>
控制台结果:
sucess! {"id":6,"name":"test","address":"Makati city","salary":124565,"ssn":"2","joiningDate":{}}
正如您所见,我未能获得加入日期值。
当我直接访问网址时,响应的输出就是这个。一切正常,我得到id,name,address,salary,ssn,joinedDate的值。
但是在joinDate中,我认为有很多大括号和字段,因为模型类中的类型设置为org.jadira.usertype.dateandtime.joda.PersistentLocalDate?我怎样才能在加入日期字段中获得至少“值”:[2018,3,27]?
有没有办法检索我想要的值,尽管joinDate中有很多值?我是否需要更改模型类中的类型?
{“id”:6,“name”:“test”,“address”:“Makati city”,“salary”:124565,“ssn”:“2”,“joinedDate”:{“请将dayOfMonth “:27,” 一周中的某天 “:2,” 时代 “:1,” 年 “:2018年,” DAYOFYEAR “:86,” 年表 “:{” 区 “:{” 固定 “:真实的,” ID “:” UTC “}},” weekyear “:2018,” monthOfYear “:3”,yearOfEra “:2018,” yearOfCentury “:18,” centuryOfEra “:20,” weekOfWeekyear “:13,” 字段 “:[{” 宽松” :假的, “maximumValue”:292278993, “minimumValue”: - 292275054, “rangeDurationField”:空, “leapDurationField”:{ “unitMillis”:86400000, “精确”:真正的 “名”: “天”, “类型” :{ “名”: “天”}, “支持”:真正}, “durationField”:{ “unitMillis”:31556952000, “精确”:假的, “名”: “年”, “类型”:{“名称“:” 年 “},” 支持 “:真正},” 名 “:” 年”, “类型”:{ “durationType”:{ “名”: “年”}, “rangeDurationType”:空, “名” : “年”}, “支持”:真正},{ “网开一面”:假的, “maximumValue”:12, “minimumValue”:1, “rangeDurationField”:{ “unitMillis”:31556952000, “精确”:假”命名 “:” 年 “ ”类型“:{ ”名“: ”年“}, ”支持“:真正}, ”leapDurationField“:{ ”unitMillis“:86400000, ”精确“:真正的 ”名“:” d AYS “ ”类型“:{ ”名“: ”天“}, ”支持“:真正}, ”durationField“:{ ”unitMillis“:2629746000, ”精确“:假的, ”名“: ”月“,”类型 “:{” 名 “:” 月 “},” 支持 “:真正},” 名 “:” monthOfYear”, “类型”:{ “durationType”:{ “名”: “月”}, “rangeDurationType” :{ “名”: “年”}, “名”: “monthOfYear”}, “支持”:真正},{ “maximumValue”:31, “minimumValue”:1, “rangeDurationField”:{ “unitMillis”:2629746000 , “精确”:假的, “名”: “月”, “类型”:{ “名”: “月”}, “支持”:真正}, “网开一面”:假的, “unitMillis”:86400000,“durationField “:{” unitMillis “:86400000,” 精确 “:真正的” 名 “:” 天 “ ”类型“:{ ”名“: ”天“}, ”支持“:真正}, ”名“:” 请将dayOfMonth ”, “类型”:{ “durationType”:{ “名”: “天”}, “rangeDurationType”:{ “名”: “月”}, “名”: “请将dayOfMonth”}, “支持”:真实, “leapDurationField”:空}], “值”:[2018,3,27], “域类型”:[{ “durationType”:{ “名”: “年”}, “rangeDurationType”:空, “名”: “年”},{ “durationType”:{ “名”: “月”}, “rangeDurationType”:{ “名”: “年”}, “名”: “monthOfYear”},{ “durationType”:{”命名 “:” 天“}, “rangeDurationType”:{ “名称”: “月”}, “名称”: “请将dayOfMonth”}]} }
更新
当我尝试删除@Type(type =“org.jadira.usertype.dateandtime.joda.PersistentLocalDate”)时出现错误。它说无法反序列化。
Apr 05, 2018 12:50:53 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/MavenTry] threw exception [Request processing failed; nested exception is org.hibernate.type.SerializationException: could not deserialize] with root cause
java.io.StreamCorruptedException: invalid stream header: 32303138
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:862)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:354)
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:328)
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:318)
at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:237)
at org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:306)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:155)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:130)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:44)
at org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:71)
at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:64)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:267)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:263)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:253)
at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:338)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2969)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1695)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1627)
at org.hibernate.loader.Loader.getRow(Loader.java:1514)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:725)
at org.hibernate.loader.Loader.processResultSet(Loader.java:952)
at org.hibernate.loader.Loader.doQuery(Loader.java:920)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2553)
at org.hibernate.loader.Loader.doList(Loader.java:2539)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
at org.hibernate.loader.Loader.list(Loader.java:2364)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:126)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1682)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:380)
at com.websystique.springmvc.dao.EmployeeDaoImpl.findAllEmployee(EmployeeDaoImpl.java:44)
at com.websystique.springmvc.service.EmployeeServiceImpl.findAllEmployee(EmployeeServiceImpl.java:55)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy112.findAllEmployee(Unknown Source)
at com.websystique.springmvc.controller.AppController.employeeList(AppController.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1539)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1495)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
完整的代码参考。这是该程序的教程。 http://websystique.com/springmvc/spring-4-mvc-and-hibernate4-integration-example-using-annotations/