标签:
??JavaBean就是把程序中的实体对象及业务逻辑单独的封装到Java类当中。然后再JSP页面中调用这个封装好的类,这样可以降低HTML与Java代码的耦合度,简化界面。
JavaBean的规范
为属性声明访问器
在实际开发中,JavaBean的属性应该用小写字母开头,采用驼峰命名法。
获取JavaBean的属性
Produce 类
public class Produce {
private String name="Java编程宝典";
private double price=200;
private int count=10;
public Produce(){}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
public int getCount() { return count; }
public void setCount(int count) { this.count = count; }
}
在index.jsp中访问
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:useBean id="Produce" class="com.java.model.Produce"></jsp:useBean>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<ul>
<li>名称:<%=Produce.getName()%></li>
<li>价格:<%=Produce.getPrice()%></li>
<li>数量:<%=Produce.getCount()%></li>
</ul>
</body>
</html>
对JavaBean的属性赋值
类还是用之前的Produce类
<jsp:useBean id="produce" class="com.java.model.Produce" ></jsp:useBean>
<jsp:setProperty name="Produce" property="name" value="JAVA WEB专业技能"></jsp:setProperty>
<jsp:setProperty name="Produce" property="price" value="100"></jsp:setProperty>
<jsp:setProperty name="Produce" property="count" value="20"></jsp:setProperty>
<body>
<ul>
<li>名称:<jsp:getProperty name="Produce" property="name"></jsp:getProperty></li>
<li>价格:<jsp:getProperty name="Produce" property="price"></jsp:getProperty></li>
<li>数量:<jsp:getProperty name="Produce" property="count"></jsp:getProperty></li>
</ul>
</body>
在JSP页面间应用JavaBean
addProduce.jsp页面
<body>
<form action="showProduce.jsp" method="post">
<input type="text" name="name"><br>
<input type="text" name="price"><br>
<input type="text" name="count"><br>
<input type="submit">
</form>
</body>
showProduce.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<% request.setCharacterEncoding("UTF-8");%>
<jsp:useBean id="produce" class="com.java.model.Produce" >
<jsp:setProperty name="produce" property="*"></jsp:setProperty> //使用property="*" 要求属性名与表单的相应name相同
</jsp:useBean>
<html>
<head>
<title>产品列表</title>
</head>
<body>
<ul>
<li>名称:<jsp:getProperty name="produce" property="name"></jsp:getProperty></li>
<li>价格:<jsp:getProperty name="produce" property="price"></jsp:getProperty></li>
<li>数量:<jsp:getProperty name="produce" property="count"></jsp:getProperty></li>
</ul>
</body>
</html>
当属性名不是对应时,可以使用下面的方式对其赋值:
<% request.setCharacterEncoding("UTF-8");%>
<jsp:useBean id="produce" class="com.java.model.Produce" >
<jsp:setProperty name="produce" property="name" param="username"></jsp:setProperty>
<jsp:setProperty name="produce" property="price" param="userprice"></jsp:setProperty>
<jsp:setProperty name="produce" property="count" param="usercount"></jsp:setProperty>
</jsp:useBean>
标签:
原文地址:http://blog.csdn.net/yen_csdn/article/details/51868524