【问题标题】:Spring 3.0 MVC Ajax exampleSpring 3.0 MVC Ajax 示例
【发布时间】:2011-04-26 21:09:42
【问题描述】:

我正在尝试向 Spring MVC 控制器发送 Ajax 请求并相应地将其映射到 Java 类:

public class Person  implements Serializable {
    private MutableLong Id = new MutableLong();
    @NotEmpty
    @Size(min = 1, max = 50)
        String FirstName=null;
        @NotEmpty
        @Size(min = 1, max = 50)
        String LastName=null;
        public Person(){}
        public long getId(){
            return this.Id.longValue();
        }
   //getters and setters
} 

然后我有发送 AJAX 请求的 JavaScript:

function loadXMLDoc(){
    if(window.ActiveXObject)
    {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(window.XMLHttpRequest)
    {
      xmlHttp=new XMLHttpRequest();
    }
    xmlHttp.onreadystatechange=handleStateChange;
    xmlHttp.open("POST","/authenticate.dlp", true);
    xmlHttp.setRequestHeader('Content-Type', 'application/json');
    param = '{\"FirstName\"=\"test\",\"LastName\"=\"test2\"}';
    xmlHttp.send(param);
}

然后是控制器本身:

@RequestMapping(value="/authenticate.dlp",method = RequestMethod.POST)
         @ResponseBody
          public String getAjax(@RequestBody Person person){
          Set<ConstraintViolation<Person>> failures = validator.validate(person);
          if(!failures.isEmpty())
    //......     
      }

服务器似乎没有响应。如果我使用 Fiddler,我会看到来自服务器的以下响应:

服务器拒绝了这个请求 因为请求实体在 请求的格式不支持 请求方法的资源 ()。

我做错了什么?

【问题讨论】:

  • 我们需要查看你的 spring appcontext 的内容

标签: java ajax spring spring-mvc


【解决方案1】:

有两个可能的原因:

  • 你忘了&lt;mvc:annotation-driven /&gt;。它会自动配置 HTTP 消息转换器以与 @RequestBody/@ResponseBody 一起使用
  • 类路径中没有Jackson JSON Processor。 Spring 要求它绑定 application/json@RequestBody

【讨论】:

  • 我添加了 Jackson JSON 处理器。现在我有以下异常 org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "FirstName" (类 com.doolloop.Person),未标记为可忽略
  • @danny:如果你的Person有对应的属性,或许你需要使用属性式大写:firstName
【解决方案2】:

只有几个其他有用的链接...查看这篇 Spring 博客文章:

http://blog.springsource.com/2010/07/22/spring-mvc-3-showcase/

以及使用@ResponseBody 的示例:

https://src.springframework.org/svn/spring-samples/mvc-showcase/

还有 ResponseEntity:

http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/http/ResponseEntity.html

@RequestMapping("/ajax/helloworld")
public ResponseEntity<String> helloworld() {
   HttpHeaders headers = new HttpHeaders();
   headers.setContentType(MediaType.APPLICATION_JSON);
   return new ResponseEntity<String>("Hello World", headers, HttpStatus.OK);
}

您可以返回一个编组对象,而不是“Hello World”。

【讨论】:

    【解决方案3】:

    这并不完全是您问题的答案,但是您以前看过 DWR 吗?它使 JS 到 Java RPC 超级简单。 http://directwebremoting.org/dwr/index.html

    【讨论】:

      猜你喜欢
      • 2012-09-14
      • 2011-08-19
      • 2014-05-23
      • 2012-06-26
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      • 2017-06-17
      • 2012-01-01
      相关资源
      最近更新 更多