【问题标题】:JSON request with JQuery/Ajax with Spring使用 JQuery/Ajax 和 Spring 的 JSON 请求
【发布时间】:2012-05-02 10:49:34
【问题描述】:

我对 JSON/Spring MVC 非常陌生,我正在尝试获取一个简单的 AJAX 调用 Spring MVC 控制器示例 - 但我一直返回错误 400 - 错误请求。

在网上搜索后,我发现这通常是由于没有设置适当的内容类型造成的 - 但[我相信]我已经这样做了。

这是我的 AJAX 调用:

    //validate the object
    var urlString = "/ajax/add/";

    $.ajax({
        type:"POST",
        url: urlString,
        contentType: "application/json; charset=utf-8",
        dataType: "json", 
        data: {value1: 'apples', value2 : 'oranges'},
        success: function(result){
            alert("success");
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert("error:" + textStatus + " exception:" + errorThrown);
        }

    }) ;

还有我的控制器:

@Controller
itpublic class AddController {

private static Logger m_log = null;

@RequestMapping(value = "/ajax/add")
public String handle(@RequestBody String json){

    DummyClass dummyRequest;
    try {

        ObjectMapper mapper = new ObjectMapper();
        dummyRequest = mapper.readValue(json, DummyClass.class);
        m_log.info("Value1: " + dummyRequest.getValue1());
        m_log.info("Value2: " + dummyRequest.getValue2());
    }  catch (Exception e) {

    }
    finally{


    }
    return "called";
}

谁能帮帮我?

编辑

这是我用来配置 Spring 的上下文:

 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="com.project.do" />

<!--<mvc:annotation-driven/> -->

<bean class="com.project.do.interceptors.handler.mapping.HandlerInterceptorAnnotationAwareHandlerMapping "/>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

<bean class="com.project.do.viewresolver.ProjectViewResolver" >
    <property name="tilesResolver" ref="tilesResolver" />
    <property name="jspResolver" ref="jspResolver" />
</bean>

<bean id="tilesResolver" class ="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" />
    <property name="order" value="2" />
</bean>

<bean id="jspResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
    <property name="order" value="3" />
</bean>

<bean id ="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
    <property name="definitions" value="/WEB-INF/tiles/tiles.xml" />
    <property name="preparerFactoryClass" value="org.springframework.web.servlet.view.tiles2.SpringBeanPreparerFactory"/>
</bean>

<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/javascript/**" location="/javascript/" />
<mvc:resources mapping="/scripts/**" location="/scripts/" />
<mvc:resources mapping="/styles/**" location="/styles/" />
<mvc:resources mapping="/help/**" location="/help/" />

<!-- <mvc:view-controller path="/" view-name="welcome"/> -->

我应该注意到我在 com.project.do.working 包中有一个带有 Ajax 的工作控制器,但是带有 Ajax 和 JSON 的非工作控制器在同一个包 com.project.do.not.working 中

【问题讨论】:

  • 你是如何配置 Spring 的?您能否编辑问题并添加配置详细信息(可能是 XML 文件,除非您使用较新的 @Configuration 样式)。
  • 我附上了用于配置 Spring 的上下文。谢谢!
  • 您可以尝试用@RequestParam String value1, ..(at)RequestParam String value2 替换您的 RequestBody 吗?并且您确实希望在 ReequestMapping 中有 method = RequestMethod.POST (如 raddykrish 所述)。

标签: jquery ajax json spring-mvc


【解决方案1】:
@Controller
@RequestMapping("/employee/add.htm")
public class EmployeeController {
    @RequestMapping(method = RequestMethod.POST)
    public @ResponseBody
    Employee add(HttpServletRequest request, HttpServletResponse response)
            throws Exception {


    }
}

【讨论】:

    【解决方案2】:

    我认为您的请求映射没有将 RequestMethod 作为 POST。我猜默认情况下它会接受一个 get 请求,但你的 AJAX 是一个 POST 请求。尝试如下更改

    @RequestMapping(value = "/ajax/add", method = RequestMethod.POST)
    public String handle(@RequestBody String json){
    }
    

    【讨论】:

    • 我选择这个作为答案,因为它看起来确实是必需的。实际上我最初对此进行了编码,但是当事情不工作时开始剥离片段。大部分问题似乎纯粹是环境问题——没有人能帮我解决这个问题。
    • @kjl,我面临着类似的issue,你能告诉我真正的问题是什么吗?它可能对我有帮助
    猜你喜欢
    • 2013-05-12
    • 2014-05-07
    • 1970-01-01
    • 2015-11-25
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    相关资源
    最近更新 更多