JavaWeb_使用JavaBean
使用JavaBean
- 1.具体了解JavaBean就可以,基本上不再使用。每个JSP标签的代码等价于该标签下注释内的代码。
bean.jsp
<%@page import="com.xs.javaweb.Customer"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="customer" class="com.xs.javaweb.Customer"
scope="request"></jsp:useBean>
<%--
//1.从scope(session)中获取id(customer)属性值,赋给class(com.xs.javaweb.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.xs.javaweb.Customer").newInstance();
session.setAttribute("customer", customer);
}
--%>
<jsp:useBean id="customer2" beanName="com.xs.javaweb.Customer"
type="java.lang.Object" scope="request"></jsp:useBean>
<%--
Object customer2 = request.getAttribute("customer2");
if(customer2){
customer2 = Class.forName("com.xs.javaweb.Customer").newInstance();
request.setAttribute("cutomer2", customer2);
}
--%>
<!-- 若property的值为*,省略value属性值,则将自动为所有属性赋值为对应的请求参数的值。 -->
<jsp:setProperty property="*" name="customer" />
<%--
<jsp:setProperty property="name" value="xs" name="customer" />
customer.setAge(10);
--%>
id:<jsp:getProperty property="id" name="customer" /><br>
name:<jsp:getProperty property="name" name="customer" /><br>
age:<jsp:getProperty property="age" name="customer" />
<%--
<%= customer.getAge() %>
--%>
</body>
</html>
Customer.java
/**
* All rights Reserved,Designed By XS
* @Title: Customer.java
* @Package com.xs.javaweb
* @Description: TODO
* @author: XS
* @date: 2019年3月12日 下午8:23:30
* @version V1.0
*/
package com.xs.javaweb;
/**
* @ClassName: Customer
* @Description: TODO
* @author: XS
* @date: 2019年3月12日 下午8:23:30
* @version V1.0
*/
public class Customer {
private int id;
private String name;
private int age;
/**
* @Title: Customer
* @Description: TODO
* @param id
* @param name
* @param age
*/
public Customer(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
/**
* @Title: Customer
* @Description: TODO
*/
public Customer() {
super();
System.out.println("Customer's Constructor...");
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id: the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name: the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age: the age to set
*/
public void setAge(int age) {
this.age = age;
}
}