⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 14. struts1.x note.txt

📁 在达内培训java笔记
💻 TXT
📖 第 1 页 / 共 4 页
字号:
例如:
对于登录用户例子----把narci的都列为黑名单。
Action:
ActionMessages errors = new ActionMessages();
    if("narci".equals(loginform.getUsername())) {
        System.out.println("narci");
        ActionMessage msg = new ActionMessage("error.user.blacklist");
        errors.add("blacklist", msg);
        this.saveErrors(request, errors);
        return mapping.findForward("current");
}

(2) 
//比在form的validate方法多出的一步
saveErrors(request, errors);
return mapping.findForward("current");

并且在struts-config.xml中配置
<forward name="current" path="/login.jsp"></forward>login_en.properties加入内容
error.user.blacklist=this user in blacklist!
login_zh
error.user.blacklist=该用户已被列入黑名单!正式的: error.user.blacklist=\u8be5\u7528\u6237\u5df2\u88ab\u5217\u5165\u9ed1\u540d\u5355\uff01
        
(3) 
<html:errors/>---->用于页面中显示异常信息(通过资源文件映射) 




方法三:
通过抛出异常处理错误(推荐使用:处理业务逻辑方面出现的错误) 
(1)在action的方法中抛出异常
(2)在struts-config.xml声明该异常的处理方法(通过exception标记) 局部异常
    <action-mappings>
        <action name="loginForm" 
                path="/login" 
                type="com.action.LoginAction" 
                input="/login.jsp"
                validate="true">
            <exception key="errors.noauthorization" 
                type="com.exception.NoAuthorizationException" 
                path="/noauthorization.jsp">
            </exception>
            <forward name="fail" path="/fail.jsp"></forward>
            <forward name="current" path="/login.jsp"></forward>
        </action>
    </action-mappings>

key="errors.noauthorization"    异常提示信息仍然通过资源文件作映射
path="/noauthorization.jsp"     出现异常时的处理页面
type="exception.NoAuthorizationException" Action处理业务过程中有可能出现的异常类型

资源文件加入:
errors.noauthorization=no authorization
errors.noauthorization=当前用户没有授权!


全局异常(对所有的action共享的,所以优先级应该比较低) 
<global-exceptions>
    <exception key="errors.global" type="java.lang.Exception" path="/error.jsp"></exception>
</global-exceptions>
资源文件加入:
errors.global=System Error! Please contact our administrators!
errors.global=系统错误!请联系管理员!


在LoginAction中加入
if("admin".equals(loginform.getUsername()) 
    && "".equals(loginform.getPassword())) {
    throw new Exception();
}


4 动态表单
  可以减少ActionForm的数量,完成对html form属性的动态映射,更便于应用维护。
  实现动态表单功能:通过struts-config.xml配置
    <form-beans >
        <form-bean name="dynForm" type="org.apache.struts.action.DynaActionForm">
            <form-property name="name" type="java.lang.String"></form-property>
            <form-property name="age" type="java.lang.String"></form-property>
            <form-property name="city" type="java.lang.String"></form-property>
            <form-property name="gender" type="java.lang.String"></form-property>
        </form-bean>
    </form-beans>

    <action-mappings >
      <action name="dynForm"
        path="/enroll"
        scope="request"
        type="com.tarena.struts.action.EnrollAction" >
        <forward name="success" path="/success.jsp" />
        <forward name="fail" path="/fail.jsp" />
       </action>
    </action-mappings>
    <message-resources parameter="com.tarena.struts.ApplicationResources" />

Struts中表单使用技巧:
  1)同类型或结构相近的html form通过一个ActionForm类型映射
  2)在都能满足需要的前提下,尽量使用动态表单
  3)ActionForm的作用域范围应尽量小,对于存放在session中的ActionForm,当不再使用时应销毁
  4)ActionForm主要用于控制器与视图之间传数据,不应包含任何业务逻辑


Struts 标签
************************************************************************************************

一、Struts标签库概述

1.回顾已经学了JSTL标签库
    标签库的作用:
    1.使得(jsp)页面开发人员不再依赖Java(EL表达式的作用也是如此) 
    2.功能封装:可重用

2.Struts的五类标签库
    Bean Tags :用来创建bean、访问bean
    HTML Tags :用来创建 html 页面的动态元素,对html进行了封装;
    Logic Tags:逻辑判断、集合迭代和流程控制。
    Nested Tags:该标签库建立在前三个标签库的基础上,具有前三个标签库的所有功能,只是允许标签间的嵌套。
    Tiles Tags :该标签库包含的标签可以用来创建tiles样式的页面;布局专用。

3.重点学习前3类标签库



二、Bean标签
    可以看成 <jsp:useBean> 的增强版,
    它可以定义bean :获取某些数据(cookie,请求参数,请求头),将之定义成一个脚本变量,并同时置于某个作用域(缺省pagaContext) 中;

bean标签的公共属性:
    id - 定义一个变量
    name - 引用一个存在的bean或对象的名字
    property - 被引用的bean的属性
    scope - 放置或搜索bean的范围,若没有制定,则依次 page--request---session--application

1.<bean:define/>
    作用: 把一个bean 或其属性, 定义成一个变量

    * 通过<bean:define/>定义的变量可以通过JSP脚本、EL以及Struts本身的<bean:write/>标记访问。
    Example1:
    1) 定义一个Java bean:student,并且对其属性进行赋值
    2) 通过<bean:define/>定义stuName、stuAge、stuGender三个变量,将student这个对象的属性值赋值给这些变量
        <bean:define id="stuName" name="student" property="name"></bean:define>
        <bean:define id="stuAge" name="student" property="age"></bean:define>
        <bean:define id="stuGender" name="student" property="gender"></bean:define>
    3) 输出
        <%=stuName%>  //jsp形式
        ${stuAge }    //EL表达式
        <bean:write name="stuGender"/>  //Struts方式


    * 如果JavaBean的属性是List等类型,可以指定type属性
    Example2:
    1)在Java Bean中添加List属性,并提供get/set方法。
        private List songs;
        public List getSongs() {
            List list = new ArrayList();
            list.add("我爱北京天安门");
            list.add("我和你");
            list.add("我不做大哥好多年");
            return list;
        }
    2)<bean:define id="songs" name="student" property="songs"></bean:define>
    3)输出
        ${mySongs[0] }
    
    * 定义新变量,例如:
        <bean:define id="bookName" value="Effective Java"></bean:define>

2.<bean:write/>
    作用: 输出 bean 或bean属性;
    等价于:
    ${} 或者 <%= %>

3.<bean:message/>
    作用:读取属性静态文本内容,支持国际化(i18n) 
    Example:
    1)确认在类路径上含有
      com/ApplicationResources.properties      配置路径: <message-resources parameter="com.ApplicationResources" />
    2)在文件中加入key,value对
      page.title=\u9875\u9762\u6807\u9898
    3)提供message.jsp
      使用<bean:message key="page.title"/>

4.<bean:size/>
    作用:获得一个集合或者数组的大小
    Example:
    1)定义Java Bean : student
    2)读取student这个java bean的songs的size
        <jsp:useBean id="student" class="com.bean.Student"></jsp:useBean>
          <bean:size id="songsize" name="student" property="songs"/>
    3)输出songsize值

    Exapmple:定义一个列表,输出其size,要求使用<bean:size/>获取该值
    1)<%定义一个List,并初始化%>
    2)使用 <bean:size id="listsize1" collection="<%=list %>"/>  获取值
        注意:如果使用${},必须要把list放置到范围对象中
    3)输出

5.<bean:cookie/>
    作用:读取请求头中cookie的信息
    * <bean:cookie id="cid" name="customid">
       获得指定的名为 "customid" 的coockie,并将其赋值给脚本变量 cid
    * 若找不到id为costCookie这个cookie,所以系统创建一个cookie,并将它的值设置为"uu11"
      <bean:cookie id="cost" name="costCookie" value="uu11"/>
     输出:  <bean:write name="cost" property="value"/>

6.<bean:header/>
    作用:获取请求头的属性信息
    <bean:header id="userAgent" name="User-Agent"/>     //打印出:Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.8.0.7) Gecko/20061011....未完
    <bean:header id="host" name="host"/>     //打印出:127.0.0.1:8080
    <bean:header id="dummy" name="UNKNOWN-HEAD" value="no defined Header"/>     // no defined Header

7.<bean:include/>
    作用:对指定url(由forward、href或page确定)处的资源做一个请求,
    将响应数据作为一个String类型的bean绑定到page作用域,
    同时创建一个scripting变量。我们可以通过id值访问它们。

    Example:
    1)在根目录下定义一个文件:include.txt
    2)获取文件的内容数据,并赋于words
      <bean:include id="words" page="/include.txt"/>
    3)输出内容

8.<bean:resource/>
    作用:获取指定的资源,以String或者InputStream的方式来读取,其中input属性是决定了对应的方式。
    默认(false)是以字符串的方式来读取。
    例如:
    <bean:resource id="r1" name="/include.txt" /> //打印文件原内容: Hello World!
    <bean:resource id="r2" name="/include.txt" input="true" />     //打印出:java.io.ByteArrayInputStream@735f45    input="false"时同样这打印

9.<bean:parameter/>
    作用:取出url中queryString中指定参数名称的值
    例子:
        <bean:parameter id="target" name="action" />
        只会读取第一个名字为"action"的参数

        <bean:parameter id="ps" name="hobby" multiple="true" />
        把url中queryString中名字叫hobby的所有值赋值给变量ps,所以ps应该是一个数组

10.<bean:page/>
    作用:把pageContext中的特定的隐含对象(application, request, response, config, session) 取出来,
    绑定到某个id中,本页的其他地方就可以使用id来操纵这些隐含对象了。

    Example:
    <bean:page id="res" property="response" />
    <bean:page id="sess" property="session" />

    <bean:write name="res" property="contentType"/>
    <bean:write name="res" property="characterEncoding"/>
    <bean:write name="sess" property="id"/>
    <bean:write name="sess" property="maxInactiveInterval"/>
    

三、HTML标签库
使用taglib指令引入标签库
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>

通常是配合bean标签一起使用,是struts中最常用的标签之一。

1.<html:form/>
    作用:对html的form表单进行简单的封装,满足struts中表单请求的处理
    <html:form action="/login">
        
    </html:form>
    如果你有上述一个标签,那么你的Struts配置文件的元素中必须有一个如下内容:
    <action-mappings>
        <action input="/login.jsp" name="loginForm" path="/login"
            type="action.LoginAction" validate="true">
            <forward name="success" path="/success.jsp" />
            <forward name="error" path="/error.jsp" />
        </action>
    </action-mappings>
    这就是说一个form标签是和form bean相关联的。
    任何包含在<form>中用来接收用户输入的标签
    (<text>、<password>、<hidden>、<textarea>、<radio>、<checkbox>、<select>) 
    必须在相关的form bean中有一个指定的属性值。<form>标签中method属性的缺省值是POST 

2.<html:link>
    作用:超文本连接
    属性:page,指定一个页面的路径,必须以/开始。

    Example:
    当前页面跳转到/bean/parameter.jsp
    需要提供参数:
    <bean:define id="beanName" value="beanValue"></bean:define>
      <html:link page="/bean/parameter.jsp"
          paramId="action" paramName="beanName">
          <html:param name="hobby" value="sports"></html:param>
          跳转到bean:parameter.jsp
      </html:link>

    这等价于:
    http://localhost:8080/工程名/bean/parameter.jsp?hobby=sports&action=beanValue    <a href="/工程名/bean/parameter.jsp?hobby=sports&amp;action=beanValue">跳转到parameter.jsp</a>



3.<html:errors/>
    作用:输出错误信息
    异常处理会介绍

    Example:
    1)在资源文件中定义
        property1.error1=Property1 Error1
        property2.error1=Property2 Error1
        property2.error2=Property2 Error2
        property2.error3=Property2 Error3
        property3.error1=Property3 Error1
        property3.error2=Property3 Error2

        globalError=Global Error

        property1.message1=Property1 Message1
        property2.message1=Property2 Message1
        property2.message2=Property2 Message2
        property2.message3=Property2 Message3
        property3.message1=Property3 Message1
        property3.message2=Property3 Message2

        globalMessage=Global Message

        messages.header=<table border=1><tr><td>错误变量</td><td>错误信息</td></tr>
        messages.footer=</table>
    2)添加jsp文件并编辑
        <%@ page import="org.apache.struts.action.*"%>
        <%@page import="org.apache.struts.Globals"%>
        <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
        <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

        <%
            ActionMessages errors = new ActionMessages();
            errors.add("property1", new ActionMessage("property1.error1"));
            errors.add("property2", new ActionMessage("property2.error1"));
            errors.add("property2", new ActionMessage("property2.error2"));
            errors.add("property2", new ActionMessage("property2.error3"));
            errors.add("property3", new ActionMessage("property3.error1"));
            errors.add("property3", new ActionMessage("property3.error2"));
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("globalError"));
            request.setAttribute(Globals.ERROR_KEY, errors);

            ActionMessages messages = new ActionMessages();
            messages.add("property1", new ActionMessage("property1.message1"));
            messages.add("property2", new ActionMessage("property2.message1"));
            messages.add("property2", new ActionMessage("property2.message2"));
            messages.add("property2", new ActionMessage("property2.message3"));
            messages.add("property3", new ActionMessage("property3.message1"));
            messages.add("property3", new ActionMessage("property3.message2"));
            messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("globalMessage"));
            request.setAttribute(Globals.MESSAGE_KEY, messages);
        %>

    3)输出相应的(出错) 信息:
        <table border=1>
            <tr>
                <td>错误变量</td>
                <td>错误信息</td>
            </tr>
            <tr>
                <td>property1</td>
                <td><html:errors property="property1" /></td>
            </tr>
            <tr>
                <td>property2</td>
                <td><html:errors property="property2" /></td>
            </tr>
            <tr>
                <td>property3</td>
                <td><html:errors property="property3" /></td>
            </tr>
            <tr>
                <td>org.apache.struts.action.GLOBAL_MESSAGE</td>
                <td><html:errors
                    property="org.apache.struts.action.GLOBAL_MESSAGE" /></td>
            </tr>
            <tr>
                <td>All</td>
                <td><html:errors /></td>
            </tr>
        </table>

        <html:messages message="true" id="msg"

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -