Javabean的设计原则
- 公有类
- 无参公有构造方法
- 私有属性
- getter和setter方法
在Jsp页面中如何使用Javabeans?
像使用普通Java类一样,创建JavaBeans实例。
在JSP页面中通常使用JSP动作标签使用JavaBeans。
useBeans动作
setProperty动作
getProperty动作
示例代码:
package com.po; /** * 用户类 */ public class Users { private String username; private String password; public Users(){ } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Login Demo</title> </head> <body> <h1>系统登录</h1> <hr> <form name="loginForm" action="do_login.jsp?myPass=888888&myUser=Vincent" method="post"> <table> <tr> <td>Username:</td> <td><input type="text" name="username" value="" placeholder="username" /></td> </tr> <tr> <td>Password:</td> <td><input type="password" name="password" value="" placeholder="password" /></td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="Login"/></td> </tr> </table> </form> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>DoLogin Demo</title> </head> <body> <jsp:useBean id="myUsers" class="com.po.Users" scope="page" /> <h1>setProperty动作元素</h1> <hr> <!-- 根据表单自动匹配所有的属性 --> <jsp:setProperty name="myUsers" property="*" /> Username: <%=myUsers.getUsername()%><br> Password: <%=myUsers.getPassword()%><br> <!-- 根据表单匹配所有部分的属性 --> <jsp:setProperty name="myUsers" property="username" /> <jsp:setProperty name="myUsers" property="password" /> Username: <%=myUsers.getUsername()%><br> Password: <%=myUsers.getPassword()%><br> <!-- 跟表单无关,通过手工赋值给属性 --> <jsp:setProperty name="myUsers" property="username" value="Menroe" /> <jsp:setProperty name="myUsers" property="password" value="123456" /> Username: <%=myUsers.getUsername()%><br> Password: <%=myUsers.getPassword()%><br> <!-- 通过Request获取参数属性 --> <jsp:setProperty name="myUsers" property="username" param="myUser" /> <jsp:setProperty name="myUsers" property="password" param="myPass" /> Username: <%=myUsers.getUsername()%><br> Password: <%=myUsers.getPassword()%><br> </body> </html>