首页 > 解决方案 > 为什么有时会绕过我的控制器?

问题描述

我有一个 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。我不明白为什么。

标签: restspring-mvc

解决方案


ajax 调用通常适用于处理 JSON、XML 等响应而不是视图。因此,如果您将控制器更改为@RestContollerfrom @Controller,这应该可以工作。


推荐阅读