• 它必须是一个公开的(public)类。已证明正确
• 它应该(不是必须)拥有一个零参数的,即默认构造函数。? 不是必须的
javabean本质还是个Java类,在他没有任何构造器的时候,系统会给他一个默认的构造器,如果自己已经给了一个有参的构造器,需要自己给定一个无参构造器,因为如果需要创建没有参数的对象的时候就会报错
• 它不应该(如果有也可以运行)有公开的实例变量。如果写成public会如何?也能运行
• 它提供setXxx()和getXxx()方法来对属性进行操作。是不是一定起名set和get?
是必须起名为set和get开头的方法来对属性进行操作
但是对于get,后面必须跟首字母大写的私有变量名称;
而对于set,后面可以跟首字母大写也可以跟首字母小写的私有变量名称
• 对于boolean类型的属性,可以使用is代替get。已证明正确
========================================================
package edu.shop.entity;
public class Item
{
private String itemId;
private String description;
private double cost;
private boolean empty;
// public Item() //这是一个默认的无参数构造函数 思考:什么时候必须拥有一个零参数的默认构造函数?
// {
//
// }
//这是一个有参数的非默认构造函数,如果已经有了一个有参的构造函数,
//则必须有一个无参的构造函数,因为如果需要创建无参的对象的时候就会报错
// public Item(String itemId)
// {
// this.itemId = itemId;
// }
//
public double getCost()
{
return cost;
}
public void setcost(double cost)
{
this.cost = cost;
}
public String getItemId()
{
return itemId;
}
public void setitemId(String itemId)
{
this.itemId = itemId;
}
public String getDescription()
{
return description;
}
public void setdescription(String description)
{
this.description = description;
}
//public Boolean getEmpty()
public Boolean isEmpty()
{
return empty;
}
public void setEmpty(Boolean empty)
{
this.empty = empty;
}
}
========================================================
package edu.shop.entity;
public class ItemOrder
{
private Item item;
private int numItems;
public ItemOrder()
{
}
public void setItem(Item item)
{
this.item = item;
}
public Item getItem()
{
return item;
}
public void setNumItems(int numItems)
{
this.numItems = numItems;
}
public int getNumItems()
{
return numItems;
}
public double getCost() //获取商品单价
{
return getItem().getCost();
}
public double getTotalCost() //获取商品总价=数量*单价
{
return getNumItems() * getCost();
}
public void cancelOrder() //取消订单
{
setNumItems(0);
}
}
========================================================
<%@ page language="java" contentType="text/html;charset=utf-8" pageEncoding="utf-8" %>
<html>
<head>
<title>TestJavaBean</title>
</head>
<body>
<!--<form action="" method="post"> -->
<form action="testJavaBean.jsp" method="post">
商品编号:<input type="text" name="itemId">
商品描述:<input type="text" name="description">
商品单价:<input type="text" name="cost">
<input type="submit" value="提交">
</form>
<%
request.setCharacterEncoding("utf-8"); //设置以utf-8编码方式获取request对象的参数值,避免产生中文乱码
%>
<jsp:useBean id="item" class="edu.shop.entity.Item"/>
<%--<jsp:useBean id="item" class="Item"/> --%>
<%--<jsp:setProperty name="item" property = "*"/> --%>
<jsp:setProperty name="item" property = "itemId"/>
<jsp:setProperty name="item" property = "description"/>
<jsp:setProperty name="item" property = "cost"/>
<jsp:setProperty name="item" property = "empty"/>
您订的商品编号是:
<jsp:getProperty name="item" property="itemId"/>
您订的商品描述是:
<jsp:getProperty name="item" property="description"/>
您订的商品单价是:
<jsp:getProperty name="item" property="cost"/>
您订的商品是否有货:
<jsp:getProperty name="item" property="empty"/>
</body>
</html>