【问题标题】:jQuery post can't get entity object as jsonjQuery post 无法将实体对象作为 json
【发布时间】:2012-01-07 10:01:52
【问题描述】:

我需要从我的控制器中获取我的“评论”(存储在 DAO 中)对象并将其显示在我的 JSP 中,但每次我看到来自错误块的错误消息时。

为什么会发生这种情况,我该怎么办?

我的代码逻辑如下:

  1. 点击“回复”按钮后,表单中的数据将发送到我的控制器。
  2. 控制器将数据保存在数据库中并返回“评论”实体。
  3. 我在我的 JSP 页面中获得了这个“评论”实体并将其用于在页面上发布。

但是我从错误块而不是从成功块中得到错误消息。

这是我的表格:

<form id="comment_${comment.getCommentId()}">
    <textarea class="textarea" rows="10" name="text"></textarea>
    <input type="hidden" name="bookId" value="${book.getBookId()}" />
    <input type="hidden" name="parentId" />
    <input type="hidden" name="commentId" value="${comment.getCommentId()}" /><br />
    <input type="button" class="button" value="Reply" id="submit_${comment.getCommentId()}" onclick="ajaxsubmit(this.id)"/>
</form>

这是我的脚本:

<script type="text/javascript">
    function ajaxsubmit(buttonId){
    var formId = document.getElementById(buttonId).parentNode.id;
    var dataString = $("#" + formId).serialize();

    $.ajax( {
        url: "ajaxcomment.htm",
        type: "post",
        data: dataString,
        dataType: "json",
        success: function(data) {
            alert(data.getCommentAdded());
        },
        error: function() {
            alert("error");
        }
    } );
}

这是我的控制器

@RequestMapping(value = "ajaxcomment.htm", method = RequestMethod.POST)
public @ResponseBody Comment ajaxcomment(
        HttpServletRequest httpServletRequest,
        @RequestParam(value = "bookId", required = false) Long bookId,
        @RequestParam(value = "parentId", required = false) Long parentId,
        @RequestParam(value = "commentId", required = false) Long commentId,
        @RequestParam(value = "text", required = true) String text) {

    String username = httpServletRequest.getRemoteUser();
    User user = userDao.getUserByUsername(username);

    Comment comment = new Comment();

    // DAO logic

    commentDao.addComment(comment);
    return comment;
}

这是我的“评论”实体:

@Entity @Table(name = "COMMENT") public class Comment implements Serializable {

@Id
@GeneratedValue
@Column(name = "COMMENT_ID", nullable = false)
private Long commentId;

@Column(name = "COMMENT_TEXT", length = 512, nullable = true)
private String commentText;

@Column(name = "COMMENT_ADDED", length = 128, nullable = true)
@Temporal(TemporalType.TIMESTAMP)
private Date commentAdded;

@ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
@JoinColumn(name = "BOOK_ID")
private Book book;

@ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
@JoinColumn(name = "PARENT_ID")
private Comment parentComment;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "parentComment")
@OrderBy("commentAdded")
private Collection<Comment> subcomments;

public void setCommentText(String commentText) {
    this.commentText = commentText;
}
public String getCommentText() {
    return this.commentText;
}

// other getters and setters are public too

这是我的 applicationContext.xml:

<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<mvc:annotation-driven />
<context:component-scan base-package="com.demo"/>
<context:component-scan base-package="com.demo.service"/>
<context:annotation-config />


<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jacksonMessageConverter" />
        </list>
    </property>
</bean>

<bean id="exceptionMessageAdapter"
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
    <property name="messageConverters">
        <list>
            <!-- Support JSON -->
            <ref bean="jacksonMessageConverter" />  
        </list>
    </property>
</bean>

【问题讨论】:

    标签: json jsp jquery spring-mvc


    【解决方案1】:

    可能是您在表单中设置了 value="${book.getBookId()}" 之类的值,而不是 value="${book.bookId}"

    换句话说,您必须通过引用 bean 中的字段名称(实体或其他)来使用表达式语言,而不是尝试直接使用该字段的 getter。

    【讨论】:

    • 我知道,但“评论”实体中的所有字段都是私有的。
    • 但你可以有公共吸气剂
    • 所有的 getter 和 setter 仍然是公开的。
    【解决方案2】:

    有效。

    我已经更新了我的控制器方法(处理程序):

    @Autowired private DAOComment commentDao;
    
    @RequestMapping(value = "ajaxcomment.htm", method = RequestMethod.POST)
    public @ResponseBody String ajaxcomment(
        HttpServletRequest httpServletRequest,
        @RequestParam(value = "bookId", required = false) Long bookId,
        @RequestParam(value = "parentId", required = false) Long parentId,
        @RequestParam(value = "commentId", required = false) Long commentId,
        @RequestParam(value = "text", required = true) String text) {
    
    String username = httpServletRequest.getRemoteUser();
    User user = userDao.getUserByUsername(username);
    
    Comment comment = new Comment();
    
    // DAO logic
    
    commentDao.addComment(comment);
    return  "{\"id\":\""    + comment.getCommentId() + "\"," +
         "\"username\":\""  + comment.getUser().getUsername() + "\"," +
         "\"text\":\""      + comment.getCommentText() + "\"," +
         "\"added\":\""     + comment.getFormattedDate() + "\"}";
    }
    

    我使用 \" 而不是 ',因为 JSON.parse() 不会解析像 'param':'value'"param":"value" 这样的字符串。

    更新脚本:

    <script type="text/javascript">
        function ajaxsubmit(buttonId, className){
            var formId = document.getElementById(buttonId).parentNode.id;
            var dataString = $("#" + formId).serialize();
            $.ajax( {
                url: "ajaxcomment.htm",
                type: "post",
                data: dataString,
                dataType: "text",
                success: function(data) {
                    var response = JSON.parse(data);
    
                    //This's it.
                    alert(response.id);
    
                },
                error: function() {
                    alert("Error has occured.");
                }
            } );
        }
    </script>
    

    【讨论】:

      猜你喜欢
      • 2012-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 2021-11-23
      • 2016-11-15
      相关资源
      最近更新 更多