JSP第二天 JavaBean加强

1.JavaBean

  JavaBean:JavaBean就是一个遵循特定写法的Java类

JavaBean特点:

  • 这个类必须有一个无参的构造函数
  • 属性必须私有化
  • 针对每个私有属性对外暴露对应的共有getter和setter方法
  • getter方法称为属性的读方法
  • setter方法称为属性的写方法
为什么javabean要有这些规定
•在java中,通常使用javabean来封装数据
•多数javabean封装工具都是通过反射来实现的
•既然要反射javabean,就需要知道javabean有什么样的构造函数和哪些方法
 
1.在 JSP中使用JavaBean

 JSP技术提供了三个关于JavaBean组件的动作元素,即JSP标签,它们分别是:

1.<jsp:useBean>标签:用于在JSP页面中查找或实例化一个JavaBean组件

  • 如果存在则直接返回该JavaBean对象的引用。
  • 如果不存在则实例化一个新的JavaBean对象并将它以指定的名称存储到指定的域范围内。

常用语法:

<jsp:useBean id="beanName" class="package.class" scope="page|request|session|application"/>

id属性用于指定JavaBean实例对象的引用名称和其存储在域范围中的名称。

class属性用于指定JavaBean的完整类名。

scope属性用于指定JavaBean所存储的域范,其取值只能是page、request、session和application等四个值中的一个,其默认值是page。

userbean标签的标签体只在userbean标签实例化时才执行。

2.<jsp:setProperty>标签:用于在JSP页面中设置一个JavaBean组件的属性

语法格式:

<jsp:setProperty name="beanName"

{

   property="propertyName" value="{string|<%=expression%>}"

   property="propertyName" [param="parameterName"]

   property="*";

}/>

name属性用于指定JavaBean对象的名称。

property属性用于指定JavaBean对象的某个属性的值。value的值可以是字符串,也可以是表达式。为字符串时,该值会自动转化为JavaBean属性相应的类型,如果value的值是一个表达式,那么该表达式的计算结果必须与所要设置的JavaBean属性的类型一致。

param属性用于将JavaBean实例对象的某个属性值设置为一个请求参数值,该属性值通用会自动转换为要设置的JavaBean属性的类型。

3.<jsp:getProperty>标签:用于在JSP页面中获取一个JavaBean组件的属性。

语法:<jsp:getProperty name="beanInstanceName" property="PropertyName" />

name属性用于指定JavaBean实例对象的名称,其值应与<jsp:useBean>标签的id属性值相同

property属性用于指定JavaBean实例对象的属性名

如果一个JavaBean实例对象的某个属性值为null,那么,使用<jsp:getProperty>标签输出该属性的结果将是一个内容为null的字符串。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
<jsp:useBean id="person" class="cn.itcast.javabean.Person" scope="page" ></jsp:useBean>
<jsp:setProperty property="name" name="person" value="lisi"/>
<%=person.getName() %><br/>
<!-- 用请求参数给属性赋值  http://localhost/day09/2.jsp?name=wangwu-->
<jsp:setProperty property="name" name="person" param="name"/>
<!-- 将客户机提交的字符串转换成相应的8中基本数据类型 -->
<jsp:setProperty property="age" name="person" param="age"/>
<%=person.getName() %><br/>
<%=person.getAge() %><br/>
<br/>------------------------<br/>
<!-- 用所有的请求参数为bean赋值 -->
<jsp:setProperty property="*" name="person"/>
<%=person.getName() %><br/>
<%=person.getAge() %><br/>

<jsp:getProperty property="name" name="person"/>
</body>
</html>
3.内省操作JavaBean

 内省的简单操作

/**
 * 利用内省操作JavaBean
 * 
 * @author malinkang
 * 
 */
public class JavaBeanTest {
    public static void main(String[] args) throws Exception {
        Person p = new Person(14, "zhangsan");

        String propertyName = "name";
        //获取属性描述对象
        PropertyDescriptor pd = new PropertyDescriptor(propertyName, p
                .getClass());
        //获取get方法
        Method methodGetName = pd.getReadMethod();

        Object retVal = methodGetName.invoke(p);

        System.out.print(retVal);
        //获取set方法
        Method methodSetName = pd.getWriteMethod();

        methodSetName.invoke(p, "lisi");

        Object retVal2 = methodGetName.invoke(p);

        System.out.print(retVal2);
    }

}

获取所有的属性值

public class JavaBeanTest2 {
    public static void main(String[] args) throws Exception {
        Person p = new Person(14, "zhangsan");
        // test(p);
        // test2(p);

    }

    private static void test2(Person p) throws IntrospectionException,
            IllegalAccessException, InvocationTargetException {
        PropertyDescriptor pd = new PropertyDescriptor("name", Person.class);
        Method methodGetAge = pd.getReadMethod();
        Object retVal = methodGetAge.invoke(p);
        System.out.println(retVal);
    }

    // 获取所有属性
    private static void test(Person p) throws IntrospectionException {
        BeanInfo beanInfo = Introspector
                .getBeanInfo(p.getClass(), Object.class);
        Object retVal = null;
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor pd : pds) {
            System.out.println(pd.getName());// age name null
        }
        System.out.println(retVal);
    }
}
4.BeanUtils操作JavaBean

 使用BeanUtils需要commons-beanutils-1.8.3.jar和commons-logging-1.1.1.jar两个jar包支持

public class BeanUtilsTest {
    public static void main(String[] args) throws Exception {
        // test1();
        test2();
    }

    // 存放到Map中进行设置
    private static void test2() throws IllegalAccessException,
            InvocationTargetException {
        Person p = new Person();
        ConvertUtils.register(new DateLocaleConverter(), Date.class);
        Map<String, String> map = new HashMap<String, String>();
        map.put("name", "lisi");
        map.put("age", "15");
        map.put("birthday", "1990-9-8");
        BeanUtils.populate(p, map);
        System.out.println(p.getName());
        System.out.println(p.getAge());
        System.out.println(p.getBirthday());
    }

    // 使用BeanUtils 设置JavaBean属性值
    private static void test1() throws IllegalAccessException,
            InvocationTargetException {
        Person p = new Person();
        String name = "wangwu";
        String age = "43";
        String birthday = "1989-08-01";
        // 为了让日期赋值到birthday属性上,我们注册一个日期转换器
        ConvertUtils.register(new Converter() {

            @Override
            public Object convert(Class arg0, Object value) {
                // 判断是否有值
                if (value == null) {
                    return null;
                }
                // 判断是否是字符串
                if (!(value instanceof String)) {
                    throw new ConversionException("不支持非String类型的转换");
                }
                String str = (String) value;
                // 判断是否为空字符串
                if (str.trim().equals("")) {
                    return null;
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    return sdf.parse(str);
                } catch (java.text.ParseException e) {
                    throw new RuntimeException(e);
                }

            }
        }, Date.class);
        /*
         * //官方提供的日期转换器 bug:不能检测空的情况 ConvertUtils.register(new
         * DateLocaleConverter(),Date.class);
         */
        BeanUtils.setProperty(p, "name", name);
        // 自动将字符串转换成int 类型
        BeanUtils.setProperty(p, "age", age);
        BeanUtils.setProperty(p, "birthday", birthday);
        System.out.println(p.getName());
        System.out.println(p.getAge());
        System.out.println(p.getBirthday());
    }
}
原文地址:https://www.cnblogs.com/malinkang/p/2710469.html