Java/JSP/Beans
Содержание
- 1 Bean property display
- 2 Here are the EmailBean properties
- 3 Beans with scriptlet
- 4 Calling a Private Method
- 5 Calling a Private Method
- 6 Getting a Property Value
- 6.1 JSP and Java beans 3
- 6.2 Please submit a valid stock symbol
- 6.3 Here is the latest value of <c:out value="${param.symbol}" />
- 6.4 JSP and Java beans (JavaBeans) 1
- 6.5 JSP and Java beans (JavaBeans) 2
- 6.6 JSP email valid check
- 6.7 Welcome
- 6.8 JSP Standard Actions: set property
- 6.9 JSP with Java bean
- 6.10 Set Property Value
- 6.11 Using a Constructor
- 7 Using a Constructor
- 8 Using a JavaBean
Bean property display
<source lang="java">
<%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %> <jsp:useBean id="emailer" class="com.jexp.EmailBean"/> <jsp:setProperty name="emailer" property="*" /> <html> <head><title>Bean property display</title></head> <body>
Here are the EmailBean properties
SMTP host: <c:out value="${emailer.smtpHost}" />
Email recipient: <c:out value="${emailer.to}" />
Email sender: <c:out value="${emailer.from}" />
Email subject: <c:out value="${emailer.subject}" />
Email content: <c:out value="${emailer.content}" />
</body>
</html>
</source>
Beans with scriptlet
<source lang="java">
<%@ page import="com.jexp.Book" %> <%
Book myBook = (Book) session.getAttribute("myBookBean"); if ( myBook == null) { myBook = new Book(); myBook.setAuthor("Joe"); session.setAttribute("myBookBean", myBook); } // end of if ()
%>
<html>
<head><title>JavaBean usage with scriptlets (1)</title></head> <body>This page creates a JavaBean if you don"t already have one.
Click to go to a page that retrieves it. </body>
</html> //useAndSet2.jsp <html>
<head><title>JavaBean usage - getProperty tag</title></head> <body>This page retrieves a JavaBean, and its properties.
JavaBean property | Value |
---|---|
id | <jsp:getProperty name="myBookBean" property="id" /> |
title | <jsp:getProperty name="myBookBean" property="title" /> |
author | <jsp:getProperty name="myBookBean" property="author" /> |
price | <jsp:getProperty name="myBookBean" property="price" /> |
</body>
</html>
</source>
Calling a Private Method
<source lang="java">
// JSP file <HTML>
<HEAD> <TITLE>Calling a Private Method</TITLE> </HEAD> <BODY>
Calling a Private Method
<jsp:useBean id="bean1" class="beans.Message" /> The message is: <jsp:getProperty name="bean1" property="message" />
<jsp:setProperty name="bean1" property="message" value="Hello again!" /> Now the message is: <jsp:getProperty name="bean1" property="message" /> </BODY>
</HTML>
/////////////////////////////////////// //Java Source Code package beans; import java.io.Serializable; public class Message implements Serializable {
private String message = "Hello from JSP!"; public void setMessage(String m) { this.message = m; } public String getMessage() { return privateMessage(); } private String privateMessage() { return this.message; } public Message() { }
}
</source>
Get Set Properties JSTL
<source lang="java">
//File: index.jsp <html>
<head> <title>Using a JavaBean</title> </head> <body>
Using a JavaBean
<jsp:useBean id="myCar" class="beans.CarBean" /> I have a <jsp:getProperty name="myCar" property="make" />
<jsp:setProperty name="myCar" property="make" value="Ferrari" /> Now I have a <jsp:getProperty name="myCar" property="make" /> </body>
</html>
////////////////////////////////////////////////////////////// //Java Bean package beans; import java.io.Serializable; public class CarBean implements Serializable {
private String make = "Company"; private double cost = 100.00; private double taxRate = 17.5; public CarBean() {} public String getMake() { return make; } public void setMake(String make) { this.make = make; } public double getPrice() { double price = (cost + (cost * (taxRate/100))); return price; }
}
</source>
Getting a Property Value
<source lang="java">
//File: index.jsp <HTML>
<HEAD> <TITLE>Getting a Property Value</TITLE> </HEAD> <BODY>
Getting a Property Value
<jsp:useBean id="bean1" class="beans.Message" /> The message is: <jsp:getProperty name="bean1" property="message" /> </body>
</html>
//////////////////////////////////////////// //Java Bean Class package beans; public class Message {
private String message = "Hello from JSP!"; public String getMessage() { return message; } public Message() { }
}
</source>
JSP and Java beans 3
<source lang="java">
/* <%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %> <jsp:useBean id="priceFetcher" class="com.jexp.StockPriceBean" /> <html> <head><title>Price Fetch</title></head> <body> <c:choose>
<c:when test="${empty param.symbol}">
Please submit a valid stock symbol
<form method="POST" action ="<c:out value="${pageContext.request.contextPath}" />/priceFetch.jsp">
Stock symbol: | <input type="text" name="symbol" size="10"> |
<input type="submit" value="Submit Info"> |
</c:when> <c:otherwise>
Here is the latest value of <c:out value="${param.symbol}" />
<jsp:setProperty name="priceFetcher" property="symbol" value="<%= request.getParameter(\"symbol\") %>" /> <jsp:getProperty name="priceFetcher" property="latestPrice"/> </c:otherwise> </c:choose>
</body> </html>
- /
package com.jexp; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.MalformedURLException; import javax.swing.text.html.HTMLEditorKit.ParserCallback; import javax.swing.text.MutableAttributeSet; import javax.swing.text.html.parser.ParserDelegator; public class StockPriceBean {
/** * The URL base for requesting a stock price; it looks like * "http://finance.yahoo.ru/q?d=t&s=" */ private static final String urlBase = "http://finance.yahoo.ru/q?d=t&s="; /** * The character stream of HTML that is parsed for the stock price * returned by java.net.URL.openStream() * * see java.net.URL * @see java.io.BufferedReader */ private BufferedReader webPageStream = null; /** * The java.net.URL object that represents the stock Web page * */ private URL stockSite = null; /** * The ParserDelegator object for which ParserDelegator.parse() is * called for the Web page * * @see javax.swing.text.html.parser.ParserDelegator */ private ParserDelegator htmlParser = null; /** * The MyParserCallback object (inner class); this object is an * argument to the ParserDelegator.parse() method * * @see javax.swing.text.html.HTMLEditorKit.ParserCallback */ private MyParserCallback callback = null; /** * This String holds the HTML text as the Web page is parsed. * * @see MyParserCallback */ private String htmlText = ""; private String symbol = ""; private float stockVal = 0f; //A JavaBean has to have a no-args constructor (we explicitly show this //constructor as a reminder; the compiler would have generated a default //constructor with no arguments automatically public StockPriceBean() {} //Setter or mutator method for the stock symbol public void setSymbol(String symbol){ this.symbol = symbol; } class MyParserCallback extends ParserCallback { //bread crumbs that lead us to the stock price private boolean lastTradeFlag = false; private boolean boldFlag = false; public MyParserCallback(){ //Reset the enclosing class" instance variable if (stockVal != 0) stockVal = 0f; } public void handleStartTag(javax.swing.text.html.HTML.Tag t, MutableAttributeSet a,int pos) { if (lastTradeFlag && (t == javax.swing.text.html.HTML.Tag.B )){ boldFlag = true; } }//handleStartTag public void handleText(char[] data,int pos){ htmlText = new String(data); //System.out.println(htmlText); if (htmlText.indexOf("No such ticker symbol.") != -1){ throw new IllegalStateException( "Invalid ticker symbol in handleText() method."); } else if (htmlText.equals("Last Trade:")){ lastTradeFlag = true; } else if (boldFlag){ try{ stockVal = new Float(htmlText).floatValue(); } catch (NumberFormatException ne) { try{ // tease out any commas in the number using //NumberFormat java.text.NumberFormat nf = java.text.NumberFormat. getInstance(); Double f = (Double) nf.parse(htmlText); stockVal = (float) f.doubleValue(); } catch (java.text.ParseException pe){ throw new IllegalStateException( "The extracted text " + htmlText + " cannot be parsed as a number!"); }//try }//try lastTradeFlag = false; boldFlag = false; }//if } //handleText }//MyParserCallback public float getLatestPrice() throws IOException,MalformedURLException { stockSite = new URL(urlBase + symbol); webPageStream = new BufferedReader(new InputStreamReader(stockSite. openStream())); htmlParser = new ParserDelegator(); callback = new MyParserCallback();//ParserCallback synchronized(htmlParser){ htmlParser.parse(webPageStream,callback,true); }//synchronized //reset symbol symbol = ""; return stockVal; }//getLatestPrice
}//StockPriceBean
</source>
JSP and Java beans (JavaBeans) 1
<source lang="java">
/* Beginning JavaServer Pages Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell ISBN: 0-7645-7485-X
- /
</source>
JSP and Java beans (JavaBeans) 2
<source lang="java">
/* Beginning JavaServer Pages Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell ISBN: 0-7645-7485-X
- /
</source>
JSP email valid check
<source lang="java">
//validCheck.jsp /* <%@page contentType="text/html"%> <%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %> <jsp:useBean id="chk" class="com.jexp.ClientValidator" > <jsp:setProperty name="chk" property="*" /> </jsp:useBean> <%-- get valid property from ClientValidator bean --%> <c:set var="isValid" value="${chk.valid}" /> <c:if test="${isValid}">
<c:set var="email" value="${chk.email}" scope="request" /> <c:set var="password" value="${chk.password}" scope="request" />
</c:if> <html> <head><title>Client Checker</title></head> <body>
Welcome
Email: <c:out value="${email}" />
Password: <c:out value="${password}" />
</body> </html>
- /
package com.jexp; public class ClientValidator implements java.io.Serializable{ String email; String password; boolean valid; public ClientValidator(){
this.valid=false;}
public boolean isValid(){
/* Use a Data Access Object to validate the email and password. If the validation does not fail then set this.valid to true*/ this.valid=true; return valid; }
public void setEmail(String _email){
if(_email != null && _email.length() > 0) email = _email; else email = "Unknown";
} public String getEmail(){
return email; }
public void setPassword(String _password){
if(_password != null && _password.length() > 0) password = _password; else password = "Unknown";
} public String getPassword(){
return password; }
}
</source>
JSP Standard Actions: set property
<source lang="java">
/* Beginning JavaServer Pages Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell ISBN: 0-7645-7485-X
- /
<html> <head> </head> <body>
<jsp:useBean id="myProduct" class="com.wrox.begjsp.ch03.Product"> <jsp:setProperty name="myProduct" property="sku" value="12345"/> <jsp:setProperty name="myProduct" property="name" value="DSL Modem"/> </jsp:useBean>
Sku: | <%= myProduct.getSku() %> |
Name: | ${myProduct.name} |
<jsp:useBean id="myMap" class="java.util.HashMap" /> <jsp:useBean id="myMap2" class="java.util.HashMap" type="java.util.Map"/>
</body>
</html>
</source>
JSP with Java bean
<source lang="java">
<%@ page import="java.util.*" %> <html>
<head> <title>WishList</title> <jsp:useBean class="com.jexp.WishList" id="wishList" scope="session"/> <jsp:useBean class="com.jexp.WishListItems" id="wishListItems" scope="application" /> </head> <body> <% Enumeration e = request.getParameterNames(); %> <% Set map = wishList.getMap(); %> <% while(e.hasMoreElements()){ String key = (String)e.nextElement(); if(key.equals(wishListItems.getItem(0).getId())){ map.add(wishListItems.getItem(0)); } if(key.equals(wishListItems.getItem(1).getId())){ map.add(wishListItems.getItem(1)); } if(key.equals(wishListItems.getItem(2).getId())){ map.add(wishListItems.getItem(2)); } if(key.equals(wishListItems.getItem(3).getId())){ map.add(wishListItems.getItem(3)); } if(key.equals(wishListItems.getItem(4).getId())){ map.add(wishListItems.getItem(4)); } } %> Items currently In your Wish List:
<% if(map.size()==0){ %> There are no items in your Wish List
<% } else { Set set = map; %> <% if (set!=null){ com.jexp.Item[] keys = new com.jexp.Item[0]; keys = (com.jexp.Item[])set.toArray(keys); for (int i=0;i<keys.length;i++){ %> <%=keys[i].getName()%><%="
"%> <% } } }%>
</body>
</html> package com.jexp; public class Item {
private String id; private String name; public Item(){} public Item(String s, String t){ name=s; id=t; } public String getId(){ return id; } public String getName(){ return name; }
}
package com.jexp;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
public class WishList implements HttpSessionBindingListener {
private Set map = new HashSet(); public Set getMap(){ return map; } //Session binding methods public void valueBound(HttpSessionBindingEvent e){ System.out.println("The WishList has been Bound!"); } public void valueUnbound(HttpSessionBindingEvent e){ Item[] keys = new Item[0]; System.out.println("Getting values..."); Iterator it = map.iterator(); while(it.hasNext()){ Item item = (Item)it.next(); System.out.println(item.getName()); } }
}
package com.jexp; public class WishListItems {
private Item[] items = { new Item("ID 1","Name 1"), new Item("ID 2","Name 2"), new Item("ID 3","Name 3"), new Item("ID 4","Name 4"), new Item("ID 5","Name 5") }; public Item getItem(int i){ if (items[i]!=null){ return items[i]; } else { return null; } }
}
</source>
Set Property Value
Using a Constructor
<source lang="java">
//File: index.jsp <HTML>
<HEAD> <TITLE>Using a Constructor</TITLE> </HEAD> <BODY>
Using a Constructor
<% beans.Message m = new beans.Message("Hello from JSP!"); %> The message is: <%= m.msg() %> </BODY>
</HTML>
/////////////////////////////////////////////////////////////////////////// //File: Message.java package beans; public class Message {
String msg; public Message(String message) { msg = message; } public String msg() { return msg; }
}
</source>
Using a Java Bean Jsp
<source lang="java">
////////////////////////////////////// //File: index.jsp
<%@ page import="beans.MessageBean" %> <HTML>
<HEAD> <TITLE>Using a JavaBean</TITLE> </HEAD> <BODY>
Using a JavaBean
<% MessageBean m = new MessageBean(); %> The message is: <%= m.msg() %> </BODY>
</HTML> ////////////////////////////////////////////////// //File: MessageBean.java package beans;
public class MessageBean {
public MessageBean() { } public String msg() { return "Hello from JSP!"; }
}
</source>
Using Bean Counter JSP
<source lang="java">
//File: BeanCounter.jsp <HTML> <HEAD> </HEAD> <BODY> <%@ page language="java" %> <jsp:useBean id="counter" scope="session" class="beans.Counter" /> <jsp:setProperty name="counter" property="count" param="count" /> <%
out.println("Count from scriptlet code : " + counter.getCount() + "
");
%> Count from jsp:getProperty :
<jsp:getProperty name="counter" property="count" />
</BODY> </HTML> /////////////////////////////////////////////////////////// //File: Counter.java package beans; import java.io.Serializable; public class Counter implements Serializable{
// Initialize the bean on creation int count = 0; // Parameterless Constructor public Counter() { } // Property Getter public int getCount() { // Increment the count property, with every request count++; return this.count; } // Property Setter public void setCount(int count) { this.count = count; }
}
</source>