rest - 为什么有时会绕过我的控制器?
问题描述
我有一个 spring web 项目,带有一个用于编辑客户详细信息的控制器。
@Controller
@RequestMapping("/customers")
public class CustomerController {
@Autowired
CustomerService customerService;
@RequestMapping(value = {"/", ""}, method = RequestMethod.PUT)
public AjaxResponse updateCustomer(
@RequestBody Customer customer
) {
// Update the customer in the service
}
}
执行 ajax 调用的 javascript
const customer = {/* get customer info from page */};
$.ajax({
url: `${contextPath}/customers`
, method: "POST"
, accept: "application/json"
, contentType: "application/json"
, dataType: "json"
, data: JSON.stringify(customer)
, beforeSend: function() {
}
, complete: function() {
}
, success: function(ajaxResponse) {
if (ajaxResponse.status !== "OK") {
return;
}
// update all references on the screen
}
, error: function(xhr, status, error) {
// log error
}
});
请注意,控制器正在使用 aRequestMethod.PUT
并且 ajax 正在使用, method: "POST"
这给了我错误POST http://localhost:8080/hub/customers 405 (Method Not Allowed)
并且响应头包含Allow: PUT
,这完全没问题。它告诉我请求将发送到我的控制器。
如果我将 ajax 更改为, method: "PUT"
,我得到PUT http://localhost:8080/hub/customers 404 (Not Found)
. 当我检查响应时,/hub/WEB-INF/views/customers.jsp The requested resource is not available.
注意到/views/customers.jsp
这似乎来自 InternalResourceViewResolver。
从我的 dispatcher-servlet.xml
<beans:bean id="tilesViewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<beans:property name="viewClass">
<beans:value>org.springframework.web.servlet.view.tiles3.TilesView
</beans:value>
</beans:property>
<beans:property name="order">
<beans:value>1</beans:value>
</beans:property>
</beans:bean>
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix">
<beans:value>/WEB-INF/views/</beans:value>
</beans:property>
<beans:property name="suffix">
<beans:value>.jsp</beans:value>
</beans:property>
<beans:property name="order">
<beans:value>#{tilesViewResolver.order+1}</beans:value>
</beans:property>
</beans:bean>
所以似乎当我的ajax方法和RequestMethod不一样时,它会进入UrlBasedViewResolver,但是当它们相同时,它会绕过它并进入InternalResourceViewResolver。我不明白为什么。
解决方案
ajax 调用通常适用于处理 JSON、XML 等响应而不是视图。因此,如果您将控制器更改为@RestContoller
from @Controller
,这应该可以工作。
推荐阅读
- regex - 正则表达式 - 查找和替换变得过于贪婪
- c# - Entity Framework Core:如何忽略 DbSet Find 方法的QueryFilters
- apache-spark - k8s 上的 Spark 无法向 ECK 进行身份验证
- javascript - 来自 Web API 的空白请求、状态和错误
- java - 如何通过相似性比较字符串而不忽略拼写错误?
- excel - 在第一行搜索一个值,然后获取整个列范围
- javascript - 在父亲的构造函数中获取子类名?
- r - 在文本中读取带有段落和转义字符的 csv 文件
- r - 替换 observeEvent() 以在闪亮的应用程序中恢复自动功能
- docker - Docker 容器没有停止