如何通过URL POST到数据库

时间:2012-07-12 01:28:22

标签: spring hibernate

我正在Spring / Hibernate中编写一个处理基本投票功能的Web应用程序。我想要一个指向/ vote / {gameId}的链接,它会将该投票添加到该特定ID的数据库中。我真的不知道如何实现这个目标。这是我在控制器中尝试的内容:

@RequestMapping(value="/vote/{gameId}", method = RequestMethod.POST)
public String addVote(@PathVariable("gameId")
Integer gameId) {

    Vote vote = new Vote();
    vote.setGameId(gameId);

    voteService.addVote(vote);
    return "redirect:/games/wanted.html";
}

这是链接在jsp中显示的位置:

<c:if test="${!empty games}">
    <table>
        <tr>
            <th>Game Title</th>
            <th>Votes</th>
            <th>&nbsp;</th>
        </tr>

        <c:forEach items="${games}" var="game">
            <tr>
                <td><c:out value="${game.title}"/></td>
                <td>Placeholder</td>
                <td><a href="vote/${game.id}">Vote!</a></td>
            </tr>
        </c:forEach>
    </table>
</c:if>

当我尝试这个时虽然我得到了404错误。任何见解都会很棒。

1 个答案:

答案 0 :(得分:2)

这就是make a post call使用普通Javascript:

的方式
var url = "vote";
var params = "id=1";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);

您需要在链接的onclick中调用此方法。

另一方面,如果您使用the jQuery Javascript library

,则会更容易

对于您的特定情况,它将类似于:

$.post("vote", { id: "1" } );

或完整的jQuery答案(记得将#linkid替换为你标记的id):

$(document).ready(function() {  //this runs on page load
  // Handler for .ready() called.

   $('#linkid').click(function(event) {  //this finds your <a> and sets the onclick, you can also search by css class by type of tag
     $.post("vote", { id: "1" } );
       return false; //this is important so that the link is not followed
    });

});