jsp与Java Bean
java bean 基本结构
public class Student {
//成员变量
//默认构造函数,可选带参构造函数
//成员变量set,get方法
}
在jsp中使用bean
-
导入bean类
<jsp:useBean id=“varname” class=“BeanClass” scope=“page|request|session|application”></jsp:useBean>
- id:bean变量名
- beanClass:类的路径,如com.test.BeanClass
- scope:作用范围
-
设置bean属性
- 一般设置方法
<jsp:setProperty property=“propertyName” name=“varname” value=“value”/>
name:变量名,与jsp:userBean的id一致
property:要修改的bean属性名
value:修改值- 通过表单设置bean属性
<jsp:setProperty property="*" name=“varname”/>
<jsp:setProperty property=“要修改的bean属性名” name=“varname” param=“表单name名”/> -
获取bean属性
<jsp:setProperty property=“要获取的bean属性名” name=“varname”/>
bean作用域
circle类
package com.test;
public class Circle {
private float radius=1;
private double area=Math.PI;
public Circle() {
}
public Circle(float radius) {
this.radius = radius;
this.area = (float) (Math.PI*Math.pow(this.radius, 2));
}
public float getRadius() {
return radius;
}
public void setRadius(float radius) {
this.radius = radius;
this.area = (float) (Math.PI*Math.pow(this.radius, 2));
}
public double getArea() {
return area;
}
}
进入index.jsp
<jsp:useBean id="circle" class="com.test.Circle" scope="page"></jsp:useBean>
<jsp:setProperty property="radius" name="circle" value="10"/>
<jsp:getProperty property="area" name="circle"/>
<form action="index1.jsp" method="post">
<input type="submit" />
</form>
结果
314.1592712402344
跳转index1.jsp
<jsp:useBean id="circle" class="com.test.Circle" scope="page"></jsp:useBean>
<jsp:getProperty property="area" name="circle"/>
结果
3.141592653589793
修改index.jsp,index1.jsp的scope为session或application两次结果会一样的
转载:https://blog.csdn.net/weixin_45116533/article/details/101027871
查看评论