为什么我的Ajax调用刷新页面? (即再次调用servlet)

时间:2010-12-18 02:04:50

标签: java ajax rest glassfish jax-rs

我正在使用Java学习RESTful Web服务。 我的环境使用Netbean和GlassFish v3。

我有一个页面网址/inventoryList,它是在web.xml中映射到InventoryApp.java servlet的URL

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
    <servlet>
        <servlet-name>inventory servlet</servlet-name>
        <servlet-class>local.test.servlet.InventoryApp</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>inventory servlet</servlet-name>
        <url-pattern>/inventoryList</url-pattern>
    </servlet-mapping>
</web-app>

在servlet中,它从DB获取库存项信息列表并显示到JSP页面。

inventory.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

        <script type="text/javascript">

        function ajaxGet(inventoryId) {
            alert(inventoryId);
            var xmlHttp = new XMLHttpRequest();
            xmlHttp.onreadystatechange = function() {

                alert('sigh');

                if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                    alert('ready 4');
                    alert('After ready4 ===> ' + xmlHttp.responseText);

                    displayInventoryHtml(xmlHttp);

                }
            }
            var url = "resources/inventory/" + inventoryId;
            xmlHttp.open("GET", url, true);
            xmlHttp.send(null);
        }

        function displayInventoryHtml(responseAjax) {
            document.getElementById('inventoryItem').innerHTML = responseAjax.responseText;
        }

        </script>

    </head>
    <body>
        <h1>Inventory page</h1>

        <table border="1" cellspacing="1" cellpadding="5">
            <th>id</th>
            <th>amount</th>
            <c:forEach items="${inventoryList}" var="inv" >
                <tr>
                    <td>${inv.id}</td>
                    <td><a href="" onclick="ajaxGet(${inv.id})">${inv.amount}</a></td>
                </tr>
            </c:forEach>
        </table>
        <hr />
        <div id="inventoryItem">
        </div>


    </body>
</html>

如您所见,inventory.jsp将成功输出库存物品清单。

到目前为止一切顺利。

在这里,我将库存量值的输出作为Ajax调用的链接。

<td><a href="" onclick="ajaxGet(${inv.id})">${inv.amount}</a></td>

它调用HTTP GET methodREST service(下面显示的代码)将获得指定id(数据库主id)的库存数据,并将Ajax responseText放入div(id = inventoryItem)

InventoryResource.java

package local.test.jaxrs;

import java.util.List;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import local.test.dao.InventoryDao;
import local.test.session.Inventory;

@Path("/inventory")
public class InventoryResource {
    @Context
    private UriInfo context;

    /** Creates a new instance of InventoryResource */
    public InventoryResource() {
    }


    @Path("{inv_id}")
    @GET
    @Produces("text/html")
    public String getJson(@PathParam("inv_id") String inventory_id) {
        System.out.println("GET is being handled");

        Inventory invBean = new Inventory(Integer.valueOf(inventory_id));
        InventoryDao invDao = new InventoryDao();
        List<Inventory> inv = invDao.findById(invBean);

        String html = "<b>" + inv.get(0).getId() + "</b><br /><b>" + inv.get(0).getAmount() + "</b><br />";

        return html;

    }
}//end class

当我测试这段代码时,一切正常。 Ajax成功获取数据并插入HTML DIV标记,库存数据显示半秒并消失。

使用firebug并查看glassfish v3 server log,我想到最后,它正在调用InventoryApp.java servlet AGAIN,导致页面重定向到/ inventoryList < / p>

我知道Ajax是部分请求,不应该导致页面刷新。

我现在已经在这里堆了几天了,有人能给我一些暗示会发生什么事吗? 我不确定将servlet和web.xml与REST混合是否可行。

仅供参考,我的 InventoryApp.java servlet代码

package local.test.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import local.test.dao.InventoryDao;
import local.test.session.Inventory;


@WebServlet(name="InventoryApp", urlPatterns={"/InventoryApp"})
public class InventoryApp extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

        } finally { 
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        InventoryDao invDao = new InventoryDao();
        List<Inventory> invList =  invDao.findAll();

        //this list looks ok...
        System.out.println("================= do get servelt ===" + invList.get(0));

        request.setAttribute("inventoryList", invList);
        request.getRequestDispatcher("inventory.jsp").forward(request, response);

        //processRequest(request, response); //commented not sure what it is..
    } 
}//end class

1 个答案:

答案 0 :(得分:4)

<a href="" onclick="ajaxGet(${inv.id})">${inv.amount}</a>

删除href属性

<a onclick="ajaxGet(${inv.id})">${inv.amount}</a>

或取消促销点击事件

<a href="" onclick="ajaxGet(${inv.id}); return false;">${inv.amount}</a>