Javabean是一个类,为了和 jsp 页面传数据化简交互过程而产生的。
jsp 中使用 <jsp:useBean> 标记符访问 javabean :
<jsp:useBean id="test" class="test.TestBean" />
jsp 中嵌入 java 代码方式访问 javabean :
首行导入 javabean :
<%@ page import="com.javaBean.TestBean" %>
下边就可以像在 java 语言中那样用了:
<% TestBean testBean=new TestBean(); %>
jsp 页面之间传递和获取数据的两种方法:
获取数据:
法一:使用属性标记符:
<jsp:getProperty name="test" property="message" />
法二:直接嵌入 java 代码:(更简单)
<%=testBean.getName()%>
保存数据:
法一:使用属性标记符:
设置单个元素值:
<jsp:setProperty name="test" property="name" value="jcm" />
设置 jsp 页面中所有元素的值:
<jsp:setProperty name="test" property="*" />
eg:
先创建一个package为org.caiduping.bean的Produce:
1 package org.caiduping.bean; 2 3 public class Produce { 4 private String name="ASUS"; 5 private double price=2800.0; 6 private int count=1; 7 private String buyaddress="科佳电脑城"; 8 public String getName() { 9 return name; 10 } 11 public void setName(String name) { 12 this.name = name; 13 } 14 public double getPrice() { 15 return price; 16 } 17 public void setPrice(double price) { 18 this.price = price; 19 } 20 public int getCount() { 21 return count; 22 } 23 public void setCount(int count) { 24 this.count = count; 25 } 26 public String getBuyaddress() { 27 return buyaddress; 28 } 29 public void setBuyaddress(String buyaddress) { 30 this.buyaddress = buyaddress; 31 } 32 }
在JSP中显示JavaBean的属性信息:
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'index.jsp' starting page</title> 13 <meta http-equiv="pragma" content="no-cache"> 14 <meta http-equiv="cache-control" content="no-cache"> 15 <meta http-equiv="expires" content="0"> 16 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 17 <meta http-equiv="description" content="This is my page"> 18 <!-- 19 <link rel="stylesheet" type="text/css" href="styles.css"> 20 --> 21 </head> 22 23 <body> 24 <jsp:useBean id="myBean" class="org.caiduping.bean.Produce"></jsp:useBean> 25 我的电脑: 26 <jsp:getProperty property="name" name="myBean"/> 27 <br> 28 价格: 29 <jsp:getProperty property="price" name="myBean"/> 30 <br> 31 数量: 32 <jsp:getProperty property="count" name="myBean"/> 33 <br> 34 购买地址: 35 <jsp:getProperty property="buyaddress" name="myBean"/> 36 </body> 37 </html>
run:
我的电脑: ASUS 价格: 2800.0 数量: 1 购买地址: 科佳电脑城