【发布时间】:2014-09-03 09:11:45
【问题描述】:
我正在使用spring mvc设置一个rest api,并且大部分配置都是通过spring boot项目自动设置的。在前端,我使用 angularjs 和他们的 $http 模块向服务器发出 ajax 请求以获取资源。资源 url 在我的控制器类中定义,但只有 GET url 被匹配。我试过 PUT 和 POST 但它们分别返回 405 方法不允许和 403 禁止。
我的控制器是这样的
@Controller
@RequestMapping("/api/users")
public class UserController {
@Inject
UserService svc;
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public List<User> home() {
return svc.findAll();
}
@RequestMapping(method = RequestMethod.GET, value = "/{id}")
@ResponseBody
public User findById(@PathVariable long id){
return svc.findById(id);
}
@RequestMapping(method = RequestMethod.PUT, value="/{id}")
@ResponseBody
public User updateUser(@PathVariable long id, @RequestBody User user){
Assert.isTrue(user.getId().equals(id), "User Id must match Url Id");
return svc.updateUser(id, user);
}
}
对与 url 不匹配的服务器的请求看起来像这样
$http({
url: BASE_API + 'users/' + user.id,
method: 'PUT',
data:user
})
这会向 localhost:8080/api/users/1 生成一个 PUT 请求,并且服务器会使用 405 Method Not Allowed 响应代码进行响应。
当服务器收到对 localhost:8080/api/users/1 的 HTTP GET 请求时,正确处理相同的请求映射但带有 RequestMethod.GET
任何见解都会有帮助。
PS 如果需要,包含的 Spring Boot 依赖项是
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
谢谢
【问题讨论】:
标签: java spring spring-mvc spring-boot