大家好。
我对 servlet 中的抽象超类和子类有些困惑:
我有抽象的servlet超类:
public abstract class CatalogPage extends HttpServlet {
public CatalogPage() {
super();
}
private CatalogItem[] items;
private String[] itemsID;
private String title;
public void setItems(String[] itemsID) {
this.itemsID = itemsID;
items = new CatalogItem[itemsID.length];
for(int i=0; i<items.length; i++) {
items[i] = Catalog.getItem(itemsID[i]);
}
}
public void setTitle(String title) {
this.title = title;
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
if (items == null) {
response.sendError(response.SC_NOT_FOUND, "Missing Items");
return;
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</H1>");
CatalogItem item;
for(int i=0; i<items.length; i++) {
item = items[i];
if(item == null) {
out.println("<FONT COLOR=\"RED\">" +
"Unknown item ID " + itemsID[i] +
"</FONT>");
} else {
out.println();
String formURL = "OrderPage";
formURL = response.encodeURL(formURL);
out.println
("<FORM ACTION=\"" + formURL + "\">\n" +
"<INPUT TYPE=\"HIDDEN\" NAME=\"itemID\" " +
" VALUE=\"" + item.getItemID() + "\">\n" +
"<H2>" + item.getShortDescription() +
" ($" + item.getCost() + ")</H2>\n" +
item.getLongDescription() + "\n" +
"<P>\n<CENTER>\n" +
"<INPUT TYPE=\"SUBMIT\" " +
"VALUE=\"Add to Shopping Cart\">\n" +
"</CENTER>\n<P>\n</FORM>");
out.println("<HR>\n</BODY></HTML>");
}
}
}
}
和抽象超类,子类:
@WebServlet("/KidsCatalogPage")
public class KidsBooksPage extends CatalogPage {
public void init() {
String[] kbp = {"lewis001", "alexander001", "rowling001"};
setItems(kbp);
setTitle("All-Time Best Children's Fantasy Books");
}
}
如果我调用子类,KidsBooksPage
我知道它init()
首先执行初始化方法,但问题是:
是什么让我的子类KidsBooksPage
调用抽象超类CatalogPage
。这个怎么运作??能明白。请给我解释一下。
谢谢你。