【发布时间】:2018-07-17 00:11:38
【问题描述】:
我正在尝试创建一个使用 HTML 的 Web 服务,该 HTML 稍后用于使用 iText 创建 PDF。
我使用 Postman 将请求发送到服务器,但每次我收到以下错误,无论我选择哪种内容类型:
{
"status": "CONFLICT",
"code": 40902,
"message": "Content type 'text/plain' not supported",
"developerMessage": "null",
"moreInfoUrl": "class org.springframework.web.HttpMediaTypeNotSupportedException",
"throwable": null
}
消息根据选择的内容类型而变化:
"message": "Content type 'text/xml' not supported"
"message": "Content type 'text/html' not supported"
这是我的终点:
@RequestMapping(path = "/reports/pdf", method = RequestMethod.POST, consumes = MediaType.TEXT_HTML_VALUE)
public ResponseEntity<byte[]> generatePdfReport(@RequestBody String html) throws Exception {
byte[] pdfBytes = reportsService.generatePdf(html);
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(pdfBytes, HttpStatus.OK);
return response;
}
我已将consumes 属性更改为:
MediaType.TEXT_PLAIN_VALUEMediaType.TEXT_XML_VALUE
以匹配我在 Postman 上发送的内容。
根据@dnault 注释,将其从RequestMapping 注释中完全删除,结果相同。
我研究过类似的问题:
- Content type 'text/plain;charset=UTF-8' not supported error in spring boot inside RestController class 这是与我的问题最接近的问题,但我已经将请求中的内容类型设置为我期望在端点上的内容类型。
- Error org.springframework.web.HttpMediaTypeNotSupportedException
- Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported
但是,以上所有内容以及我检查过的与我的问题不太接近的其他一些内容都没有提供解决此问题的答案。
我尝试发送到服务器的示例 HTML 是:
<table style="border: 1px solid black; font-size: 12px; margin-top: 1px; width: 900px;" id="table_direction">
<tr>
<td width="33%" colspan="2">
<strong>Data1</strong>
</td>
<td width="33%" colspan="2">
<strongData2</strong>
</td>
<td width="16%" colspan="1">Foo</td>
<td width="16%" colspan="1">Bar</td>
</tr>
<tr>
<td colspan="">ID</td>
<td colspan="">123456</td>
<td colspan="">Property 1</td>
<td colspan="">Foo</td>
<td colspan="">Property 2</td>
<td colspan="">Bar</td>
</tr>
</table>
我们的配置是通过Java配置类进行的,如下:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.company.project")
@PropertySource("classpath:application.properties")
@EnableTransactionManagement // proxyTargetClass = true
@EnableJpaRepositories(basePackages = { "com.company.project.dao", "com.company.project.repository" })
public class HelloWorldConfiguration extends WebMvcConfigurerAdapter {
@Inject
Environment env;
@Value("${jdbc.user}")
private String userDB;
@Value("${jdbc.password}")
private String passDB;
@Value("${jdbc.url}")
private String urlDB;
@Value("${jdbc.driverClassName}")
private String driverClassName;
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public CommonsMultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}
@Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName(driverClassName);
driverManagerDataSource.setUrl(urlDB);
driverManagerDataSource.setUsername(userDB);
driverManagerDataSource.setPassword(passDB);
return driverManagerDataSource;
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.company.project.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource,
JpaVendorAdapter jpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter);
entityManagerFactoryBean.setPackagesToScan("com.company.project.model");
entityManagerFactoryBean.setJpaProperties(hibernateProperties());
return entityManagerFactoryBean;
}
private Properties hibernateProperties() {
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
jpaProperties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
jpaProperties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
return jpaProperties;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
@Bean(name = "transactionManager2")
@Autowired
@Named("transactionManager2")
public HibernateTransactionManager transactionManager2(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
@Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
return vendorAdapter;
}
public MappingJackson2HttpMessageConverter jacksonMessageConverter(){
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
Hibernate5Module module = new Hibernate5Module();
module.disable(Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION);
mapper.registerModule(module);
messageConverter.setObjectMapper(mapper);
return messageConverter;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(jacksonMessageConverter());
super.configureMessageConverters(converters);
}
}
@ControllerAdvice
public class GenericRepositoryRestExceptionHandler extends RepositoryRestExceptionHandler {
@Autowired
public GenericRepositoryRestExceptionHandler(MessageSource messageSource) {
super(messageSource);
// TODO Auto-generated constructor stub
}
@ResponseBody
@ExceptionHandler(Exception.class)
ResponseEntity<?> handleException(Exception e) {
// return response(HttpStatus.CONFLICT, 40902, e.getMessage());
return response(HttpStatus.CONFLICT, 40902, e.getMessage(), e.getCause() + "", e.getClass() + "");
}
private ResponseEntity<RestError> response(HttpStatus status, int code, String msg) {
return response(status, code, msg, "", "");
}
private ResponseEntity<RestError> response(HttpStatus status, int code, String msg, String devMsg, String moreInfo) {
return new ResponseEntity<>(new RestError(status, code, msg, devMsg, moreInfo, null), status);
}
}
public class CORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
System.out.println("Filtering on...........................................................");
SecurityContext ctx = SecurityContextHolder.getContext();
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
【问题讨论】:
-
如果从
RequestMapping注释中省略consumes属性有什么区别? -
@dnault 如果我忽略它或离开它,则同样的行为
-
@SotiriosDelimanolis 很抱歉回复晚了,开会了,但我编辑了帖子以显示配置文件
标签: java spring spring-mvc postman media-type