Java/JSP/Beans
Содержание
- 1 Bean property display
- 2 Beans with scriptlet
- 3 Calling a Private Method
- 4 Get Set Properties JSTL
- 5 Getting a Property Value
- 6 JSP and Java beans 3
- 7 JSP and Java beans (JavaBeans) 1
- 8 JSP and Java beans (JavaBeans) 2
- 9 JSP email valid check
- 10 JSP Standard Actions: set property
- 11 JSP with Java bean
- 12 Set Property Value
- 13 Using a Constructor
- 14 Using a Java Bean Jsp
- 15 Using Bean Counter JSP
- 16 Using Package Jsp
- 17 Using UseBean in Jsp
Bean property display
<%@ 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>
<h2>Here are the EmailBean properties</h2>
<strong>SMTP host: </strong><c:out value="${emailer.smtpHost}" /><br />
<strong>Email recipient: </strong><c:out value="${emailer.to}" /><br />
<strong>Email sender: </strong><c:out value="${emailer.from}" /><br />
<strong>Email subject: </strong><c:out value="${emailer.subject}" /><br />
<strong>Email content: </strong><c:out value="${emailer.content}" /><br />
</body>
</html>
Beans with scriptlet
<%@ 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.<P></P>
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.<P>
<table border="1">
<th>JavaBean property</th><th>Value</th>
<tr><td>id</td> <td><jsp:getProperty name="myBookBean" property="id" /></td></tr>
<tr><td>title</td> <td><jsp:getProperty name="myBookBean" property="title" /></td></tr>
<tr><td>author</td><td><jsp:getProperty name="myBookBean" property="author" /></td></tr>
<tr><td>price</td> <td><jsp:getProperty name="myBookBean" property="price" /></td></tr>
</table>
</body>
</html>
Calling a Private Method
// JSP file
<HTML>
<HEAD>
<TITLE>Calling a Private Method</TITLE>
</HEAD>
<BODY>
<H1>Calling a Private Method</H1>
<jsp:useBean id="bean1" class="beans.Message" />
The message is: <jsp:getProperty name="bean1" property="message" />
<BR>
<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()
{
}
}
Get Set Properties JSTL
//File: index.jsp
<html>
<head>
<title>Using a JavaBean</title>
</head>
<body>
<h2>Using a JavaBean</h2>
<jsp:useBean id="myCar" class="beans.CarBean" />
I have a <jsp:getProperty name="myCar" property="make" /> <br />
<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;
}
}
Getting a Property Value
//File: index.jsp
<HTML>
<HEAD>
<TITLE>Getting a Property Value</TITLE>
</HEAD>
<BODY>
<H1>Getting a Property Value</H1>
<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()
{
}
}
JSP and Java beans 3
/*
<%@ 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}">
<h2>Please submit a valid stock symbol</h2>
<form method="POST" action ="<c:out value="${pageContext.request.contextPath}" />/priceFetch.jsp">
<table border="0"><tr><td valign="top">
Stock symbol: </td> <td valign="top"><input type="text" name="symbol" size="10"></td></tr><tr><td valign="top"><input type="submit" value="Submit Info"></td></tr></table></form>
</c:when>
<c:otherwise>
<h2>Here is the latest value of <c:out value="${param.symbol}" /></h2>
<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
JSP and Java beans (JavaBeans) 1
/*
Beginning JavaServer Pages
Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell
ISBN: 0-7645-7485-X
*/
JSP and Java beans (JavaBeans) 2
/*
Beginning JavaServer Pages
Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell
ISBN: 0-7645-7485-X
*/
JSP email valid check
//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>
<h2>Welcome</h2>
<strong>Email</strong>:
<c:out value="${email}" /><br><br>
<strong>Password</strong>:
<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; }
}
JSP Standard Actions: set property
/*
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>
<table border="1">
<tr>
<td>Sku:</td><td><%= myProduct.getSku() %></td>
</tr>
<tr>
<td>Name:</td><td>${myProduct.name}</td>
</tr>
</table>
<jsp:useBean id="myMap" class="java.util.HashMap" />
<jsp:useBean id="myMap2" class="java.util.HashMap" type="java.util.Map"/>
</body>
</html>
JSP with Java bean
<%@ 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:<br>
<% if(map.size()==0){ %>
There are no items in your Wish List<br>
<% }
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()%><%="<br>"%>
<% }
}
}%>
<br>
</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;
}
}
}
Set Property Value
Using a Constructor
//File: index.jsp
<HTML>
<HEAD>
<TITLE>Using a Constructor</TITLE>
</HEAD>
<BODY>
<H1>Using a Constructor</H1>
<% 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;
}
}
Using a Java Bean Jsp
//////////////////////////////////////
//File: index.jsp
<%@ page import="beans.MessageBean" %>
<HTML>
<HEAD>
<TITLE>Using a JavaBean</TITLE>
</HEAD>
<BODY>
<h1>Using a JavaBean</h1>
<% 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!";
}
}
Using Bean Counter JSP
//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() + "<BR>");
%>
Count from jsp:getProperty :
<jsp:getProperty name="counter" property="count" /><BR>
</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;
}
}