gpt4 book ai didi

java - 未使用自定义 HTTP 消息转换器,415 媒体类型不受支持

转载 作者:IT老高 更新时间:2023-10-28 13:59:13 24 4
gpt4 key购买 nike

我正在创建一个测试应用程序,以在传递给 Controller ​​之前实现从 XML 字符串到 Employee 对象的转换。我不想使用 JAXB 转换器,因为其目的是测试自定义 HTTP 消息转换器,我将在涉及使用 SAX 解析器和一些复杂规则的 XML 解析的实际用例中使用它。

以下是执行的关键步骤:

  • Employee.java 类的创建:域对象
  • EmployeeManagementController.java 类的创建:用于管理员工的 Spring MVC Controller
  • EmployeeConverter.java 的创建:用于将 XML 字符串转换为 Employee 对象的自定义转换器。
  • 创建employee-servlet.xml:Spring配置文件
  • 创建 web.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;
}


}

employee-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 Unsupported Media Type.

我在 RestClient 中将 Content-Type 和 Accept header 设置为 text/xml,并在正文中将以下 XML 字符串作为参数传递:

xml=<employee><name>Jack</name><designation>Account Director</designation><skill>Commuication</skill></employee>

有人可以帮忙告诉我需要进行哪些更改吗?我也尝试使用 AnnotationMethodHandlerAdapter 来注册消息转换器。

最佳答案

1.设置媒体类型

将您的实现与一些 HttpMessageConverter 进行比较Spring 提供的实现(例如“MappingJackson2HttpMessageConverter”)表明您错过了定义 supportedMediaTypes .

HttpMessageConverter 的常用方式*扩展 AbstractHttpMessageConverter<T>是在构造函数中设置媒体类型,使用 super 构造函数AbstractHttpMessageConverter.(MediaType supportedMediaType) .

 public class EmployeeConverter extends AbstractHttpMessageConverter<Employee> {
public EmployeeConverter() {
super(new MediaType("text", "xml", Charset.forName("UTF-8")));
}
}

顺便说一句:您还可以注册一种以上的媒体类型**

super(MediaType.APPLICATION_XML,
MediaType.TEXT_XML,
new MediaType("application", "*+xml"));

顺便说一句 2:对于 xml 计数器,应该考虑从 AbstractXmlHttpMessageConverter<T> 扩展。

<强>2。注册您的转换器

<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">...

  • *被其他实现使用,例如 MappingJackson2HttpMessageConverter´
  • **示例取自 AbstractXmlHttpMessageConverter<T>

关于java - 未使用自定义 HTTP 消息转换器,415 媒体类型不受支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21349030/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com