Struts标签库

来源:互联网 发布:明道软件 拉钩 编辑:程序博客网 时间:2024/05/16 13:47

 (转自http://www.blogjava.net//mrklmxy/archive/2007/07/16/130542.html)

一.html标签
1.html元素的标签:
a1.<html:link forward="index"> 链接<global-forwards>中的name </html:link>
a2. <html:link href="http://www.baidu.com" > 链接到站点外   </html:link>
a3. <html:link page="/HtmlBasic.do">同一个应用     </html:link>
如:包含请求参数: <html:link page="/HtmlBasic.do?prop1=abc&amp;prop2=123" />
   包含单个请求变量:<% String stringBean = "Value to Pass on URL";
                   pageContext.setAttribute("stringBean", stringBean);%>
<html:link page="/HtmlBasic.do" paramId="urlParamName" paramName="stringBean" />
<jsp:useBean id="javaBean" scope="page" class="CustomerBean" />
<jsp:setProperty name="javaBean" property="name" value="weiqin" /> //要有范围
<html:link page="/Html" paramId="url" paramName="javaBean" paramProperty="name"/>
包含多个请求变量: <% java.util.HashMap myMap = new java.util.HashMap();
                      myMap.put("myString", new String("myStringValue") );
                     myMap.put("myArray", new String[] { "str1", "str2", "str3" });
                     pageContext.setAttribute("map", myMap);%>
<html:link page="/HtmlBasic.do" name="map"> url </html:link>
b.<html:img>: <html:img page="/struts-power.gif" /> //也可以包含单个或多个请求变量
<html:img src="/struts-power.gif" paramId="urlParamName" paramName="stringBean" />
<html:img page="/struts-power.gif" name="map" />


2.
基本表单标签:<html:form>,<html:text>,<html:hidden>,<html:submit>,<html:reset>
<html:cancel>Cancel</html:cancel> :Action中的取消事件:
FormBasicForm fbf = (FormBasicForm) form;
        if (isCancelled(request)) { fbf.setStatus("Cancel was pressed!");
            return (mapping.findForward("success"));      }//表示取消选中
 else { fbf.setStatus("Submit was pressed!");
            return (mapping.findForward("success"));    }

3.
下拉列表和多选列表
<html:select property="colors" size="6" multiple="true" > // multiple下拉可多选
<html:option value="htmlselect.orange">Orange</html:option> //基本的页面输入
<html:option value="red" bundle="htmlselect.Colors" key="red"/>//从资源文件中显示
<% Vector colorCollection = new Vector(); colorCollection.add(
         new org.apache.struts.util.LabelValueBean("Pink", "htmlselect.pink"));
      colorCollection.add(              // Pink为label htmlselect.pink为value
         new org.apache.struts.util.LabelValueBean("Brown", "htmlselect.brown"));
      pageContext.setAttribute("colorCollection", colorCollection);   %>
<html:options collection="colorCollection" property="value" //实际值                   
labelProperty="label" />   </html:select>// labelProperty显示值


4.
显示错误消息: errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("key") );
a.显示全局:<html:errors property="org.apache.struts.action.GLOBAL_MESSAGE"/>
b.显示特定字段: errors.add("checkbox1", new ActionMessage("error.checkbox"));
<html:errors property="checkbox1" bundle="HtmlErrors" /> //bundle资源文件


5.
显示信息<html:messages>:
a.<html:messages id=”message” message=”true”/>//如果为true则从全局中搜索
则:ActionMessages actionMessages=new ActionMessages();
actionMessages.add(ActionMessages.GLOBAL_MESSAGE,new ActionMessage(“key”));
saveMessages(request,actionMessages);
b.从一定的范围中查找:<html:messages id=”message”>
<bean:write name=”message” /> </html:messages>
则:protected void saveMessages(HttpServletRequest request,ActionMessages messages){
...request.setAttribute(GLOBAL_MESSAGE_key,messages); }
 
二:Struts Bean标签
1.访问http请求信息和JSP对象
a. <bean:cookie id="cookie" name="cookiedemo" value="firsttime"/> // value为默认值
     <% if (cookie.getValue().equals("firsttime")) {
         Cookie c = new Cookie("cookiedemo", "Hi Linda!");
         c.setComment("A test cookie");c.setMaxAge(3600);response.addCookie(c);} %>
输出: <bean:write name="cookie" property="value"/>
b. <bean:header id="lang" name="Accept-Language"/> <bean:write name="lang"/>
c.<bean:page id="this_session" property="session"/>//检索JSP范围,隐含对象
   <bean:write name="this_session" property="creationTime"/>
d. <bean:parameter id="arg1" name="testarg" value="noarg"/> // value为默认值
   <bean:write name="arg1"/>
检索多值:<bean:parameter id="arg2" multiple="yes" name="testarg" value="noarg"/>
通过链接传递参数:<html:link page="/this.jsp?testarg=123&testarg=456&testarg=789">
循环输出:<% for (int i=0; i <arg2.length; i++) {out.write(arg2[i] + "<BR>");} %>


2
.访问WEB应用资源: <message-resources parameter="res" key="special" />
a. <bean:message key="hello" arg0="Linda" /> //默认资源文件中:hello=Hello,{0}
<% request.setAttribute("stringBean","hello"); SomeBean bean=new SomeBean();
        bean.setName("hello");   request.setAttribute("someBean",bean);   %>
通过变量名或javaBean得到key值再访问资源文件:
<bean:message bundle="special" name="stringBean"/>// bundle不能省,只能访问资源文件
<bean:message bundle="special" name="someBean" property="name"/>
b. <bean:include>同<jsp:include>,但将WEB资源存放在一个变量中,有forward,page,href
<bean:include id="tp1" page="/testpage1.jsp"/> <bean:write name="tp1" filter="false"/>
<bean:include id="tp2" forward="testpage2"/> <bean:write name="tp2" filter="false"/>


3.
定义或输出javaBean,bean:write标签filter为true时会将特殊符号转换成普通字符串
a.value属性:<bean:define id="name" value="lib"/><bean:write name="name"/>
 name和property属性:<% request.setAttribute("sessionBean", session); %>
     <bean:define id="contextBean" name="sessionBean" property="servletContext"/>
// contextBean为javax.servlet.ServletContext类型,实例化
<bean:write name="contextBean" property="servletContextName"/>
  name和type属性(用于复制):<bean:define id="contextBean_copy" name="contextBean"
                    type="javax.servlet.ServletContext"/>
<bean:write name="contextBean_copy" property="majorVersion"/>


三.Struts Logic标签:
1.逻辑判断:(greatEqual,lessEqual,greatThan...)
<% Cookie c = new Cookie("username", "Linda");      c.setComment("A test cookie");
         c.setMaxAge(3600);    response.addCookie(c); %>
a.<logic:equal cookie="username" value="Linda">UserName is Linda </logic:equal>
b. <% SomeBean bean=new SomeBean();    bean.setName("Linda");
        request.setAttribute("someBean",bean);%>
<logic:notEqual name="someBean" property="name" value="Tom">not Tom </logic:notEqual>
c. <% request.setAttribute("number","100"); %>
<logic:lessThan name="number" value="100.0a" > "100" 小于"100.0a"</logic:lessThan >


2
.字符串匹配:变量中是否包含指定的字符串
<% request.setAttribute("authorName", "LindaSun");%>
a.<logic:match name="authorName" scope="request" value="Linda">
   <bean:write name="authorName"/> has the string 'Sun' in it.</logic:match>
  <logic:notMatch name="authorName" scope="request" value="Linda" /> //还有end属性
<logic:match name="authorName" scope="request" value="Linda" location="start">
<bean:write name="authorName"/> starts with the string 'Linda'.</logic:match>


3
.判断指定内容是否存在
<% ActionErrors errors = new ActionErrors();
errors.add("totallylost", new ActionMessage("application.totally.lost"));
request.setAttribute(Globals.ERROR_KEY, errors);
request.setAttribute("myerrors",errors);request.setAttribute("emptyString","");%>
a.<logic:empty name="emptyString"> emptyString is empty! </logic:empty>
b.<logic:notPresent name="noSuchBean" property="noSuchProperty">
 判断指定的安全角色,用户,cookie,header或javaBean是否存在 </logic:notPresent>
c. <logic:messagesPresent name="myerrors" >在范围内检索key</logic:messagesPresent>
<logic:messagesNotPresent message="true">
从Globals.MESSAGE_KEY中检索,不同于Globals.ERROR_KEY </logic:messagesNotPresent>
<logic:messagesNotPresent  property="noSuchError">
     从指定的ActionMessages对象中检索 </logic:messagesNotPresent>
 

4
.请求转发或重定向a.<logic:forward name="index"/>,与配置中<global-forwards>同名
b.<logic:redirect href="http://www.apache.org"/>,也有page,href和forward三种属性


5
.循环遍历//offset为开始位置,indexId为序号
a. 遍历集合<% Vector animals=new Vector(); animals.addElement("Dog");
            animals.addElement("Cat"); animals.addElement("Bird");
request.setAttribute("Animals", animals);%>
<logic:iterate id="element" indexId="index" name="Animals" offset="1" length="2">
<bean:write name="index"/>.<bean:write name="element"/><BR></logic:iterate>
b.遍历Map<% HashMap h= new HashMap();String fruits[ ] = {"apple","orange","banana"};
h.put("Fruits", fruits); request.setAttribute("catalog", h); %>
<logic:iterate id="map" name="catalog"> <bean:write name="map" property="key"/><BR>
<logic:iterate id="val" name="map" property="value"><bean:write name="val"/>
</logic:iterate>   </logic:iterate>   //如果value不是集合就不用嵌套了


四.利用Tiles模板和Tiles组件创建复合式网页
1.在web.xml中配置所需要的<tablib>url和location
2.建立tiles的xml文件放在WEB-INF下:<?xml version="1.0" encoding="ISO-8859-1" ?>
 <!DOCTYPE tiles-definitions PUBLIC
       "-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN"
       "http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd">
<tiles-definitions> <definition name="index-definition" path="/layout.jsp">
      <put name="header" value="header.jsp"/>  
      <put name="content" value="indexContent.jsp"/>  
      <put name="footer" value="footer.jsp"/> </definition>  
<definition name="product-definition" path="/layout.jsp">
      <put name="sidebar" value="sidebar.jsp"/>
      <put name="header" value="header.jsp"/>  
      <put name="content" value="productContent.jsp"/>  
      <put name="footer" value="footer.jsp"/>    </definition>
</tiles-definitions>
3.在struts配置文件中配置TilesPlugin插件(ctrl+n):
<plug-in className="org.apache.struts.tiles.TilesPlugin" >
    <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml"/>
<set-property property="definitions-parser-validate" value="true"/> </plug-in>
4.在Action已经存在ActionServlet,并在struts配置文件中配置Action来调用Tiles组件
<action path="/index"   type="org.apache.struts.actions.ForwardAction"
parameter="index-definition">    </action>
ForwardAction为Action内置对象,专门负责转发功能,在将请求转发给parameter的组件
 
5.在index.jsp中插入Tiles组件<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>
<tiles:insert definition="index-definition"/>
6.在layout.jsp文件中进行布局并设计好其他页面:
<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles"%>
<table width="100%" height="100%">
 <tr><td height="15%"><tiles:insert attribute="header"/> </td>  </tr>
 <tr><td valign="top"><tiles:insert attribute="content"/> </td> </tr>
 <tr><td valign="bottom"><tiles:insert attribute="footer"/></td></tr> </table>
备注:在需要出现的页面只有写<tiles:insert definition="*"/>就可以插入框架,根据definition中的content改变主体。


7
.Tiles组件的组合(type="definition")以示区别
<tiles-definitions>
   <definition name="sidebar-definition"   path="/sidebar-layout.jsp">
      <put name="top" value="flags.jsp"/>        </definition>
   <definition name="index-definition"   path="/layout.jsp">
      <put name="sidebar" value="sidebar-definition" type="definition"/>
      <put name="header" value="header.jsp"/>
   </definition>       </tiles-definitions>//将一个组件put成另一个组件的元素
原创粉丝点击