javaBean的使用方法;
在jsp页面中使用javaBean:三个标签;
<jsp:useBean>标签
<jsp:setProperty>标签
<jsp:getProperty>标签
首先建立一个customer类:
package com.lanqiao.javatest; public class Customer { private Integer id; private String name; private int age; public Customer() { super(); // TODO Auto-generated constructor stub } public Customer(Integer id, String name, int age) { super(); this.id = id; this.name = name; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } 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; } @Override public String toString() { return "Customer [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
建立一个jsp页面:直接调用customer的属性和方法,并且可以给属性赋值;
<%@page import="com.atguigu.javaweb.Customer"%> <%@ 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="customer" class="com.lanqiao.javatest.Customer" scope="request"></jsp:useBean> <jsp:useBean id="customer2" beanName="com.lanqiao.javatest.Customer" type="java.lang.Object" scope="request"></jsp:useBean> <%-- Object customer2 = request.getAttribute("customer2"); if(customer2){ customer2 = Class.forName("com.lanqiao.javatest.Customer").newInstance(); request.setAttribute("customer2", customer2); } --%> <!-- 若 property 的值为 *, 省略 value 属性值, 则将自动为所有属性赋值为对应的请求参数的值. --> <jsp:setProperty property="*" name="customer"/> <%-- <jsp:setProperty property="name" value="ATGUIGU2" name="customer"/> --%> age: <jsp:getProperty property="age" name="customer"/> <br> name: <jsp:getProperty property="name" name="customer"/> <br> id: <jsp:getProperty property="id" name="customer"/> <%-- <%= customer.getAge() %> --%> <%-- customer.setAge(10); --%> <%-- //1. 从 scope(session) 中获取 id(customer) 属性值, 赋给 class(com.lanqiao.javatest.Customer) //类型的 id(customer) 变量 Customer customer = (Customer)session.getAttribute("customer"); //2. 若属性值为 null, 则利用反射创建一个新的对象, 把该对象赋给 id(customer), 并以 id(customer) //为属性名让如到 scope(session) 中. if(customer == null){ customer = (Customer)Class.forName("com.lanqiao.javatest.Customer").newInstance(); session.setAttribute("customer", customer); } --%> </body> </html>