Java 从@RestController返回Obj
格雷廷 我有一个SpringMVC控制器,它使用@RestController返回JsonData(Spring4.1.7) 我的问题是,如果我返回一个列表,它会工作,但是如果我尝试返回一个obj,我会得到一个没有跟踪的错误!它不会简单地返回 这就是我打电话的方式Java 从@RestController返回Obj,java,json,angularjs,spring,Java,Json,Angularjs,Spring,格雷廷 我有一个SpringMVC控制器,它使用@RestController返回JsonData(Spring4.1.7) 我的问题是,如果我返回一个列表,它会工作,但是如果我尝试返回一个obj,我会得到一个没有跟踪的错误!它不会简单地返回 这就是我打电话的方式 $scope.edit = function edit(id) { $http.post(urlBase + 'test/edit/'+id).success(function(data) { alert('works'
$scope.edit = function edit(id) {
$http.post(urlBase + 'test/edit/'+id).success(function(data) {
alert('works');
}).error(function(data) {
alert('error' + data);
});
};
这是控制器
@RestController
public class MyController {
@Autowired
MyService myService;
//THIS DOESN'T WORK
@RequestMapping(value="/secure/test/edit/{id}", method={RequestMethod.POST,RequestMethod.GET})
public MyObject editObj(@PathVariable("id") int id) {
return this.myService.getObjById(id);
}
//THIS WORKS
@RequestMapping(value="/secure/test/edit/{id}", method={RequestMethod.POST,RequestMethod.GET})
public List<MyObject> editObj(@PathVariable("id") int id) {
return this.myService.getAll();
}
}
你可以试试这个
@RequestMapping(value=“/secure/test/edit/{id}”,method={RequestMethod.POST,RequestMethod.GET})
public@ResponseBody ResponseEntity editObj(@PathVariable(“id”)int-id){
返回新的ResponseEntity(this.myService.getObjById(id),HttpStatus.OK);
}
返回ResponseEntity对象,因为Spring可以很容易地为此生成/解析JSON。我已经用我的类对象尝试了您的代码,并看到它运行良好。似乎您的类
MyObject
缺少某些内容。可能缺少可序列化的工具解决方案
在我的模型类中添加了以下注释
它必须返回某些内容,或者抛出异常。如果没有堆栈跟踪,就不可能得到异常。检查在浏览器开发工具的网络面板中得到的响应。或者更改您的方法以获取(这是他们应该使用的),只需在浏览器地址栏中输入REST服务的URL。是否可以添加您获得的错误跟踪?或者简单地使用Chrome控制台开发者查找POST请求,或者简单地使用Console.log(数据);在js代码中?如果没有堆栈跟踪,您如何知道您得到了一个错误?若你们认为在UI中你们并没有得到预期的结果,所以一定有异常,那个么它是错误的。使用Chrome developers工具或HTTP调试客户端(如Fiddler)检查从服务器返回的内容。此外,检查您的配置文件中是否有
org.springframework.web.servlet.view.ContentNegotingViewResolver
的自定义设置。如果是这样,请在这里提供分析。我已经映射了所有可丢弃的异常和错误页面,我将对该映射进行注释,以查看是否得到一些跟踪,然后我会让你们知道!谢谢将我的Obj类添加到Postal我需要的是实现可序列化到我的类?像这样<代码>公共类myObj实现可序列化的{..code..}尝试过,但没有结果。@lucas freitas创建myObject实体的VO,然后将所有值从实体设置为VO。JSON消息转换器将无法直接从实体创建JSON字符串,因为它有多个关系。此外,在一般情况下,实体类具有双向关系,即在一个类manytone和另一个类OneToMany中,当使用JSON消息转换器解析对象时,它在两个类的对象之间进行无限递归调用。因此,创建一个VO并将其作为ResponseBy传递是一个很好的做法。您有没有示例向我展示?我发布并回答了我为解决这个问题所做的一切,我认为这不是最好的方法,但我已经多次推墙了。我现在没有任何例子,但遵循设计模式总是很好的。特别是使用spring框架时的MVC(三层体系结构)。如果我们将所有层/层解耦,即数据层(JPA类实体和存储库)--->业务层(服务类)--->客户机层(控制器),效果会更好。
<html><head><title>Apache Tomcat/7.0.56 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 500 - Could not write content: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: sys.barattie.model.Caixa_$$_jvst126_0["handler"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: sys.barattie.model.Caixa_$$_jvst126_0["handler"])</h1><HR size="1" noshade="noshade"><p><b>type</b> Exception report</p><p><b>message</b> <u>Could not write content: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: sys.barattie.model.Caixa_$$_jvst126_0["handler"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: sys.barattie.model.Caixa_$$_jvst126_0["handler"])</u></p><p><b>description</b> <u>The server encountered an internal error that prevented it from fulfilling this request.</u></p><p><b>exception</b> <pre>org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: sys.barattie.model.Caixa_$$_jvst126_0["handler"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: sys.barattie.model.Caixa_$$_jvst126_0["handler"])
org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:238)
org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:161)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:101)
org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:185)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:126)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:105)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
</pre></p><p><b>root cause</b> <pre>com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: sys.barattie.model.Caixa_$$_jvst126_0["handler"])
com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:59)
com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:26)
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:505)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:639)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:114)
com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1887)
org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:231)
org.springframework.http.converter.AbstractHttpMessageConverter
@Entity
@Table(name = "test")
public class myObject {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
@JoinColumn(name = "objb_id", referencedColumnName = "id")
private Objb objb;
private String test;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Objb getObjb() {
return objb;
}
public void setObjb(Objb objb) {
this.objb = objb;
}
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
@RequestMapping(value="/secure/test/edit/{id}", method={RequestMethod.POST,RequestMethod.GET})
public @ResponseBody ResponseEntity<MyObject> editObj(@PathVariable("id") int id) {
return new ResponseEntity<MyObject>(this.myService.getObjById(id),HttpStatus.OK);
}
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})