java 在 servlet 的 jsp 文件中显示购物车中的商品
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17934676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display the items in the cart in a jsp file from servlet
提问by Leon
I am building a E-Commerce simple solution in java and i am stucked in a critical point. I am not able to display the correct items. I am using a servlet that has a doGet a shoppingcart class, a products class and viewcart.jsp file. To pass the items between servlets i am using the setAttribute of context. Here are my files i have build so far. Can anyone help me fix this problems? Every time i press add to car it adds the element but look like all the previous elements get overwritten by the last one i added.
我正在用 Java 构建一个电子商务简单的解决方案,但我陷入了一个关键点。我无法显示正确的项目。我正在使用具有 doGet 购物车类、产品类和 viewcart.jsp 文件的 servlet。为了在 servlet 之间传递项目,我使用了上下文的 setAttribute。这是我迄今为止构建的文件。谁能帮我解决这个问题?每次我按添加到汽车时,它都会添加元素,但看起来所有以前的元素都被我添加的最后一个元素覆盖了。
package com.kd.ecommerce;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class addtocart
*/
@WebServlet("/addtocart")
public class addtocart extends HttpServlet {
private static final long serialVersionUID = 1L;
private shoppingcart shop = new shoppingcart();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext thisContext = getServletContext();
String name = request.getParameter("product");
Connection cn = DBConnect.getInstance();
try {
Statement st = cn.createStatement();
ResultSet rs = st.executeQuery("select * from inventory where name = '"+name+"' LIMIT 1");
while(rs.next()){
Products p = new Products(rs.getString(2),rs.getString(3),rs.getString(4),rs.getFloat(5));
System.out.println(p.getName()+":"+ p.getPrice());
shop.ins(p);
thisContext.setAttribute("shop", shop.getIt());
for(int i = 0; i< shop.getIt().size(); i++){
System.out.println(shop.getIt().get(i)+":"+ shop.getIt().get(i).getPrice());
}
response.sendRedirect("inventory.jsp?addedto=success");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Products.java
产品.java
package com.kd.ecommerce;
public class Products {
private static String name;
private static Float price;
private static String desc;
private static String img;
public Products(String n, String d, String i,Float p){
name = n;
price = p;
desc = d;
img = i;
}
public String getName(){
return name;
}
public Float getPrice(){
return price;
}
public String getImage(){
return img;
}
public String getDesc(){
return desc;
}
}
shoppingcart.java
购物车.java
package com.kd.ecommerce;
import java.util.ArrayList;
public class shoppingcart {
private static ArrayList<Products> items;
public shoppingcart(){
items = new ArrayList<Products>();
}
public void ins(Products p){
items.add(p);
}
public void remove(Products p){
items.remove(p);
}
public int getSize(){
return items.size();
}
public ArrayList<Products> getIt(){
return items;
}
}
viewcart.jsp
viewcart.jsp
<jsp:include page="menu.jsp"></jsp:include>
<%
ServletContext sc = getServletConfig().getServletContext();
if(sc.getAttribute("shop") != null){
ArrayList<Products> it = (ArrayList<Products>)sc.getAttribute("shop");
out.println(it);
for(int i = 0; i< it.size(); i++){
out.println("<span class='price'>"+it.get(i).getPrice()+"</span>");
}
}else{
out.println("<span class='empty'>Shopping cart empty</span>");
}
%>
-- EDIT --
- 编辑 -
My new viewcart.jsp using sessions
我的新 viewcart.jsp 使用会话
<%
if(session.getAttribute("shop") != null){
shoppingcart sh = (shoppingcart)session.getAttribute("shop");
ArrayList<Products> pd = sh.getIt();
for(int i = 0; i< pd.size(); i++){
out.println("<span class='price'>"+pd.get(i).getPrice()+"</span>");
}
}else{
out.println("<span class='empty'>Shopping cart empty</span>");
}
%>
回答by Mindle Hastings
What's causing your problem is that you have made the shoppingcartan instance variable in your Servlet. That means that every HTTP request that your Servlet handles is sharing the same shoppingcart. To fix this, move the following line from the class definition code:
导致您出现问题的原因是您已将购物车设为 Servlet 中的实例变量。这意味着您的 Servlet 处理的每个 HTTP 请求都共享同一个购物车。要解决此问题,请从类定义代码中移动以下行:
private shoppingcart shop = new shoppingcart();
And move it into the doGetmethod before the following line:
并将其移动到以下行之前的doGet方法中:
shop.ins(p);
The doGetmethod will then contain the following two lines:
然后doGet方法将包含以下两行:
shoppingcart shop = new shoppingcart();
shop.ins(p);
You may even consider giving the shoppingcartclass a constructor that takes a Productsobject as parameter and sets the items in the constructor. Then you could combine those two lines into one, as follows:
您甚至可以考虑为购物车类提供一个构造函数,该构造函数将Products对象作为参数并在构造函数中设置项目。然后你可以将这两行合二为一,如下所示:
shoppingcart shop = new shoppingcart(p);
It's a common mistake to define objects as instance variables in Servlets. Just remember that every HTTP call to your servlet will share the instance variables. If you're wanting to store information for specific users, consider putting them in the session.
在 Servlet 中将对象定义为实例变量是一个常见的错误。请记住,对 servlet 的每个 HTTP 调用都将共享实例变量。如果您想为特定用户存储信息,请考虑将他们放入会话中。
----EDIT----
- - 编辑 - -
I didn't actually answer the question, as it turns out. To keep a running tally of the added items, you have to save the items to a place that will not be shared by anyone--a place only the specific user will have his data saved to. The session is the place that was specifically designed for this purpose. You can use the session like this in your doGetmethod:
事实证明,我实际上并没有回答这个问题。要保持添加项目的运行记录,您必须将项目保存到任何人都不会共享的地方——只有特定用户将其数据保存到的地方。会议是专门为此目的而设计的。您可以在doGet方法中使用这样的会话:
HttpSession session = request.getSession(true);
shoppingcart shop = (shoppingcart)session.getValue("shop");
if(shop == null) {
shop = new shoppingcart();
session.putValue("shop", shop);
}
shop.ins(p);
The line that gets the value from the session returns whatever object is stored with the key "shop". If this is the first item the user is adding, no shopping cart will have been saved yet, so shopwill be null. That's why we do the null check; to create a shopping cart and then associate it with the "shop" key so that the next time the user adds an item, a shopping cart will have been associated with the key "shop".
从会话中获取值的行返回使用键“shop”存储的任何对象。如果这是用户添加的第一件商品,则尚未保存购物车,因此shop将为null。这就是我们进行空检查的原因;创建一个购物车,然后将它与“shop”键相关联,以便用户下次添加商品时,购物车将与键“shop”相关联。
Once we have a shoppingcartthat is associated with the "shop" key for that particular user, you should see the items being added to that same cart object as multiple submissions are made.
一旦我们有一个购物车是与该特定用户的“商店”键关联,你应该看到正在向同车对象的项目,如多次提交制成。