在 Jsp 页面中使用 JavaBean

来源:互联网 发布:海知智能 CTO 编辑:程序博客网 时间:2024/04/19 11:55

个网站系统一般可分为3层:数据层(data layer)、商业层(business layer)、应用层(presentation layer)。若使用Java语言环境,可采用ServletJsp编程。若使用纯脚本的Jsp语言,如果出现大量用户单击,很快就到达了其功能上限,而采用JavaBean组件技术就能大幅度提高功能上限,加快执行速度。另外一方面,纯脚本语言将应用表现层和商业逻辑层混用在一起,造成修改不方便,并且代码不能重复利用,采用组件技术就可以解决这些问题,并使系统更易维护,也使网站的开发人员分工更为明确。

    在此片断将介绍Jsp中有关JavaBean的编写规范,那么如何在Jsp页面中调用这些Bean组件呢?JavaBean其实就是用Java语言编写的一个类,在Jsp页面中调用这些Bean组件就是要创建此类的一个对象。
   在Jsp页面中使用JavaBean,必须要告诉Jsp页面它将用到一个Bean。可以用<jsp:userBean>标记来做到这一点:
<jsp:useBean id="idname" class="package.class" scope="page|session|application" />
首先,<jsp:useBean>标记要求用id属性来标记Bean,以识别Jsp页面中其余部分的Bean。
其次,要使用scope属性,确定Bean的使用范围。有了scope属性,就能确定Bean单一页面(scope="page")、会话
(scope="session")和整个应用程序(scope="application")保留信息。有了会话范围,就可以实现网站购物中的购物车
功能。
  最后,要告诉Jsp页面从何处查找Bean,即找到Bean的Class文件。在实际应用中,JavaBean被组织成包(package),
以便进行管理,也就是把一组JavaBean放在同一个目录下。在Tomcat中,class文件保存在web-inf/classes目录下。
如下实战练习,在服务器上正常调试运行通过,服务器端验证客户端输入的数据:
一、程序文件 LogBean.java
package yin.bean;
import java.util.*;
public class LogBean {
private String username;
private String password;
private String email;
private Hashtable errors;
public LogBean()// 构造方法
{
   username = "";
   password = "";
   email = "";
   errors = new Hashtable();
}
/**
* @return the email
*/
public String getEmail() {
   return email;
}
/**
* @param email
*            the email to set
*/
public void setEmail(String emailStr) {
   this.email = emailStr;
}
/**
* @return the erroes
*/
public Hashtable getErrors() {
   return errors;
}
/**
* @return the password
*/
public String getPassword() {
   return password;
}
/**
* @param password
*            the password to set
*/
public void setPassword(String passwordStr) {
   this.password = passwordStr;
}
/**
* @return the userName
*/
public String getUsername() {
   return username;
}
/**
* @param userName
*            the userName to set
*/
public void setUsername(String usernameStr) {
   this.username = usernameStr;
}
/**
* @param erroes
*            the erroes to set
*/
public void setErrors(String Key, String msg) {
   errors.put(Key, msg);
}
// 数据验证方法
public boolean validate() {
   boolean allOk = true;
   if (username.equals("")) {
    errors.put("username", "Please enter your name.");
    username = "";
    allOk = false;
   }
   if (password.equals("")
     || (password.length() > 10 || password.length() < 6)) {
    errors.put("password",
      "Please enter a valid password of 6-10 charactors.");
    password = "";
    allOk = false;
   }
   if (email.equals("") || (email.indexOf('@') == -1)
     || (email.indexOf('.') == -1)) {
    errors.put("email", "Please enter a valid Email address.");
    email = "";
    allOk = false;
   }
   return allOk;
}
public String getErrorMsg(String s) {
   String errorMsg = (String) errors.get(s.trim());
   return (errorMsg == null) ? "" : errorMsg;
}
}
二、程序文件 logBean.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<jsp:useBean id="handle" class="yin.bean.LogBean" scope="request" />
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
    + request.getServerName() + ":" + request.getServerPort()
    + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
   <base href="<%=basePath%>">
   <title>Jsp 页面中使用 Bean</title>
   <meta http-equiv="pragma" content="no-cache">
   <meta http-equiv="cache-control" content="no-cache">
   <meta http-equiv="expires" content="0">
   <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
   <meta http-equiv="description" content="This is my page">
   <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
   <!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
   <style type="">
   BODY{FONT-FAMILY:宋体;FONT-SIZE:9pt}
   TH{FONT-SIZE:9pt}
   TD{FONT-SIZE:9pt}
</style>
</head>
<body>
   <center>
    <form method="post" action="logValidate.jsp">
     <table border="0" cellspacing="0" cellpadding="0" width="320"
      bgcolor="#F0F8FF" bordercolorlight="#4DA6FF"
      bordercolordark="#ECF5FF">
      <tr>
       <td colspan="2" align="center">
        <h4>请你注册:</h4>
       </td>
      </tr>
      <tr>
       <td align="center">注册名:</td>
       <td>
        <input type="text" name="username" value="<jsp:getProperty name="handle" property="username" />">
       </td>
      </tr>
      <tr>
       <td colspan="3" align="center">
        <font color="red"><span class="error"><%=handle.getErrorMsg("username")%></span></font>
       </td>
      </tr>
      <tr>
       <td align="center">密 码:</td>
       <td>
        <input type="password" name="password" value="<jsp:getProperty name="handle" property="password" />">
       </td>
      </tr>
      <tr>
       <td colspan="3" align="center">
        <font color="red"><span class="error"><%=handle.getErrorMsg("password")%></span></font>
       </td>
      </tr>
      <tr>
       <td align="center">E-mail:</td>
       <td>
        <input type="text" name="email" value="<jsp:getProperty name="handle" property="email" />">
       </td>
      </tr>
      <tr>
       <td colspan="3" align="center">
        <font color="red"><span class="error"><%=handle.getErrorMsg("email")%></span></font>
       </td>
      </tr>
      <tr>
       <td colspan="2" align="center">
        <input type="submit" valign="top" size="4" value=" 注 册 ">&nbsp;&nbsp;
        <input type="reset" valign="top" size="4" value=" 清 除 ">
       </td>
     </table>
    </form>
    <br>
   </center>
   <jsp:useBean id="LogBean" scope="page" class="yin.bean.LogBean" />
</body>
</html>
三、程序文件 logValidate.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
    + request.getServerName() + ":" + request.getServerPort()
    + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
   <base href="<%=basePath%>">
   <title>Jsp 页面中使用 Bean</title>
   <meta http-equiv="pragma" content="no-cache">
   <meta http-equiv="cache-control" content="no-cache">
   <meta http-equiv="expires" content="0">
   <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
   <meta http-equiv="description" content="This is my page">
   <!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
   <jsp:useBean id="handle" class="yin.bean.LogBean" scope="request">
    <jsp:setProperty name="handle" property="*" />
   </jsp:useBean>
   <%
   if (handle.validate()) {
   %>
   <jsp:forward page="success.jsp" />
   <%
   } else {
   %>
   <jsp:forward page="logBean.jsp" />
   <%
   }
   %>
</body>
</html>
四、程序文件 success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<jsp:useBean id="handle" class="yin.bean.LogBean" scope="request" />
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
    + request.getServerName() + ":" + request.getServerPort()
    + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
   <base href="<%=basePath%>">
   <title>Jsp 页面中使用 Bean</title>
   <meta http-equiv="pragma" content="no-cache">
   <meta http-equiv="cache-control" content="no-cache">
   <meta http-equiv="expires" content="0">
   <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
   <meta http-equiv="description" content="This is my page">
   <!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
   <style type="">
   BODY{FONT-FAMILY:宋体;FONT-SIZE:9pt}
   TH{FONT-SIZE:9pt}
   TD{FONT-SIZE:9pt}
</style>
</head>
<body>
   <center>
    <table border="0" cellspacing="0" cellpadding="0" width="350"
     bgcolor="#F0F8FF" bordercolorlight="#4DA6FF"
     bordercolordark="#ECF5FF">
     <tr>
      <td colspan="2" align="center">
       <h4>祝贺你验证成功!</h4>
      </td>
     </tr>
     <tr>
      <td align="center">注册名:</td>
      <td>
       <jsp:getProperty name="handle" property="username" />
      </td>
     </tr>
     <tr>
      <td align="center">密 码:</td>
      <td>
       <jsp:getProperty name="handle" property="password" />
      </td>
     </tr>
     <tr>
      <td align="center">E-mail:</td>
      <td>
       <jsp:getProperty name="handle" property="email" />
      </td>
     </tr>
    </table>
   </center>
   <jsp:useBean id="LogBean" scope="page" class="yin.bean.LogBean"></jsp:useBean>
</body>
</html>
原创粉丝点击