1

我正在尝试创建春季休息服务。我的 servlet.xml 如下所示:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans     
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>


<!-- Database Configuration -->
<import resource="classpath:DataSource.xml"/>
<import resource="classpath:Hibernate.xml"/>

<!-- Beans Declaration -->
<import resource="classpath:Employee.xml"/>

<context:component-scan base-package="com.nilenium.service.controller" />

<mvc:annotation-driven />

      <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
   <property name="messageConverters">
  <list>
   <ref bean="jsonConverter"/>
   <ref bean="marshallingHttpMessageConverter"/>
  </list>
   </property>
  </bean>

   <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>


  <bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
   <property name="autodetectAnnotations" value="true"/>
   <property name="annotatedClasses">
    <list>
        <value>com.nilenium.employee.model.Employee</value>                         
        <value>com.nilenium.employee.model.EmployeeRecord</value>                           
    </list>                     
  </property>

</bean>

    <bean id="marshallingHttpMessageConverter"
      class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
    <property name="marshaller" ref="xstreamMarshaller"/>
    <property name="unmarshaller" ref="xstreamMarshaller"/>
</bean>



  <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
 <property name="order" value="1" />
  <property name="ignoreAcceptHeader" value="true" />
 <property name="defaultContentType" value="application/json" />
  <property name="mediaTypes">
 <map>
 <entry key="json" value="application/json" />
 <entry key="xml" value="application/xml" />
 </map>
 </property>

<property name="defaultViews">
 <list>
<!-- JSON View -->
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />

<!-- XML View -->
 <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
 <constructor-arg>
  <bean class="org.springframework.oxm.xstream.XStreamMarshaller">
   <property name="autodetectAnnotations" value="true"/>
   <property name="aliases">
    <props>
     <prop key="employee">com.nilenium.employee.model.Employee</prop>
     <prop key="employee">com.nilenium.employee.model.EmployeeRecord</prop>
     </props>
</property>
  </bean>
 </constructor-arg>
</bean>
   </list>
  </property>
 </bean>


</beans>

我的模型类是这样的:

package com.nilenium.employee.model;

import java.io.Serializable;

import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonRootName;

import com.thoughtworks.xstream.annotations.XStreamAlias;


@XStreamAlias("employee")

public class Employee implements Serializable {

private static final long serialVersionUID = 1L;


private int employeeId;
private String employeeName;

public int getEmployeeId() {
    return employeeId;
}

public void setEmployeeId(int employeeId) {
    this.employeeId = employeeId;
}

public String getEmployeeName() {
    return employeeName;
}

public void setEmployeeName(String employeeName) {
    this.employeeName = employeeName;
}



public Employee(int employeeId, String employeeName)
{
    this.employeeId = employeeId;
    this.employeeName = employeeName;

}
public Employee() {
}
}

我的服务控制器类是这样的:

package com.nilenium.service.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.nilenium.employee.bo.EmployeeBo;
import com.nilenium.employee.model.Employee;
import com.nilenium.employee.model.EmployeeRecord;

@Controller
@RequestMapping("/Service")
public class NileniumServiceController {

@Autowired
private EmployeeBo employeeBo;

@ExceptionHandler
 public String exceptionHandler(Exception e){
    return "serviceError"; 
 }

@RequestMapping(value =  "employeeId/{employeeId}", method = RequestMethod.GET, headers = "Accept=application/xml, application/json")
public Employee getEmployeeName(@PathVariable int employeeId,
        HttpServletResponse resp,
        ModelMap model) {
//      System.out.println("Emp Name : " + employeeName);
    Employee empReturned = new Employee();
    empReturned.setEmployeeId(employeeId);
    empReturned.setEmployeeName("Demo Name");

    return empReturned;

}

@RequestMapping(value = "/employees", method = RequestMethod.GET, headers = "Accept=application/xml, application/json")
public EmployeeRecord getAllEmployeeDetails(HttpServletResponse resp,
        ModelMap model) {

    List<Employee> empListReturned = employeeBo.getAllEmployee();
    EmployeeRecord eRecords = new EmployeeRecord();
    eRecords.setEmployeeList(empListReturned);
    return eRecords;
}

@RequestMapping(value = "/storeemployee",method = RequestMethod.POST, headers = {"Accept=text/xml, application/json"})
public Employee storeEmpRecord(@RequestBody Employee employee,HttpServletResponse resp,
        ModelMap model)
{
    System.out.println("Emp Id received : "+employee.getEmployeeId());
    System.out.println("Emp Name received : "+employee.getEmployeeName());
//      Employee empReturned = employeeBo.findByEmployeeId(1);


    return employee;
}

}

当我尝试将 xml 发布到storeEmpRecord方法时,xstream marshaller 无法将 xml 请求转换为相应的对象(Employee对象)。

我的测试客户端是这样的:

package com.nilenium.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.aop.framework.adapter.DefaultAdvisorAdapterRegistry;

import com.nilenium.employee.model.Employee;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class RestPostTest {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setEmployeeId(1);
emp.setEmployeeName("Nilalohita");

XStream xStream = new XStream(new DomDriver());
xStream.alias("employee", Employee.class);
System.out.println(xStream.toXML(emp));
String xmlBody = xStream.toXML(emp);
HttpClient client = new DefaultHttpClient();
String jsonDemo = "{\"employeeId\":2,\"employeeName\":\"He-Man\"}";
try {
    HttpPost post = new  HttpPost("http://localhost:8080/SampleMaven/Service/storeemployee");
//      post.addHeader("Accept", "application/json");
//      post.addHeader("Content-Type", "application/json");

    post.addHeader("Accept", "application/xml");
    post.addHeader("Content-Type", "application/xml");

    StringEntity entity = new StringEntity(xmlBody, "UTF-8");
//      entity.setContentType("application/json");
    entity.setContentType("application/xml");
    post.setEntity(entity);

    HttpResponse response = client.execute(post);

    BufferedReader rd = new BufferedReader(new   InputStreamReader(response.getEntity().getContent()));
      String line = "";
      while ((line = rd.readLine()) != null) {
       System.out.println(line);
      }


} catch (URISyntaxException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (HttpException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}
}

如果我做错了什么,请告诉我。使用@XMLrootEmployee 类而不是@XStreamAlias("employee").

我收到以下错误。完整的堆栈跟踪是这样的

   Caused by:</h3><pre>javax.servlet.ServletException: Unable to locate object to be marshalled in model: {}
  at  org.springframework.web.servlet.view.xml.MarshallingView.renderMergedOutputModel(MarshallingView.java:100)
  at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1047)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:726)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:206)
at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:324)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:648)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:205)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)
4

1 回答 1

0

问题出在控制器方法中:

@RequestMapping(value = "/storeemployee",method = RequestMethod.POST, headers = {"Accept=text/xml, application/json"})
public Employee storeEmpRecord(@RequestBody Employee employee,HttpServletResponse resp,
    ModelMap model)
{
    System.out.println("Emp Id received : "+employee.getEmployeeId());
    System.out.println("Emp Name received : "+employee.getEmployeeName());
//      Employee empReturned = employeeBo.findByEmployeeId(1);
return employee;
}

Spring MVC 不会(不能)model自动添加对象。您需要将employee对象添加到ModelMap. 然后将模型映射传递给编组视图,该视图查找它可以编组的任何对象,并将它们编组以进行响应。

Unable to locate object to be marshalled in model: {}意味着 Marshalling View 收到了一个 ModelMap,其中没有带有 XStream 注释的对象。

希望这可以帮助。

于 2013-04-20T20:01:48.787 回答