Reputation: 105
Sorry to interrupt all of you.
I have a question about session.
In my case, I need to check the session has stored value or not.
If the session is not null, I want to loop the value to do comparison.
Now, I only use if statement to check the last record of book ID is repetitive or not.
But I don't know how to use loop to check there is any book ID that is repetitive or not.
Would any one provide some advice for me to acheive this goal?
Many thanks.
here is my source code:
<%@ page contentType="text/html; charset=Big5"%>
<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.lang.*"%>
<%!
public class BookInfo {
private String id;
private String name;
private int count;
public BookInfo(String id, String name, int count) {
this.id = id;
this.name = name;
this.count = count;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BookInfo other = (BookInfo) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
public String toString()
{
return " ISBN is " + getId() + " , book title is " + getName() + " & order no. is " + getCount() + "\n";
}
}
%>
<%
try {
List MyCart = (List) request.getSession().getAttribute("MyCart");
if (MyCart == null) {
MyCart = new ArrayList();
}
BookInfo book = new BookInfo("2", "C++ langauge", 1);
//BookInfo book = new BookInfo("2", "java", 1);
if (!MyCart.contains(book)) {
MyCart.add(book);
} else {
//how to loop the value stored in session?
BookInfo tmpBook = (BookInfo) MyCart.get(MyCart.indexOf(book));
tmpBook.setCount(tmpBook.getCount() + book.getCount());
}
request.getSession().setAttribute("MyCart", MyCart);
System.out.println(MyCart);
}
catch ( Exception main_error ) {
System.out.println("%%%%%%%%%%%"+main_error);
}
%>
Upvotes: 1
Views: 1176
Reputation: 5964
You shouldnt be writing java code, especially creating classes inside a JSP. Its very bad coding practice - try extracting your code to actual java files.
But to answer your question: You should see that the List object is iterable, so you can loop through it using
for(BookInfo aBook: MyCart){
//code to look at each BookInfo object here
}
Upvotes: 1