javaBean的编写:
标准的java类;
需要定义一个无参的构造方法;
定义有属性;
定义有属性的getter和setter方法;
实现serializable接口;
ussBean动作:
使用userBean动作的代码;
<jsp:useBean class="webbook.chapter9.Book" id="book" scope="page"/>
等价的代码:
<%
webbook.chapter9.Book book=null;
if(pageContext.getAttribute("book")==null){
book=new Book();
pageContext.setAttribute("book",book);
}
}else{
book=(Book)pageContext.getAttribute("book");
}
%>
setProperty动作:
使用setProperty动作的代码;
<jsp:setProperty name="book" property="name" value="Hibernate"/>
等价代码;
<%book.setName("Hibernate");%>
getProperty动作:
使用getProperty动作的代码;
<jsp:getProperty name="book" name="name"/>
等价代码:
<%= book.getName() %>
测试代码:
book.html
代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form name="form1" method="post" action="displayBook.jsp">
ISBN:<input type="text" name="isbn"> <br>
书名:<input type="text" name="name"> <br>
作者:<input type="text" name="author"> <br>
是否售出:是<input type="radio" name="sale" value="true" checked>
否<input type="radio" name="sale" value="false"><br>
<input type="submit" value="提交">
<input type="reset" value="重来">
</form>
</body>
</html>
Book.java
代码:
package webbook.chapter9;
public class Book {
private String isbn;
private String name;
private String author;
private boolean sale;
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public boolean isSale() {
return sale;
}
public void setSale(boolean sale) {
this.sale = sale;
}
}
displayBook.jsp
代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>display Book Bean information</title>
</head>
<body>
<% request.setCharacterEncoding("utf-8");%>
<jsp:useBean class="webbook.chapter9.Book" id="book" scope="request"/>
<jsp:setProperty name="book" property="*"/>
ISBN:<jsp:getProperty name="book" property="isbn"/><br>
书名:<jsp:getProperty name="book" property="name"/><br>
作者:<% out.println(book.getAuthor()); %><br><br>
是否售出:
<%
if(book.isSale()){
out.println("是");
}else{
out.println("否");
}
%>
<br>
</body>
</html>