第一次在这里发帖……但我在许多教程、SO 帖子和文档中找不到解决方案。
使用以下命令创建 Spring MVC REST webapp:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.8</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.8</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.6</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.7</version>
</dependency>
我的控制器是
@Controller
public class HomeController {
@RequestMapping(value = "/login", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
@ResponseBody
public String login(@RequestBody Login login) {
if (login != null) {
logger.debug(login.toString());
} else {
logger.error("Null Login JSON received!");
}
return new Login();
}
private class Login {
String username;
String password;
..}
我正在尝试通过以下方式以编程方式配置它:
@Configuration
@EnableTransactionManagement
@EnableWebMvc
@ImportResource("classpath:applicationContext.xml")
@PropertySource("classpath:application.properties")
public class ApplicationContext {
@Bean
public MappingJacksonJsonView mappingJacksonJsonView() {
MappingJacksonJsonView mappingJacksonJsonView = new MappingJacksonJsonView();
return mappingJacksonJsonView;
}
@Bean
public ContentNegotiatingViewResolver contentNegotiatingViewResolver() {
Map<String, String> mediaTypes = new HashMap<String, String>();
mediaTypes.put("json", "application/json");
org.springframework.web.servlet.view.ContentNegotiatingViewResolver contentNegotiatingViewResolver = new ContentNegotiatingViewResolver();
contentNegotiatingViewResolver.setMediaTypes(mediaTypes);
return contentNegotiatingViewResolver;
}
@Bean
public org.codehaus.jackson.map.ObjectMapper objectMapper() {
org.codehaus.jackson.map.ObjectMapper objectMapper = new org.codehaus.jackson.map.ObjectMapper();
return objectMapper;
}
}
但是当我通过 AJAX 或 Firefox RESTClient 发送请求时:
{"username": "aname", "password" : "ahack"}
我收到消息:
"NetworkError: 415 Unsupported Media Type - http://localhost:8080/edm/login"
我真的很感激任何指示,这个让我很难过。