正文

strutsNotes(4)2008-04-01 20:22:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/ghlat520/33789.html

分享到:

 第四章 struts的标签库     1)在jsp页面中应该避免使用java脚本,因为这些脚本会大大降低jsp页面的可维护性     2)而通过标签可以大大减少jsp页面中的脚本,象jstl(jsp标准标签库)     3)为了更好的与struts结合,在struts框架中已经集成了自己的标签库      4)struts主要提供了以下三个标签库:         A:html标签库。用于生成html基本的标签         B:bean用于完成程序国际化,输出Struts的ActionForm的属性值         C:logic.用于完成循环,选择流程控制等     5)在使用struts标签库必须要导入对应的标签库。       <%@ taglib uri="http://struts.apache.org/tags-html"  prefix="html"  %>  导入html标签库       <%@ taglib uri="http://struts.apache.org/tags-bean"  prefix="bean"  %>  导入bean标签库       <%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %> 导入logic标签库    6)对于bean标签与logic标签而言,通常会有两种属性(******重要**********)       id属性:该属性用来说明存入page范围内的变量的值      name属性:从四种范围内取出变量的值。表示从四种范围内取出值(page,request,session,application)                            html标签库        1)struts的html标签通过浏览器解析之后最终变成标准的html标签        2)Struts的html标签比标准的html标签功能更加强大,并且能够与struts实现很好的结合        3)但是即使不要Struts的html标签,使用标准的html标签也能够进行Struts框架的开发        4)Struts的html标签库里面的标签大致可以分成三类:           A:生成html元素的标签                           B:生成html表单的标签           C:显示错误或正常消息的标签  <a                                              生成html元素的标签             1)<html:link>相当于<a href>标签                 属性:                   A)href:要链接的目的地。比如:<html:link  href="a.jsp">进入a.jsp</html:link>                   B)forward:要链接到全局转发<html:link forward="msg" >this link</html:link>                      首先要在struts-config.xml中配置全局转发                       <global-forwards>                            <forward name="msg" path="/msg.jsp"/>                       </global-forwards>                   C)值得注意的是超连接也可以连接action。此时属于get提交,因此不用ActionForm.                     比如:                       <html:link href="SumAction.do?n=4" >this link</html:link>                       举例:通过本页面进行处理。之后把结果返回本页面,而不是其它的页面                       创建一个Action,但是不需要创建ActionForm,然后配置此Action的forward                       让此Action处理完结果之后,跳转回自己                   D)该标签最具有特色是可以把四种范围内(request,page,session.applicaion)内的                     变量或javabean的值做为参数进行传递                     比如:              pageContext.setAttribute("uid","chen");                                   <html:link page="msg.jsp" paramId="uid" paramName="uid">this pram link</html:link>              paramId:指定get参数名              paramName:指定参数的值             再比如:              <jsp:useBean id="sum" class="ht.NetBook.sumBean" scope="page"/>              <jsp:setProperty name="sum" property="n1" value="10"/>                 <html:link href="msg.jsp" paramId="n1" paramName="sum" paramProperty="n1">               其中:               paramName:指定javaBean的名字               paramProperty:指定javaBean属性,该连接会自动的把javaBean的属性取出来做为get的提交值                             举例:通过数据库取出员工的基本资料,然后显示,注意放入删除超连接                     思路:通过javaBean结合超连接进行                2)<html:img src="ab.jgp"/>图像标签。相当于<img>标签                                                          生成html表单元素的标签                          1)<html:form action="Action.do">                  A:用于生成表单                 B:action用来指定跳转到struts-config.xml中配置的Action                     对于<html:form>的说明:                              C:struts表单元素的标签一定要嵌套在<html:form>标签里面,否则会出现错误                         比如:                           <form id="frm" action="testAction.do"> //这是html表单                               单价:<html:text property="price"/>//而这是struts表单元素                               </form>                  D:一个Action可以没有对应的ActionForm,但是<html:form action>对应的Action一定要                    有ActionForm,否则会出现错误                     比如:                        <html:form  action="testAction.do">                               </html:form>                    而struts-config.xml的Action配置如下:                     <action  path="/testAction" type="ht.NetBook.struts.Action.testAction" />                      即表示testAction没有与之对应的ActionFrom,运行时会出现以下错误:                          Cannot retrieve definition for form bean null on action testAction.do                       如果form Bean为空,则不能编译                                    E:<html:form>不需要加id或name属性,它经过IE解释之后其名字自动变成与之对应的                     ActionForm的名字,这也就是为什么如果不为Action指定ActionForm会出错的原因                F:结论:如果要使用struts表单元素必须要放在<html:form>中,而此                     <html:form>对应的Action一定要有ActionForm才可以正常运行,                      如果不使用struts表单元素,也可以使用普通的html标签,同样                     可以与struts结合,但是struts里面的有些标签更加智能                                                   3)<html:button property="register"/>生成普通的按钮             4)<html:submit>提交</html:submit>生成提交按钮             5)<html:reset>重置</html:reset>生成重置按钮              6)<html:text property="uid"/>用于生成文本框                A:prperty中的值一定要与ActionForm中的属性值保持一致                B:struts里面的文本框在表单提交以后值会依然保留这与一般的html标签不一样                 C:可以使用<html:text property="uid" value="值"/>的方法赋值给文本框                    7)<html:reset>复位</html:reset>与普通html的重置按钮一样             8)<html:submit>提交</html:submit>与普通的html的提交按钮一致                  9)<html:checkbox>相当于html的checkbox                格式:<html:checkbox property="discount"/>                      其中的property中的属性名一定要与ActionForm中类型为布尔类型的属性关联                    比如:                         public class discountActionForm extends ActionForm                          {                                private boolean discount=true;//此处将会使checkbox自动勾选                          }                     则可以使用<html:checkbox property="discount"/>与该discount的关联                   说明:                    1)该标签一定要配合普通隐藏域标签才能够正常使用,否则只有勾选一次,以后不管是否                        勾选其值都是true                       <html:checkbox property="discount"/>                       <input type="hidden" name="discount" value="flase">                    2)可以Action中的Excecute方法里面。去检查discount的值                        discountActionForm frm=(discountActionForm)form;                        if (frm.getDiscount()) {做一些事件}                   3)该标签默认情况是在页面初始化时不会自动选中,可以设置ActionForm里面的属性默认                     值为true.比如:                     举例:让用户输入商品单价与商品数量,实付款,用是否打折来显示应付款与找零                 6)<html:multibox/>产生一组复选框与<html:checkbox>的区别在于,它可以与                                 ActionForm中数组属性对应                    比如:      <html:multibox property="love" value="唱歌"/>唱歌<br>                    <html:multibox property="love" value="跳舞"/>跳舞<br>                    <html:multibox property="love" value="足球"/>足球<br>                    <html:multibox property="love" value="音乐"/>音乐<br>                  说明:                     1)其中每个mulitbox的property值必须一样,才可以做为一个复选框组。                     2)property="love"中的love必须是在ActionForm中定义的数组                        private String love[];                        public String[] getLove()                             {                 return love;                     }                        public void setLove(String[] love)                              {                  this.love = love;                      }                    3)当用户选中某个复选框后,会把该复选框的值存入ActionForm中的love数组中                    4)与<html:checkbox>一样,也存在同样的缺点,就是如果选中之后取消勾选此时                      还是会继续勾选。解决的方案是增加一个隐藏域                      <html:multibox property="love" value="唱歌"/>唱歌<br>                      <html:multibox property="love" value="跳舞"/>跳舞<br>                      <html:multibox property="love" value="足球"/>足球<br>                      <html:multibox property="love" value="音乐"/>音乐<br>                      <input type="hidden" name="love"/>//注意不要value=flae                    5)加了隐藏域之后,struts会把隐藏域的值也加入到love数组中,所以在使用时,                      应该去掉。for(int i=0;i<frm.getLove().length-1;i++) //长度减1去掉                     举例:                          1)爱好,把人的爱好放入数据库中保存                         2)各模块之间的权限管理                  7)<html:radio>产生一组单选框      <html:radio property="degree" value="1">高中</html:radio><br>       <html:radio property="degree" value="2">中专</html:radio><br>       <html:radio property="degree" value="3">大学</html:radio><br>       <html:radio property="degree" value="4">小学</html:radio><br>                    说明:                      1)property的值必须与ActionForm中的某个属性关联,以后选择了那个单选框                        Struts就会与之对应的值赋给ActionForm的关联的属性                      2)单选框不需要隐藏域,就可以正常的工作                      3)如何要设置默认的选项,可以把ActionForm中关联的属性值设置成单选框中                        与之对应的值                            public class discountActionForm                               {                                      private String degree="1";//设置默认值。                               }这样"高中"就默认选中了。因为ActionForm中的degree关联的值与                                "高中"单选框的值相同                        举例:                           1)爱好                           2)投票---要求从数据库读取投票项,进行投票                  8) <html:select property="color">下拉列表框                      A:一个<html:select>会包括多个<html:option>                      B:property属性值与ActionForm中对应的属性关联。                           public class ActionForm extends ActionForm                              {                               private String color;                               get...                               set...                              }                      C:<html:option>中有一个显示值与实际值                       比如:                           <html:select property="color">                           <html:option value="yellow">黄色</html:option>                           <html:option value="green">绿色</html:option>                           <html:option value="blue">蓝色</html:option>                           </html:select>                      D:<html:select>不用设置默认值,它会自动选中第一项                      D:该类型的下拉列表一般适合于不与数据库发生交互的情况                                      9)<html:options collection>该options非常适合于与数据库进行交互                   比如:<html:options collection="save" labelProperty="voteItem" property="id"/>                    A:<html:options>标签必须放在<html:select>里面                    B:collection表示Javabean的一个集合,该集合一定要放在四个范围里面                    C:labelProperty表示显示的值                    D:property选中之后的值                   比如:一个jsp页面                     <%                          java.util.List save=votes.getAllvote();//返回投票的javabean的集合                          request.setAttribute("save",save);                      %>                      <html:select property="id"> //此处的id一定要与ActionForm中的属性对应                        <html:options collection="save" labelProperty="voteItem" property="id"/>                        </html:select>            //此处不能用${save}                                           ActionForm的定义                                public class voteActionForm extends ActionForm                       {                         private String id;                          get...                          set...                      }                      JavaBean(描述类vote)的定义                       public class vote                             {                          private String id;                          private String voteItem;                                 get...                                 set...                            }                                               管理类(votes)的定义                         pulbic class votes                           {                              public static List getAllvote()                                  {                                      vote newInstance=new vote();                 newInstance.setId(rs.getInt(1));                 newInstance.setVoteItem(rs.getString(2));                 list.add(newInstance);                                      return list;                                  }                           }                      举例:                       1)用<html:select>结合<html:options>来重做投车票项目                       2)让用户选择部门编号,查询出对应的职工信息。要求部门用下拉框实现                 10)<html:file property="file">文件上传组件                     A:<html:file>必须嵌套在<html:form>标签中                     B:<html:form>标签的method必须为post提交                     C:<html:form>中的enctype必须为multipart/form-data method="post"                      D:<html:file>标签必须设置property属性。这个属性和ActionForm中的                       的FormFile类型的属性对应                     比如:              ====================ActionForm=====================================                       private private org.apache.struts.upload.FormFile file;                       public get...                       public set....             ====================================================================                      jsp页面             <html:form action="SumAction.do" method="post" enctype="multipart/form-data" >              <html:file property="file"/>注意这里面的file与ActionForm中的file属性对应             <html:submit>提交</html:submit>             </html:form>                              ============================Action====================================                    uploadActionForm frm=(uploadActionForm)from;                    FormFile file=frm.getFile();//得到file对像      String fileName=file.getFileName();//得到要上传的文件名      String dir=servlet.getServletContext().getRealPath("upload");                    //得到文件的路径,这里面统一上传到upload文件夹下面(WebRoot\upload)      String serverPath=dir+"\\"+fileName;//服务器的实际文件路径             InputStream inputStream=file.getInputStream();//输入流      OutputStream outputStream=new FileOutputStream(serverPath);//输出流      int readBinary=0;             byte buffer[]=new byte[8192];//缓冲区为1024*8也就是8字节      while((readBinary=inputStream.read(buffer, 0, 8192))!=-1)      {      //从inputStream中每次读取8字节的的数据到byte数据组中       outputStream.write(buffer, 0, readBinary);                                   //写入到outputStream中      }      outputStream.close();      inputStream.close();                    ===========================inputStream.read的介绍==================               inputStream.read(byte b[],int off,int len)               读取len个字节,放置到下标off开始的字节数组b中,返回实际读取的字节的数量               一般off都是零,因为是从数组的第一个位置开始填充         =============================================================================                                           Bean标签库           1)Bean标签库中的标签可以访问已经存在的javaBean以及它的属性,还可以定义新的                          javaBean,把它存放在指定的范围内。还用于输出国际化信息           2)要使用bean标签库,需要加入               <%@ taglib uri="http://struts.apache.org/tags-bean"  prefix="bean" %>标签库                                       <bean:parameter>标签                 A:这个标签主要的功能是用于将请求的参数(get提交与post提交)封装成一个java脚本可以                   访问的变量                 B:<bean:parameter id="a" name="id"/>                    id:要page范围中的变量的名。一般用id表示                    name:属性是参数名                    上述的代码表示把请求参数名为id的值保存到page范围中变量a中去                   比如:                    源页面:                     < html:link href = "/StrutsTagDemo/parameter_2.jsp?custId=1127"/>                     接受页面:                    < bean:parameter id = "custId" name = "custId" />                     < bean:write name = "custId" />                     会输出1127                 C:<bean:parameter>相当于一个java脚本                     <bean:parameter id = "custId" name = "custId" /> 相当于                       <%                         String custId=request.getParameter("custId")                       %>                    而< bean:write name = "custId" /> 相当于                      <%                          out.print("custid")                      %>                   D:<bean:parameter id = "custId" name = "custId" />把值取过来之后,完全                    可以java脚本进行访问                    比如:                      <bean:parameter id = "custId" name = "custId" />                       <%                          custId=custId+"abcd"//直接对custId进行处理                       %>                                                                           <bean:message key="index.passWord"/>                        A:<bean:message>是用在国际化功能中输出国际化消息的                        B:<bean:message key="index.passWord"/> 其中的key与国际化资源文件对应                        C:实现国际化的步骤:                          1)在web应用程序的class文件夹(一定要在此文件夹)下面创建一个resource包(名                            字可以随便取)                          2)在resource包下面创建两个文件,文件名固定不能修改.                             格式形如:键=值                             application_en.properties  其中的内容为(代表英文)                            ==========================================                                 index.title=On Line  NetBook Manager                                 index.userName=userName                                 index.passWord=password                                 index.submit=submit                                 index.reset=reset                          ==========================================                           application_zh.properties 其中的内容为(代表中文)                                                                                                                           ==========================================                                 index.title=在线图书管理系统                                 index.userName=用户名                                 index.passWord=密码                                 index.submit=提交                                 index.reset=重置                          ==========================================                          3)如果是中文为了避免乱码。要通过如下命令进行转换                                 native2ascii -encoding gb2312 源文件                              可直接在cmd模式下,通过拖曳的方法得到中文文件对应的编码                            index.title=\u5728\u7ebf\u56fe\u4e66\u7ba1\u7406\u7cfb\u7edf                            index.userName=\u7528\u6237\u540d                            index.passWord=\u5bc6  \u7801                            index.submit=\u63d0 \u4ea4                            index.reset=\u91cd \u7f6e复制后直接付盖application_zh.properties                         4)配置struts-config.xml文件,在<message-resources>节点下配置属性                            <message-resources parameter="resource.application" />                            注意这里面的resource表示在class文件夹的resource下面有application                            对应的两个中英文资源文件。                         5)在jsp页面里面可以通过                             <bean:message key="index.passWord"/>来从资源文件里面获取                         6)可以在IE里面的工具-->internet选项-->常规--->语言                           在里面加入"中文[zh]"与"英文[en]"通过改变顺序会发现jsp页面会自动加载                           对应的中英文资源文件                         7)如果失败,请注意重新启动tomcat之后, 再试验                         8)如果想实现动态中英文转化,可以通过两个超级连接,连到一个action里面                           进行处理                            <a href="Action.do?en=0">英文</a>                            <a href="Action.do?en=1">中文</a>           ================================================Actioin代码======================              import org.apache.struts.Globals; //注意导入以下包              import java.util.Locale;              int en=Integer.parseInt(request.getParameter("en"));                 if (en==0)       {                request.getSession().setAttribute(Globals.LOCALE_KEY,Locale.ENGLISH);       }     else     {              request.getSession().setAttribute(Globals.LOCALE_KEY,Locale.CHINA);     }           return mapping.findForward("index");       =================================================Action=============================                      <bean:writer>标签             1)用来输出存放在四种范围内的数据             2)格式:<bean:write name="要输出的四种范围内的变量名"/>             3)可以输出普通的变量                     <%                          String uid="chen";                   equest.setAttribute("uid",uid); //如果不把uid放入request范围内,则                      %>                                    //bean:write不能输出                     <bean:write name="uid"/> 相当于${uid}             4)输出JavaBean的值               格式:bean:write name="已经存放在四种范围内的javabean的变量名" property="要输出                          的JavaBean的属性"/>                 <%                     worker d=new worker();                      d.setId("w1");                     d.setName("chan");                     request.setAttribute("d",d);                 %>                         <bean:write name="d" property="name"/>                         相当于${d.name}                  所以如果要输出javaBean的内容,一般直接用EL就行了.                 举例:让用户输入一个工号,检验该工号在不在数据库中,如果在下面的                       输入框中显示对应的详细资料。如果没有则输出找不到该职工,如果找到                       职工,则可以修改职工内容        ==============================================jsp页面=========================                    ${msg} 用来显示出错误            <html:form  action="修改职工的Action.do"> //                       工号:<html:text property="id" value="${emp.id}"/>                    <html:button property="check" onclick="window.location='检查是否存在的.do?                        id='+表单名(会自动成为修改职工Action对应的ActionForm名).id.value"/>                    姓名:<html:text property="name" value="${emp.name}"/><br>                    职位:<html:text property="job" value="${emp.job}"/>                   html:submit>提交</html:submit><html:reset>重置</html:reset>                  </html:form>        =================================检查是否存在的Action========================         int id=Integer.parseInt(request.getParameter("id"));  emp instance=emps.getEmpById(id);                if (instance==null)  {      request.setAttribute("msg","<script>alert('找不到该职工')</script>");                        不能使用out.print("<script>alert('找不到该职工')</script>")原因是该脚本                       为客户端脚本,而mapping.findForward("show")为服务器脚本先于它执行,解决                       的方法是把数据传到show.jsp中,再它的页面中提示  }                          request.setAttribute("emp", instance);  return mapping.findForward("show");           ================================================================================== 

阅读(4518) | 评论(1)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

loading...
您需要登录后才能评论,请 登录 或者 注册