我正在创建一个测试应用程序,以便在传递给控制器之前实现从XML String到Employee对象的转换。我不想使用JAXB转换器,因为我的目的是测试自定义HTTP消息转换器,我将在我的实际用例中使用它涉及使用SAX解析器和一些复杂规则进行XML解析。
以下是执行的关键步骤:
Employee.java
@Component
@XmlRootElement(name="employee")
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee{
@XmlElement(name="name")
String name;
@XmlElement(name="designation")
String designation;
@XmlElement(name="skill")
String skill;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getSkill() {
return skill;
}
public void setSkill(String skill) {
this.skill = skill;
}
}
EmployeeManagementController.java
@Controller
@RequestMapping(value="/emp")
public class EmployeeManagementController {
@RequestMapping(value="/add/employee", method=RequestMethod.POST, consumes="text/html")
public void addEmployee(@RequestBody Employee employee){
System.out.println("Employee Name : "+employee.getName());
System.out.println("Employee Designation : "+employee.getDesignation());
System.out.println("Employee Skill : "+employee.getSkill());
}
}
EmployeeConverter.java
@Component
public class EmployeeConverter extends AbstractHttpMessageConverter<Employee>{
@Override
protected Employee readInternal(Class<? extends Employee> arg, HttpInputMessage inputMsg) throws IOException,
HttpMessageNotReadableException {
// TODO Auto-generated method stub
Map<String,String> paramMap = getPostParameter(inputMsg);
BufferedReader file = new BufferedReader(new StringReader(paramMap.get("xml")));
Employee employee = null;
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance(Employee.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
employee = (Employee) jaxbUnmarshaller.unmarshal(file);
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(employee);
return employee;
}
@Override
protected boolean supports(Class<?> type) {
if(type.getSimpleName().equalsIgnoreCase("Employee")){
return true;
}
return false;
}
@Override
protected void writeInternal(Employee arg0, HttpOutputMessage arg1)
throws IOException, HttpMessageNotWritableException {
// TODO Auto-generated method stub
}
private Map<String,String> getPostParameter(HttpInputMessage input) throws IOException{
String payload = null;
String[] params = null;
BufferedReader buf = new BufferedReader(new InputStreamReader(input.getBody()));
Map<String,String> paramMap = new HashMap<String,String>();
String line="";
while((line = buf.readLine())!=null){
payload = payload+line;
}
if(payload.contains("&")){
params = payload.split("&");
for(String param : params){
paramMap.put(param.split("=")[0],param.split("=")[1]);
}
}
return paramMap;
}
}
雇员-servlet.xml中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.1.xsd">
<mvc:default-servlet-handler/>
<context:component-scan base-package="com"/>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="com.converter.EmployeeConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="json" value="application/json"/>
<entry key="xml" value="text/xml"/>
<entry key="htm" value="text/html"/>
</map>
</property>
<property name="defaultContentType" value="text/html"/>
</bean>
<!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list id="beanList">
<ref bean="employeeConverter"/>
</util:list>
</property>
</bean> -->
<!-- <bean id="employeeConverter" class="com.converter.EmployeeConverter"/> -->
</beans>
的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>TestConverter</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>employee</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>employee</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/employee-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
当我使用FireFox RestClient时,我得到响应为: 415 Unsupproted Media Type。
我在RestClient中将Content-Type和Accept标头设置为text / xml,并将正文中的以下XML字符串作为参数传递:
xml=<employee><name>Jack</name><designation>Account Director</designation><skill>Commuication</skill></employee>
有人可以帮忙,让我知道需要进行哪些更改?我还尝试使用AnnotationMethodHandlerAdapter
来注册消息转换器。
答案 0 :(得分:16)
<强> 1。设置媒体类型
将您的实现与Spring提供的一些HttpMessageConverter
实现进行比较(例如'MappingJackson2HttpMessageConverter'),表明您错过了定义supportedMediaTypes
。
扩展HttpMessageConverter
的{{1}}的常用方法是使用超级构造函数AbstractHttpMessageConverter<T>
在构造函数中设置媒体类型。
AbstractHttpMessageConverter.(MediaType supportedMediaType)
BTW 1:您还可以注册多个媒体类型**
public class EmployeeConverter extends AbstractHttpMessageConverter<Employee> {
public EmployeeConverter() {
super(new MediaType("text", "xml", Charset.forName("UTF-8")));
}
}
BTW 2:对于xml conterter,应该考虑从super(MediaType.APPLICATION_XML,
MediaType.TEXT_XML,
new MediaType("application", "*+xml"));
<强> 2。注册转换器
AbstractXmlHttpMessageConverter<T>
<击>
<mvc:annotation-driven>
<mvc:message-converters>
...
<bean class="com.example.YourConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
的主要缺点是,这取代了默认配置,因此您还必须明确注册所有默认<mvc:message-converters>
。
击>
要保留默认邮件转换,您需要使用:HttpMessageConverter
<mvc:message-converters register-defaults="true">...