版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/twilight_karl/article/details/70214763
创建JavaBean实例:
<jsp:useBean id=”name” class=”” scope=”page/session/request/application”/>
id为类的另一个名字,class指定具体的类,scope表示范围,在scope的范围内查找是否有指定的属性存在
赋值
- 指定参数和值
<jsp:setProperty name="user" property="password" value="123" />
- 将指定参数的值赋值给JavaBean的属性
<jsp:setProperty name="user" param="pwd" property="password" />
- 通过自省机制自动匹配
<jsp:setProperty name="user" property="*" />
使用jsp:useBean的目的是减少Script的使用
一个典型的javabean: JavaBean.java
java">package Bean;
import java.io.Serializable;
public class JavaBean implements Serializable {
private String name ;
private String password;
public JavaBean(String name, String password) {
super();
this.name = name;
this.password = password;
}
public JavaBean() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isValid(){
if(name.equals("tom") && password.equals("123")){
return true;
}
return false;
}
}
使用jsp:Bean标签
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<jsp:useBean id="user" class="Bean.JavaBean" scope="page" />
<jsp:setProperty name="user" property="*" />
<html>
<body>
<font color='red'>
<jsp:getProperty property="name" name="user"/>
</font>
</body>
</html>
web容器翻译后的Java代码
Bean.JavaBean user = null;
user = (Bean.JavaBean) _jspx_page_context.getAttribute("user", javax.servlet.jsp.PageContext.PAGE_SCOPE);
if (user == null){
user = new Bean.JavaBean();
_jspx_page_context.setAttribute("user", user, javax.servlet.jsp.PageContext.PAGE_SCOPE);
}
采用传统方式的做法:
<%@ page language="java" import="java.util.*,Bean.JavaBean" pageEncoding="UTF-8"%>
<html>
<body>
<%
JavaBean user = (JavaBean)request.getAttribute("user");
if(user == null){
user = new JavaBean();
}
user.setName(request.getParameter("name"));
user.setPassword(request.getParameter("pwd"));
if(user.isValid()){
out.println("登录成功");
}else{
out.println("登录失败");
}
%>
</body>
</html