zoukankan      html  css  js  c++  java
  • JavaBean 基础概念、使用实例及代码分析

    JavaBean 基础概念、使用实例及代码分析

    JavaBean的概念

      JavaBean是一种可重复使用的、且跨平台的软件组件。

      JavaBean可分为两种:一种是有用户界面的(有UI的);另一种是没有用户界面的(无UI的),无UI的JavaBean主要负责处理事务(如数据运算,操纵数据库)。

      JSP通常访问的是后一种JavaBean。

    JSP与JavaBean搭配使用的优点

      使得HTML与Java程序分离,这样便于维护代码。

      如果把所有的程序代码都写到JSP网页中,会使得代码繁杂,难以维护。

      可以降低开发JSP网页人员对Java编程能力的要求。

      JSP侧重于生成动态网页,事务处理由JavaBean来完成,这样可以充分利用JavaBean组件的可重用性特点,提高开发网站的效率。

      MVC设计模式(Model View Controller)。

    JavaBean的特征

      一个标准的JavaBean有以下几个特征:

      JavaBean是一个公共(public)的类。

      JavaBean有一个不带参数的构造方法。

      JavaBean通过setXXX方法设置属性,通过getXXX方法获取属性。

    JSP访问JavaBean的语法

    1.导入JavaBean类。

      通过<%@ page import>指令导入JavaBean类,

      例如:

    <%@ page import="mypack.MyJavaBean" %>

    2.声明JavaBean对象。

      <jsp:useBean>标签用来声明JavaBean对象,

      例如: 

    <jsp:useBean id="myBean" class="mypack.MyJavaBean" scope="session"/>

    3.访问JavaBean属性。

      JSP提供了访问JavaBean属性的标签,如果要将JavaBean的某个属性输出到网页上,可以用<jsp:getProperty>标签。

      例如:

    <jsp:getProperty name="myBean" property="count"/>

      如果要给JavaBean的某个属性赋值,可以用<jsp:setProperty>标签,

      例如:

    <jsp:setProperty name="myBean" property="count" value="0"/>

      

      使用指定的值来设置Bean的属性,这个值可以使字符串,也可以是表达式。

      如果是字符串,那么它就会被转换成Bean属性的类型。

      如果是一个表达式,那么它的类型就必须和将要设定的属性值的类型一致。

      不能在同一个<jsp:setProperty>中使用valueparam参数。

      其中param是指通过请求参数的值来给属性赋值。

     

    一个JavaBean使用的例子

      写一个Person类(JavaBean):

    复制代码
    package com.shengqishiwind.bean;
    
    public class Person
    {
        private String name = "zhangsan";
        private int age = 24;
        private String address = "beijing"; 
        public Person()
        {
            
        }
        public String getName()
        {
            return name;
        }
        public void setName(String name)
        {
            this.name = name;
        }
        public int getAge()
        {
            return age;
        }
        public void setAge(int age)
        {
            this.age = age;
        }
        public String getAddress()
        {
            return address;
        }
        public void setAddress(String address)
        {
            this.address = address;
        }
    
        
    }
    复制代码

      然后在JSP中导入这个类,并且声明该类的对象,然后获取其属性或者更改属性:

      导入: 

    <%@ page language="java" import="java.util.*,com.shengqishiwind.bean.Person" pageEncoding="UTF-8"%>

      声明:

          <!-- 声明JavaBean对象 -->
        <jsp:useBean id="person" class="com.shengqishiwind.bean.Person" scope="session"/>

      获取对象属性:

        <!-- 获取对象属性 -->
        name: <jsp:getProperty name="person" property="name" /><br>
        age: <jsp:getProperty name="person" property="age" /><br>
        address: <jsp:getProperty name="person" property="address" /><br>

      设置对象属性:

    复制代码
        <!-- 设置对象姓名属性 -->
        <jsp:setProperty name="person" property="name" value="lisi"/>
        <!-- 设置对象年龄属性 -->
        <jsp:setProperty name="person" property="age" value="30"/>    <!-- 这里有自动的类型转换:String2int-->
        <jsp:setProperty name="person" property="age" value="<%=20+20 %>"/>    <!-- value值还可以用表达式 -->
        <jsp:setProperty name="person" property="address" param="hello"/>    <!-- 可以通过请求参数的值来赋值,如果不传递这个参数,则该属性仍是原值 -->
        
    复制代码

      

      关于声明对象,也可以用脚本段来声明,其作用是一样的:

        <!-- 脚本段声明对象 -->
        <br>another person:
        <% Person person2 = new Person();//这里不能把对象叫做person,提示重复的局部变量,进一步说明这种方法和上面的方法,本质上是一样的
        out.println(person2.getName());
        %>

      所以输出属性时也可以直接用表达式:

        
        <!-- 用表达式输出对象属性 -->
        <br>name again: <%= person.getName()%><br>

       完整JSP代码如下:

    复制代码
    <%@ page language="java" import="java.util.*,com.shengqishiwind.bean.Person" 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>My JSP 'JavaBeanTest.jsp' starting page</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>
          <!-- 声明JavaBean对象 -->
        <jsp:useBean id="person" class="com.shengqishiwind.bean.Person" scope="session"/>
        <!-- 获取对象属性 -->
        name: <jsp:getProperty name="person" property="name" /><br>
        age: <jsp:getProperty name="person" property="age" /><br>
        address: <jsp:getProperty name="person" property="address" /><br>
        
        <!-- 设置对象姓名属性 -->
        <jsp:setProperty name="person" property="name" value="lisi"/>
        <!-- 设置对象年龄属性 -->
        <jsp:setProperty name="person" property="age" value="30"/>    <!-- 这里有自动的类型转换:String2int-->
        <jsp:setProperty name="person" property="age" value="<%=20+20 %>"/>    <!-- value值还可以用表达式 -->
        <jsp:setProperty name="person" property="address" param="hello"/>    <!-- 可以通过请求参数的值来赋值,如果不传递这个参数,则该属性仍是原值 -->
        
        <!-- 再次获取对象属性 -->
        name after change: <jsp:getProperty name="person" property="name" /><br>
        age after change: <jsp:getProperty name="person" property="age" /><br>
        address after change: <jsp:getProperty name="person" property="address" /><br>
        
        <!-- 用表达式输出对象属性 -->
        <br>name again: <%= person.getName()%><br>
        
        <!-- 脚本段声明对象 -->
        <br>another person:
        <% Person person2 = new Person();//这里不能把对象叫做person,提示重复的局部变量,进一步说明这种方法和上面的方法,本质上是一样的
        out.println(person2.getName());
        %>
        
        <!-- 再声明一个Person类对象,注意id必须和前面的不同,声明的是同一个类的不同的对象-->
        <jsp:useBean id="person3" class="com.shengqishiwind.bean.Person" scope="session"/>
    
      </body>
    </html>
    复制代码

      运行时输入地址(注意加上请求参数):http://localhost:8080/HelloWeb/JavaBeanTest.jsp?hello=shanghai

      运行后如图:

    生成的Java源文件 

      查看Tomcat work路径下该项目路径生成的源文件:(JSP会转化成Servlet):

    复制代码
    /*
     * Generated by the Jasper component of Apache Tomcat
     * Version: Apache Tomcat/7.0.40
     * Generated at: 2013-06-23 14:41:47 UTC
     * Note: The last modified time of this file was set to
     *       the last modified time of the source file after
     *       generation to assist with modification tracking.
     */
    package org.apache.jsp;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.jsp.*;
    import java.util.*;
    import com.shengqishiwind.bean.Person;
    
    public final class JavaBeanTest_jsp extends org.apache.jasper.runtime.HttpJspBase
        implements org.apache.jasper.runtime.JspSourceDependent {
    
      private static final javax.servlet.jsp.JspFactory _jspxFactory =
              javax.servlet.jsp.JspFactory.getDefaultFactory();
    
      private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
    
      private javax.el.ExpressionFactory _el_expressionfactory;
      private org.apache.tomcat.InstanceManager _jsp_instancemanager;
    
      public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
        return _jspx_dependants;
      }
    
      public void _jspInit() {
        _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
        _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
      }
    
      public void _jspDestroy() {
      }
    
      public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
            throws java.io.IOException, javax.servlet.ServletException {
    
        final javax.servlet.jsp.PageContext pageContext;
        javax.servlet.http.HttpSession session = null;
        final javax.servlet.ServletContext application;
        final javax.servlet.ServletConfig config;
        javax.servlet.jsp.JspWriter out = null;
        final java.lang.Object page = this;
        javax.servlet.jsp.JspWriter _jspx_out = null;
        javax.servlet.jsp.PageContext _jspx_page_context = null;
    
    
        try {
          response.setContentType("text/html;charset=UTF-8");
          pageContext = _jspxFactory.getPageContext(this, request, response,
                      null, true, 8192, true);
          _jspx_page_context = pageContext;
          application = pageContext.getServletContext();
          config = pageContext.getServletConfig();
          session = pageContext.getSession();
          out = pageContext.getOut();
          _jspx_out = out;
    
          out.write('
    ');
          out.write('
    ');
    
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    
          out.write("
    ");
          out.write("
    ");
          out.write("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    ");
          out.write("<html>
    ");
          out.write("  <head>
    ");
          out.write("    <base href="");
          out.print(basePath);
          out.write("">  
    ");
          out.write("    
    ");
          out.write("    <title>My JSP 'JavaBeanTest.jsp' starting page</title>
    ");
          out.write("    
    ");
          out.write("	<meta http-equiv="pragma" content="no-cache">
    ");
          out.write("	<meta http-equiv="cache-control" content="no-cache">
    ");
          out.write("	<meta http-equiv="expires" content="0">    
    ");
          out.write("	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    ");
          out.write("	<meta http-equiv="description" content="This is my page">
    ");
          out.write("	<!--
    ");
          out.write("	<link rel="stylesheet" type="text/css" href="styles.css">
    ");
          out.write("	-->
    ");
          out.write("
    ");
          out.write("  </head>
    ");
          out.write("  
    ");
          out.write("  <body>
    ");
          out.write("  	<!-- 声明JavaBean对象 -->
    ");
          out.write("    ");
          com.shengqishiwind.bean.Person person = null;
          synchronized (session) {
            person = (com.shengqishiwind.bean.Person) _jspx_page_context.getAttribute("person", javax.servlet.jsp.PageContext.SESSION_SCOPE);
            if (person == null){
              person = new com.shengqishiwind.bean.Person();
              _jspx_page_context.setAttribute("person", person, javax.servlet.jsp.PageContext.SESSION_SCOPE);
            }
          }
          out.write("
    ");
          out.write("    <!-- 获取对象属性 -->
    ");
          out.write("	name: ");
          out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString((((com.shengqishiwind.bean.Person)_jspx_page_context.findAttribute("person")).getName())));
          out.write("<br>
    ");
          out.write("	age: ");
          out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString((((com.shengqishiwind.bean.Person)_jspx_page_context.findAttribute("person")).getAge())));
          out.write("<br>
    ");
          out.write("	address: ");
          out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString((((com.shengqishiwind.bean.Person)_jspx_page_context.findAttribute("person")).getAddress())));
          out.write("<br>
    ");
          out.write("	
    ");
          out.write("	<!-- 设置对象姓名属性 -->
    ");
          out.write("	");
          org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(_jspx_page_context.findAttribute("person"), "name", "lisi", null, null, false);
          out.write("
    ");
          out.write("	<!-- 设置对象年龄属性 -->
    ");
          out.write("	");
          org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(_jspx_page_context.findAttribute("person"), "age", "30", null, null, false);
          out.write("	<!-- 这里有自动的类型转换:String2int-->
    ");
          out.write("	");
          org.apache.jasper.runtime.JspRuntimeLibrary.handleSetProperty(_jspx_page_context.findAttribute("person"), "age",
    20+20 );
          out.write("	<!-- value值还可以用表达式 -->
    ");
          out.write("	");
          org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(_jspx_page_context.findAttribute("person"), "address", request.getParameter("hello"), request, "hello", false);
          out.write("	<!-- 可以通过请求参数的值来赋值,如果不传递这个参数,则该属性仍是原值 -->
    ");
          out.write("	
    ");
          out.write("	<!-- 再次获取对象属性 -->
    ");
          out.write("	name after change: ");
          out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString((((com.shengqishiwind.bean.Person)_jspx_page_context.findAttribute("person")).getName())));
          out.write("<br>
    ");
          out.write("	age after change: ");
          out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString((((com.shengqishiwind.bean.Person)_jspx_page_context.findAttribute("person")).getAge())));
          out.write("<br>
    ");
          out.write("	address after change: ");
          out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString((((com.shengqishiwind.bean.Person)_jspx_page_context.findAttribute("person")).getAddress())));
          out.write("<br>
    ");
          out.write("	
    ");
          out.write("	<!-- 用表达式输出对象属性 -->
    ");
          out.write("	<br>name again: ");
          out.print( person.getName());
          out.write("<br>
    ");
          out.write("	
    ");
          out.write("	<!-- 脚本段声明对象 -->
    ");
          out.write("	<br>another person:
    ");
          out.write("	");
     Person person2 = new Person();//这里不能把对象叫做person,提示重复的局部变量,进一步说明这种方法和上面的方法,本质上是一样的
        out.println(person2.getName());
        
          out.write("
    ");
          out.write("	
    ");
          out.write("	<!-- 再声明一个Person类对象,注意id必须和前面的不同,声明的是同一个类的不同的对象-->
    ");
          out.write("    ");
          com.shengqishiwind.bean.Person person3 = null;
          synchronized (session) {
            person3 = (com.shengqishiwind.bean.Person) _jspx_page_context.getAttribute("person3", javax.servlet.jsp.PageContext.SESSION_SCOPE);
            if (person3 == null){
              person3 = new com.shengqishiwind.bean.Person();
              _jspx_page_context.setAttribute("person3", person3, javax.servlet.jsp.PageContext.SESSION_SCOPE);
            }
          }
          out.write("
    ");
          out.write("
    ");
          out.write("  </body>
    ");
          out.write("</html>
    ");
        } catch (java.lang.Throwable t) {
          if (!(t instanceof javax.servlet.jsp.SkipPageException)){
            out = _jspx_out;
            if (out != null && out.getBufferSize() != 0)
              try { out.clearBuffer(); } catch (java.io.IOException e) {}
            if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
            else throw new ServletException(t);
          }
        } finally {
          _jspxFactory.releasePageContext(_jspx_page_context);
        }
      }
    }
    复制代码

      其中,关键代码对应如下:

      导入语句对应:

    import com.shengqishiwind.bean.Person;

      生成对象的语句对应:

    复制代码
     com.shengqishiwind.bean.Person person = null;
          synchronized (session) {
            person = (com.shengqishiwind.bean.Person) _jspx_page_context.getAttribute("person", javax.servlet.jsp.PageContext.SESSION_SCOPE);
            if (person == null){
              person = new com.shengqishiwind.bean.Person();
              _jspx_page_context.setAttribute("person", person, javax.servlet.jsp.PageContext.SESSION_SCOPE);
            }
          }
    复制代码

      获取name属性:

     out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString((((com.shengqishiwind.bean.Person)_jspx_page_context.findAttribute("person")).getName())));

      设置name属性:

      org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(_jspx_page_context.findAttribute("person"), "name", "lisi", null, null, false);

     

    参考资料

      圣思园张龙老师Java Web视频教程。

  • 相关阅读:
    POJ 1251 Jungle Roads
    1111 Online Map (30 分)
    1122 Hamiltonian Cycle (25 分)
    POJ 2560 Freckles
    1087 All Roads Lead to Rome (30 分)
    1072 Gas Station (30 分)
    1018 Public Bike Management (30 分)
    1030 Travel Plan (30 分)
    22. bootstrap组件#巨幕和旋转图标
    3. Spring配置文件
  • 原文地址:https://www.cnblogs.com/liu-Gray/p/4851962.html
Copyright © 2011-2022 走看看