老王学jsp之javabean与表单

今天掌握了一个新的知识,javabean与表单的结合,可以省去不少事情

代码

1):html表单

<!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=GBK">
<title>Insert title here</title>
</head>
<body>
<center>
<form action="javabean_03.jsp" method="post">
姓名:<input type="text" name="name"/><br>
爱好:<input type="text" name="aihao"/><br>
<input type="submit" value="提交" />
<input type="reset" value="重置"/>
</form>
</center>
</body>
</html>

2:jsp处理页面

<%@ page language="java" contentType="text/html;"
    pageEncoding="GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<% request.setCharacterEncoding("utf-8"); %>
<jsp:useBean id="beanTest" class="a.b.javabean_demo_01" scope="page"></jsp:useBean>
<jsp:setProperty name="beanTest" property="*"></jsp:setProperty>
姓名:<%=beanTest.getName()%>
爱好:<%=beanTest.getAihao() %>
</body>
</html>

3):javaBean代码

package a.b;
public class javabean_demo_01 {
    private String name=null;
    private String aihao=null;
    public javabean_demo_01(){
        System.out.println("=====产生新的实例=====");
    }
    public void setName(String namestring)
    {
        name=namestring;
    }
    public String getName()
    {
        return name;
    }
    public void setAihao(String aihaoString)
    {
        aihao=aihaoString;
    }
    public String getAihao()
    {
        return aihao;
    }
}

运行时,不需要设置bean的属性,直接就可以用了

关键是在设置上

首先,表单的字段名称要和javabean的属性名称一致,其次

<jsp:useBean id="beanTest" class="a.b.javabean_demo_01" scope="page"></jsp:useBean>
<jsp:setProperty name="beanTest" property="*"></jsp:setProperty>
这两句代码是关键
第一句指明使用的bean和实例的名称
第二句设置了属性:name表示实例的名字,property表示需要设置的属性,*表示全部。

当然还有其他的方式
1):<jsp:setProperty name="beanTest" property="name" parma="name"></jsp:setProperty> 只设置一个值
2):<jsp:setProperty name="beanTest" property="name" value="name"></jsp:setProperty> 直接指定一个值

取得属性的方法
<jsp:getProperty name="beanTest" property="name"  ></jsp:getProperty>
只有这一种方式的
原文地址:https://www.cnblogs.com/wanglei-134/p/3187298.html