在JSP页面中,处理中文字符经常会出现字符乱码的现象,特别是通过表单传递中文数据时容易产生。它的解决办法有很多,如将request的字符集指定为中文字符集,编写JavaBean对乱码字符进行转码等。下面就通过实例编写JavaBean对象来解决中文乱码问题。
例1.1 本实例通过编写对字符转码的JavaBean,来解决在新闻发布系统中,发布中文信息的乱码现象,其开发步骤如下。
(1)创建名称为News的类,将其放置于com.cn.gao包中,实现对新闻信息实体对象的封装。关键代码如下:
package com.cn.gao; 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; } }
(2)创建对字符编码进行处理的JavaBean,它的名称为CharactorEncoding。在该类中编写toString()方法对字符编码进行转换。关键代码如下:
package com.cn.gao; import java.io.UnsupportedEncodingException; 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("ISO-8859-1"),"UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return text; } }
CharactorEncoding类通过toString()方法对字符串参数进行编码,实例中将编码设置为UTF-8,因为在JSP页面中的编码也是UTF-8,这里将其进行统一。
String类的getBytes()方法的作用,是按给定的字符编码将此字符串编码到byte序列,并将结果存储到新的byte数组;而String类的构造方法String(byte[] bytes,Charset charset)是通过使用指定的字符编码解码指定的byte数组,构造一个新的字符串,实例中应用这两个方法,实现了构造UTF-8编码的字符串。
(3)创建名称为news.jsp的页面,它是程序中的主页面,用于放置发布新闻信息的表单。关键代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'news.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </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>
(4) 创建名称为release.jsp的页面,用于对发布新闻信息的表单请求进行处理。关键代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'release.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <jsp:useBean id="news" class="com.cn.gao.News"></jsp:useBean> <jsp:useBean id="encoding" class="com.cn.gao.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是用java语言所写的可重用组件,它可以是一个实体类对象,也可以是一个业务逻辑的处理,但编写JavaBean要遵循JavaBean规范。下面通过实例在JSP页面中调用获取当前时间的JavaBean。
例2.1 创建获取当前时间的JavaBean对象,该对象既可以获取当前的日期及时间,同时可以获取今天是星期几。通过在JSP页面调用该JavaBean对象,实现在网页中创建一个简易的电子时钟。
(1)创建名称为DateBean的类,将其放置于com.cn.gao包中,主要对当前时间、星期进行封装。关键代码如下:
package com.cn.gao; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import sun.java2d.pipe.SpanShapeRenderer.Simple; public class DateBean { private String dateTime; private String week; private Calendar calendar = Calendar.getInstance(); /** * 获取当前日期及时间 * @return 日期及时间的字符串 */ public String getDateTime() { //获取当前时间 Date currDate = Calendar.getInstance().getTime(); 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; } }
(2)创建名称为clock.jsp的页面,它是程序中的主页。在clock.jsp页面中实例化DateBean对象,并获取当前日期时间及星期实现电子时钟效果。关键代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> <title>电子时钟</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <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.cn.gao.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>
程序运行效果如下:
在程序开发中,将数组转换成为字符串是经常被用到的,如表单中的复选框按钮,在提交之后就是一个数组对象,由于数组对象在业务处理中不方便,所以在实际应用中通过将其转换成字符串后再进行处理。
例3.1 创建字符串转换成数组的JavaBean,实现对“问卷调查”表单中复选框的数值的处理。
(1)创建名称为Paper的类,将其放置于com.cn.gao包中,对调查问卷进行封装。关键代码如下:
package com.cn.gao; import java.io.Serializable; 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; } }
(2)创建将数组转换成字符串的JavaBean对象,它的名称为Convert。在该类中编写arr2Str()方法,将数组对象转换成为指定格式的字符串。关键代码如下:
package com.cn.gao; public class Convert { /** * 将数组转换成为字符串 * @param arr 数组 * @return 字符串 */ public String arr2Str(String[] arr){ StringBuffer sb = new StringBuffer(); if(arr!=null&&arr.length>0){ for(String s:arr){ sb.append(s); sb.append(","); } if(sb.length()>0){ sb = sb.deleteCharAt(sb.length() - 1); } } return sb.toString(); } }
(3)创建程序中的首页dcwj.jsp,在该页面中放置调查问卷所使用的表单。关键代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'dcwj.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </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>
(4)创建名称为reg.jsp的页面,用于对dcwj.jsp页面表单提交请求进行处理,将用户所提交的调查问卷结果输出到页面中。关键代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'reg.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <jsp:useBean id="paper" class="com.cn.gao.Paper"></jsp:useBean> <jsp:useBean id="convert" class="com.cn.gao.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>