<%@ page contentType="text/html; charset=GBK" language="java" errorPage=""%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>java bean 测试 </title> </head> <body> <jsp:useBean id="p1" class="test.Person" scope="page"> </jsp:useBean> <jsp:setProperty property="name" name="p1" value="小明" /> <jsp:setProperty name="p1" property="age" value="23" /> <jsp:getProperty name="p1" property="name" /> <jsp:getProperty name="p1" property="age" /> </body> </html>
package test; public class Person { private String name; private int age; //无参构造器 public Person() { } //初始化全部成员变量的构造器 public Person(String name, int age) { this.name = name; this.age = age; } public void setName(String name) { this.name = name; } public String getName() { return this.name; } public void setAge(int age) { this.age = age; } public int getAge() { return this.age; } }
<%-- Document : beanTest2 Created on : 2020-4-11, 19:16:58 Author : Administrator --%> <%@page import="test.Person"%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>java bean 测试</title> </head> <body> <% Person p1 = new Person(); pageContext.setAttribute("p1",p1); p1.setName("wawa"); p1.setAge(23); %> <%=p1.getName()%> <br/> <%=p1.getAge()%> </body> </html>