JEE_JavaBean
JavaBean:通过Java代码封装的Java类,以实现JSP页面中(HTML/CSS代码,JSP代码)和Java代码的分离和代码的重用。JavaBean封装后可在JSP页面中调用.
JavaBean严格规范:
1.公共的无参的构造方法(无参:<jsp:useBean>),
2.类的声明是非final型的(数据可以修改),
3.实现可序列化接口,
1.JavaBean中的属性可设置为private防止外部访问,但需对外提供public的访问方法(get/set方法:<jsp:getProperty>,<jsp:setProperty>).
示例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.lyq.Bean; /** * JavaBean对象 * @author Li YongQiang */ public class GreetingBean { // 用户名 private String userName; // 问候指定用户 public String getUserName() { return userName + ",你好!" ; } // 设置用户 public void setUserName(String userName) { this.userName = userName; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@page import="com.lyq.Bean.GreetingBean"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>主页</title> </head> <body> <% GreetingBean bean = new GreetingBean(); bean.setUserName("明日科技"); out.print(bean.getUserName()); %> </body> </html>
例:通过非可视化的JavaBean,封装邮箱地址对象,通过JSP页面调用此对象,来验证邮箱地址是否合法.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.lyq.bean; import java.io.Serializable; /** * 邮件对象JavaBean * @author Li YongQiang */ public class Email implements Serializable { // serialVersionUID 值 private static final long serialVersionUID = 1L;//序列号版本号 // Email地址 private String mailAdd; // 是否是一个标准的Email地址 private boolean eamil; /** * 默认无参的构造方法 */ public Email() { } /** * 构造方法 * @param mailAdd Email地址 */ public Email(String mailAdd) { this.mailAdd = mailAdd; } /** * 是否是一个标准的Email地址 * @return 布尔值 */ public boolean isEamil() { // 正则表达式,定义邮箱格式 String regex = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"; // matches()方法可判断字符串是否与正则表达式匹配 if (mailAdd.matches(regex)) { // eamil为真 eamil = true; } // 返回eamil return eamil; } public String getMailAdd() { return mailAdd; } public void setMailAdd(String mailAdd) { this.mailAdd = mailAdd; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <!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=GB18030"> <title>Insert title here</title> </head> <body> <form action="result.jsp" method="post"> <table align="center" width="300" border="1" height="150"> <tr> <td colspan="2" align="center"> <b>邮箱认证系统</b> </td> </tr> <tr> <td align="right">邮箱地址:</td> <td><input type="text" name="mailAdd"/></td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" /> </td> </tr> </table> </form> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@page import="com.lyq.bean.Email"%><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>Insert title here</title> </head> <body> <div align="center"> <% // 获取邮箱地址 String mailAdd = request.getParameter("mailAdd"); // 实例化Email,并对mailAdd赋值 Email email = new Email(mailAdd); // 判断是否是标准的邮箱地址 if(email.isEamil()){ out.print(mailAdd + " <br>是一个标准的邮箱地址!<br>"); }else{ out.print(mailAdd + " <br>不是一个标准的邮箱地址!<br>"); } %> <a href="index.jsp">返回</a> </div> </body> </html>
JavaBean应用:
在JSP页面中应用JavaBean非常简单,主要通过JSP动作标签<jsp:useBean>,<jsp:getProperty>,<jsp:setProperty>来实现对JavaBean对象的操作,但前提是所编写的JavaBean要符合JavaBean规范,只有严格遵循JavaBean规范,在JSP页面中才能方便地调用和操作JavaBean对象.(内部的操作也是通过规范化的JavaBean进行处理的)
例:对JavaBean属性赋值,获取JavaBean属性信息
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.lyq.bean; /** * 商品对象 * @author Li YongQiang */ public class Produce { // 商品名称 private String name ; // 商品价格 private double price ; // 数量 private int count ; // 出厂地址 private String factoryAdd ; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public String getFactoryAdd() { return factoryAdd; } public void setFactoryAdd(String factoryAdd) { this.factoryAdd = factoryAdd; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <!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=GB18030"> <title>Insert title here</title> </head> <body> <jsp:useBean id="produce" class="com.lyq.bean.Produce"></jsp:useBean> //实例化JavaBean对象 <jsp:setProperty property="name" name="produce" value="洗衣机"/> <jsp:setProperty property="price" name="produce" value="8888.88"/> <jsp:setProperty property="count" name="produce" value="88"/> <jsp:setProperty property="factoryAdd" name="produce" value="广东省xxx公司"/> <div> <ul> <li> 商品名称:<jsp:getProperty property="name" name="produce"/> </li> <li> 价格:<jsp:getProperty property="price" name="produce"/> </li> <li> 数量:<jsp:getProperty property="count" name="produce"/> </li> <li> 厂址:<jsp:getProperty property="factoryAdd" name="produce"/> </li> </ul> </div> </body> </html>
例:在JSP页面中应用JavaBean
reg.jsp页面<jsp:userBean>标签实例化了JavaBean,然后通过<jsp:setProperty name="person" property="*"/>对Person类中的所有属性进行赋值.
使用这种方法的前提是表单中name属性的名称要和JavaBean中所定义的属性名称一致.
如若表单中name属性的名称和JavaBean中的属性名称不一致,则必须通过<jsp:setProperty>标签中的param属性来指定表单中的属性.
如表单中name为"username",可以使用<jsp:setProperty name="person" property="name" param="username"/>对齐进行赋值.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.lyq.bean; /** * 用户信息 * @author Li YongQiang */ public class Person { // 姓名 private String name; // 年龄 private int age; // 性别 private String sex; // 住址 private String add; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAdd() { return add; } public void setAdd(String add) { this.add = add; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <!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=GB18030"> <title>Insert title here</title> </head> <body> <form action="reg.jsp" method="post"> <table align="center" width="400" height="200" border="1"> <tr> <td align="center" colspan="2" height="40"> <b>添加用户信息</b> </td> </tr> <tr> <td align="right">姓 名:</td> <td> <input type="text" name="name"> </td> </tr> <tr> <td align="right">年 龄:</td> <td> <input type="text" name="age"> </td> </tr> <tr> <td align="right">性 别:</td> <td> <input type="text" name="sex"> </td> </tr> <tr> <td align="right">住 址:</td> <td> <input type="text" name="add"> </td> </tr> <tr> <td align="center" colspan="2"> <input type="submit" value="添 加"> </td> </tr> </table> </form> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> //Java代码 <!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=GB18030"> <title>Insert title here</title> </head> <body> <%request.setCharacterEncoding("GB18030");%> <jsp:useBean id="person" class="com.lyq.bean.Person" scope="page"> <jsp:setProperty name="person" property="*"/> </jsp:useBean> <table align="center" width="400"> <tr> <td align="right">姓 名:</td> <td> <jsp:getProperty property="name" name="person"/> </td> </tr> <tr> <td align="right">年 龄:</td> <td> <jsp:getProperty property="age" name="person"/> </td> </tr> <tr> <td align="right">性 别:</td> <td> <jsp:getProperty property="sex" name="person"/> </td> </tr> <tr> <td align="right">住 址:</td> <td> <jsp:getProperty property="add" name="person"/> </td> </tr> </table> </body> </html>
JavaBean在JSP中的应用:
随着学习了JSTL标签库及EL表达式或一些MVC框架后,就可以完全通过标签来取代所有JSP页面中的Java代码了,真正实现代码分离.
上例的reg.jsp页面中仍含有处理中文编码的Java代码,此处给出一例,实现JavaBean解决中文编码问题:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.lyq.bean; /** * 新闻对象 * @author Li YongQiang */ public class News { // 标题 private String title; // 内容 private String content; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.lyq.bean; import java.io.UnsupportedEncodingException; /** * 字符编码处理JavaBean * @author Li YongQiang */ public class CharactorEncoding { /** * 构造方法 */ public CharactorEncoding(){ } /** * 对字符进行转码处理 * @param str 要转码的字符串 * @return 编码后的字符串 */ public String toString(String str){ // 转换字符 String text = ""; // 判断要转码的字符串是否有效 if(str != null && !"".equals(str)){ try { // 将字符串进行编码处理 text = new String(str.getBytes("iso8859-1"),"GB18030"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } // 返回后的字符串 return text; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <!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=GB18030"> <title>XX新闻发布系统</title> </head> <body> <form action="release.jsp" method="post"> <table align="center" width="450" height="260" border="1"> <tr> <td align="center" colspan="2" height="40" > <b>新闻发布</b> </td> </tr> <tr> <td align="right">标 题:</td> <td> <input type="text" name="title" size="30"> </td> </tr> <tr> <td align="right">内 容:</td> <td> <textarea name="content" rows="8" cols="40"></textarea> </td> </tr> <tr> <td align="center" colspan="2"> <input type="submit" value="发 布"> </td> </tr> </table> </form> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <!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=GB18030"> <title>发布结果</title> <style type="text/css"> #container{ width: 450px; border: solid 1px; padding: 20px; } #title{ font-size: 16px; font-weight: bold; color: #3399FF; } #content{ font-size: 12px; text-align: left; } </style> </head> <body> <jsp:useBean id="news" class="com.lyq.bean.News"></jsp:useBean> <jsp:useBean id="encoding" class="com.lyq.bean.CharactorEncoding"></jsp:useBean> <jsp:setProperty property="*" name="news"/> <div align="center"> <div id="container"> <div id="title"> <%= encoding.toString(news.getTitle())%> </div> <hr> <div id="content"> <%= encoding.toString(news.getContent())%> </div> </div> </div> </body> </html>
例:获取当前时间的JavaBean
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.lyq.bean; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * 获取当前时间的JavaBean * @author Li YongQiang * */ public class DateBean { // 日期及时间 private String dateTime; // 星期 private String week; // Calendar对象 private Calendar calendar = Calendar.getInstance(); /** * 获取当前日期及时间 * @return 日期及时间的字符串 */ public String getDateTime() { // 获取当前时间 Date currDate = Calendar.getInstance().getTime(); // 实例化SimpleDateFormat SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH点mm分ss秒"); // 格式化日期时间 dateTime = sdf.format(currDate); // 返回日期及时间的字符串 return dateTime; } /** * 获取星期几 * @return 返回星期字符串 */ public String getWeek() { // 定义数组 String[] weeks = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; // 获取一星期的某天 int index = calendar.get(Calendar.DAY_OF_WEEK); // 获取星期几 week = weeks[index - 1]; // 返回星期字符串 return week; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <!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=GB18030"> <title>电子时钟</title> <style type="text/css"> #clock{ width:420px; height:80px; background:#E0E0E0; font-size: 25px; font-weight: bold; border: solid 5px orange; padding: 20px; } #week{ padding-top:15px; color: #0080FF; } </style> <meta http-equiv="Refresh" content="1"> </head> <body> <jsp:useBean id="date" class="com.lyq.bean.DateBean" scope="application"></jsp:useBean> <div align="center"> <div id="clock"> <div id="time"> <jsp:getProperty property="dateTime" name="date"/> </div> <div id="week"> <jsp:getProperty property="week" name="date"/> </div> </div> </div> </body> </html>
例:数组转换成字符串
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.lyq.bean; import java.io.Serializable; /** * 调查问卷 * @author Li YongQiang */ public class Paper implements Serializable { private static final long serialVersionUID = 1L; // 编程语言 private String[] languages; // 掌握技术 private String[] technics; // 部分 private String[] parts; public Paper(){ } public String[] getLanguages() { return languages; } public void setLanguages(String[] languages) { this.languages = languages; } public String[] getTechnics() { return technics; } public void setTechnics(String[] technics) { this.technics = technics; } public String[] getParts() { return parts; } public void setParts(String[] parts) { this.parts = parts; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.lyq.bean; /** * 转换数组的JavaBean * @author Li YongQiang */ public class Convert { /** * 将数组转换成为字符串 * @param arr 数组 * @return 字符串 */ public String arr2Str(String[] arr){ // 实例化StringBuffer StringBuffer sb = new StringBuffer(); // 判断arr是否为有效数组 if(arr != null && arr.length > 0){ // 遍历数组 for (String s : arr) { // 将字符串追加到StringBuffer中 sb.append(s); // 将字符串追加到StringBuffer中 sb.append(","); } // 判断字符串长度是否有效 if(sb.length() > 0){ // 截取字符 sb = sb.deleteCharAt(sb.length() - 1); } } // 返回字符串 return sb.toString(); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <!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=GB18030"> <title>调查问卷</title> </head> <body> <form action="reg.jsp" method="post"> <div> <h1>调查问卷</h1> <hr/> <ul> <li>你经常用哪些编程语言开发程序:</li> <li> <input type="checkbox" name="languages" value="JAVA">JAVA <input type="checkbox" name="languages" value="PHP">PHP <input type="checkbox" name="languages" value=".NET">.NET <input type="checkbox" name="languages" value="VC++">VC++ </li> </ul> <ul> <li>你目前所掌握的技术:</li> <li> <input type="checkbox" name="technics" value="HTML">HTML <input type="checkbox" name="technics" value="JAVA BEAN">JAVA BEAN <input type="checkbox" name="technics" value="JSP">JSP <input type="checkbox" name="technics" value="SERVLET">SERVLET </li> </ul> <ul> <li>在学习中哪一部分感觉有困难:</li> <li> <input type="checkbox" name="parts" value="JSP">JSP <input type="checkbox" name="parts" value="STRUTS">STRUTS </li> </ul> <input type="submit" value="提 交"> </div> </form> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <!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=GB18030"> <title>调查结果</title> </head> <body> <jsp:useBean id="paper" class="com.lyq.bean.Paper"></jsp:useBean> <jsp:useBean id="convert" class="com.lyq.bean.Convert"></jsp:useBean> <jsp:setProperty property="*" name="paper"/> <div> <h1>调查结果</h1> <hr/> <ul> <li> 你经常用使用的编程语言:<%= convert.arr2Str(paper.getLanguages()) %> 。 </li> <li> 你目前所掌握的技术:<%= convert.arr2Str(paper.getTechnics()) %> 。 </li> <li> 在学习中感觉有困难的部分:<%= convert.arr2Str(paper.getParts()) %> 。 </li> </ul> </div> </body> </html>