【问题标题】:What does my Servlet have that my JSP is missing?我的 Servlet 有什么让我的 JSP 丢失了?
【发布时间】:2010-10-18 20:50:44
【问题描述】:

我目前正在通过 Sam's Teach Yourself JSP 工作。在一章中,我们编写了一个粗略的购物车应用程序,它使用 Servlet 实现各种功能。在第 14 章中,我们使用 bean 将大部分 servlet 替换为 JSP。

由于某种我无法理解的原因,我的 JSP 无法正常工作。


这是函数式servlet


/**
 * 
 */
package hu.flux.shoppingcart;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * @author Brian Kessler
 *
 */
public class AddToShoppingCartServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @SuppressWarnings("deprecation")
    public void service (HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException
        {
            // First get the item values from the request.
            String productCode = request.getParameter("productCode");
            String description = request.getParameter("description");
            int quantity = Integer.parseInt(request.getParameter("quantity"));
            double price = Double.parseDouble(request.getParameter("price"));

            // Now create an item to add to the cart.
            Item item = new Item(productCode, description, price, quantity);
            HttpSession session = request.getSession();
            ShoppingCart cart = ShoppingCart.getCart(session);

            cart.addItem(item);

            // Now display the cart and allow the user to check out or order more items.
            response.sendRedirect(
                    response.encodeRedirectUrl(ShoppingCart.SHOPPING_CART_PATH + "/ShowShoppingCart.jsp"));
        }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}


这是功能失调的 JSP


<%-- Get a reference to the shopping cart --%>
<jsp:useBean id="cart" class="hu.flux.shoppingcart.ShoppingCart" scope="session" />

<%-- Create an item object --%>
<jsp:useBean id="item" class="hu.flux.shoppingcart.Item" scope="page" />

<%-- Copy the request parameters into the item --%>
<jsp:setProperty name="item" property="*"/>

<%-- Add the item to the shopping cart --%>
<% cart.addItem(item); %>

<%--Display the product catalog again --%>
<jsp:forward page="ShowShoppingCart.jsp" />

为了让事情变得神秘,没有显示任何错误。最后一行肯定可以正常工作,因为它成功转发到 ShowShoppingCart.jsp,但是购物车是空的。

经过实验,我得出的结论是,无论发生什么问题,都必须在调用时或之后发生。我知道这一点是因为我将 ShowShoppingCart.jsp 上的一些代码移到了 AddToShoppingCart.jsp 上,并且(经过一些调试),购物车将在 AddToShoppingCart.jsp 上正确显示

因为它可能有助于理解出了什么问题,这里还有两段代码:

*这里是jsp调用的页面:forward page="ShowShoppingCart.jsp" *

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="hu.flux.shoppingcart.*"%>
<%
    String shoppingCartSerialization = "";
    ShoppingCart cart = ShoppingCart.getCart(session);
    shoppingCartSerialization = cart.getSerialization();  
    Cookie cookie = new Cookie ("ShoppingCart", shoppingCartSerialization);
    cookie.setMaxAge(999999999);
    response.addCookie (cookie);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="#ffffff">
<div><jsp:include page="DisplayShoppingCart.jsp" flush="true" /></div>
<form action="<%=ShoppingCart.SHOPPING_CART_PATH %>/Checkout.jsp"
        method="post" >
    You may <a 
        href="<%=ShoppingCart.SHOPPING_CART_PATH %>/ShowProductCatalog2.jsp"
    >continue shopping</a> or
    <input type="submit" value="Check Out">
</form>
<br/><br/><br/><hr/>
<form action="TerminateShoppingSessionServlet" method="post"><input
    type="submit" value="Terminate Session"></form>
</body>
</html>

*这里是jsp调用的页面:include page="DisplayShoppingCart.jsp" flush="true" *

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="hu.flux.shoppingcart.*"%>
<%@ page import="java.text.*"%>
<%@ page import="java.util.*"%>
<%-- Show the header with the shopping cart item --%>
<img id="cart_image"
    src="/SamsTeachYourselfJSP/ShoppingCart/images/cart4.png" />
<h1>Shopping Cart</h1>

<% // Get the current shopping cart from the user's session.
    ShoppingCart cart = ShoppingCart.getCart(session);

    // Get the items from the cart.
    Vector<Item> items = cart.getItems();

    // If there are no items, tell the user that the cart is empty.
    if (items.size() == 0) {%><strong>Your shopping cart is empty.</strong>
<%}
    else
    {
        %>
<%-- Display the header for the shopping cart table --%>
<br />
<table border="4">
    <tr>
        <th>Description</th>
        <th>Quantity</th>
        <th>Price</th>
    </tr>
    <%
                int numItems = items.size();

                // Get a formatter to write out currency values.
                NumberFormat currency = NumberFormat.getCurrencyInstance();
                for (int i=0; i<numItems; i++)
                {
                    Item item = (Item)items.elementAt(i);
                    out.print (item.printShoppingCartTableRow(currency, 
//                              "/SamsTeachYourselfJSP/ShoppingCart/RemoveItemServlet?item="+i)
                                "/SamsTeachYourselfJSP/ShoppingCart/RemoveItem.jsp?item="+i)
                            );
                }
              %>
</table>
<%  
    }
%>

任何想法我忽略了什么?

【问题讨论】:

  • 也许错误信息会有所帮助
  • 抱歉,没有错误信息。系统一直在运行,只是在使用 JSP 时不会将任何商品添加到购物车中。

标签: java jsp session servlets javabeans


【解决方案1】:

我发现了问题。

以前,我为保存我的 ShoppingCart 的变量使用了一个名称“cart”。

我为保存我的 ShoppingCart 的会话属性使用了第二个名称“ShoppingCart”。

使用Beans,这些名称必须相同,所以我需要更改

<jsp:useBean id="cart" class="hu.flux.shoppingcart.ShoppingCart" scope="session" />

<jsp:useBean id="ShoppingCart" class="hu.flux.shoppingcart.ShoppingCart" scope="session" />

同样:

<% cart.addItem(item); %>

<% ShoppingCart.addItem(item); %>

为了约定(以小写字母开头的变量),最好改为更改对会话属性名称的所有其他引用,但这适用于“快速修复”。

【讨论】:

    【解决方案2】:

    尝试以下操作(假设 jsp 位于根文件夹 (webapp) 中):

    final RequestDispatcher rd = request.getRequestDispatcher("ShowShoppingCart.jsp");
    rd.forward(request, response);
    

    而不是重定向。我认为重定向会导致浏览器在获取对指定 url 的响应时发出新请求。

    【讨论】:

    • servlet 版本实际上是工作版本。该请求工作正常。如果沿着这条线有什么可能是 造成了问题?
    • 哦,那我误读了这个问题。您是否检查过是否可以访问转发页面上的项目,例如: ${item} ?我不确定项目的范围可能应该是请求而不是页面。
    • 在前进页面上,购物车是空的,所以尽管有 应该已将项目添加到页面。在“ShowShoppingCart.jsp”上,商品只能通过购物车访问,而购物车又应该是会话的属性。
    • hm.. 好吧,我最初的想法是,这可能是因为项目的范围是它被添加但在转发后超出范围的页面。
    • 我认为您可能遇到了范围问题。我一直在玩代码,我发现如果我绕过 页面并在转发页面上包含来自 的代码,我实际上可以显示购物车。但是还有另一个异常情况,因为收到的商品显示数量为 0 ......所以不知何故数量丢失了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 2017-04-27
    • 2015-03-22
    相关资源
    最近更新 更多