26.Struts2_类型转换错误消息的显示和定制

来源:互联网 发布:php curl发送get请求 编辑:程序博客网 时间:2024/05/21 20:21

内容提要

一.类型转换概述
二.类型转换出错时如何进行处理
 1.转到哪个页面
 2.显示什么错误消息
三.自定义类型转换器
四.类型转换与复杂对象配合使用


一.类型转换概述

从一个HTML表单到一个Action对象,类型转换是从字符串到非字符串

--HTTP没有“类型”的概念,每一项表单输入只可能是一个字符串或一个字符串数组。在服务器端,必须把String转换为特定的数据类型。

在Struts2中,把请求参数映射到action属性的工作由Parameters拦截器负责,它是默认的defaultStack拦截器中的一员。Parameters拦截器可以自动完成字符串和基本数据类型之间的转换。


二.类型转换出错时如何进行处理

a.转到哪个页面

b.显示什么错误消息


1.类型转换错误

  • 如果类转型失败

--若Action类没有实现ValidationAware接口:Struts在遇到类型转换错误时仍会继续调用其Action方法,就好像什么都没有发生一样。

--若Action类实现ValiddationAware接口:Struts在遇到类型转换错误时将不会继续调用其Action方法,Struts将检查相关action元素的声明是否包含着一个name=input的result。如果有,Struts将把控制权转交给那个result元素,若没有input结果,Struts将抛出一个异常。


2.类型转换错误消息的定制

  • 作为默认的default拦截器的一员,Conversion拦截器负责添加与类型转换有关的出错消息(前提:Action类必须实现了ValidationAware接口)和保存各请求参数的原始值。
  • 若字段标签使用的不是simple主题,则非法输入字段将导致一条有着以下格式的出错消息:

Invalid field value for field "fieldname"

  • 覆盖默认的出错信息

 --在对应的Action类所在的包中新建ActionClassName.properties文件,ActionClassName即为包含着输入字段的Action类的类名

--在属性文件中添加如下键值对:invalid.fieldvalue.fieldName=Custom error message

  • 定制出错消息的样式:
--每一条出错消息都被打包在一个HTMLspan元素里,可以通过覆盖其行标为errorMessage的那个css样式来改变出错消息的格式。

  • 显示错误消息:如果是simple主题,可以通过<s:fielderror fieldName="fieldname"></s:fielderror>标签显示错误信息

例:<s:fielderror fieldName="age"></s:fielderror>


    问题1:如何覆盖默认的错误信息?  

    1)在对应的Action类所在的包中新建  
     ActionClassName.properties文件,ActionClassName即为包含着输入字段的Action类的类名  
    2)在属性文件中添加如下键值对:invalid.fieldvalue.fieldName=xxx; 
 
    问题2:如果是simple主题,还会自动显示错误消息吗?如果不,该如何让其显示? 

    1)不显示。通过debug标签,可知若转换出错,则在值栈的Action(实现了ValidationAware接口)对象中有一个fieldErrors属性,该属性的类型为Map<String,List<String>>键:字段(属性名),值:错误 消息组成的List。所以可以使用EL或OGNL的方式来显示错误消息:${fieldErrors.age[0]}  
    2)还可以使用s:fielderror标签来显示,可以通过fieldName属性显示指定字段的错误: <s:fielderror fieldName="age"></s:fielderror>
  
    问题3:若是simple主题,且使用<s:fielderror fieldName="age"></s:fielderror>来显示错误消息,则该消息在一个ul,li,span中,如何去除ul,li,span呢?

    在template.simple下面的fielderror.ftl定义了simple主题下,s:fielderror标签显示错误消息的样式。配置文件即可。在src下新建template.simple包,新建fielderror.ftl文件,把原生的fielderror.ftl中的内容复制到新建的fielderror.ftl中,然后剔除ul,li,span部分即可。   
    (原生的fielderror.ftl在项目名->java Resources->Libraries->Web App Libraries->struts-core-2.2.1.jar(核心包)->template.simple->fielderror.ftl)


完整范例:

1.结构目录:


2.代码

web.xml

<?xml version="1.0" encoding="UTF-8"?>  <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">    <display-name>Struts2-2</display-name>    <welcome-file-list>      <welcome-file>index.html</welcome-file>      <welcome-file>index.htm</welcome-file>      <welcome-file>index.jsp</welcome-file>      <welcome-file>default.html</welcome-file>      <welcome-file>default.htm</welcome-file>      <welcome-file>default.jsp</welcome-file>    </welcome-file-list>        <!-- 配置过滤器类 -->    <filter>          <filter-name>struts2</filter-name>         <!--  从struts-2.1.3以后,org.apache.struts2.dispatcher.FileDispatcher值被标注为过时,现在是如下写法 -->          <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>      </filter>      <!-- 过滤器用来初始化struts2并处理所有web请求 -->      <filter-mapping>          <filter-name>struts2</filter-name>          <url-pattern>/*</url-pattern>      </filter-mapping>        </web-app> 

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>  <!DOCTYPE struts PUBLIC      "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"      "http://struts.apache.org/dtds/struts-2.3.dtd">    <struts>        <package name="default" namespace="/" extends="struts-default">            <action name="testConversion" class="struts.app.ConversionAction">              <result>/success.jsp</result>              <result name="input">/index.jsp</result>                   </action>              </package>  </struts>


index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>  <%@ taglib prefix="s" uri="/struts-tags" %>  <!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=utf-8">  <title>Insert title here</title>  </head>  <body>  <!--      问题1:如何覆盖默认的错误信息?      1)在对应的Action类所在的包中新建       ActionClassName.properties文件,ActionClassName即为包含着输入字段的Action类的类名      2)在属性文件中添加如下键值对:invalid.fieldvalue.fieldName=xxx;      问题2:如果是simple主题,还会自动显示错误消息吗?如果不,该如何让其显示?     1)不显示。通过debug标签,可知若转换出错,则在值栈的Action(实现了ValidationAware接口)对象中有一个fieldErrors属性,该属性的类型为Map<String,List<String>>键:字段(属性名),值:错误 消息组成的List。所以可以使用EL或OGNL的方式来显示错误消息:${fieldErrors.age[0]}      2)还可以使用s:fielderror标签来显示,可以通过fieldName属性显示指定字段的错误: <s:fielderror fieldName="age"></s:fielderror>      问题3:若是simple主题,且使用<s:fielderror fieldName="age"></s:fielderror>来显示错误消息,则该消息在一个ul,li,span中,如何去除ul,li,span呢?    在template.simple下面的fielderror.ftl定义了simple主题下,s:fielderror标签显示错误消息的样式。配置文件即可。在src下新建template.simple包,新建fielderror.ftl文件,把原生的fielderror.ftl中的内容复制到新建的fielderror.ftl中,然后剔除ul,li,span部分即可。       (原生的fielderror.ftl在项目名->java Resources->Libraries->Web App Libraries->struts-core-2.2.1.jar(核心包)->template.simple->fielderror.ftl)-->        <s:debug></s:debug>    <s:form action="testConversion" theme="simple">          <s:textfield name="age" label="Age"></s:textfield>        ${fieldErrors.age[0]}^        <s:fielderror fieldName="age"></s:fielderror>                 <s:submit></s:submit>      </s:form>      </body>  </html>  


success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!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=UTF-8"><title>Insert title here</title></head><body><h4>success page</h4></body></html>


ConversionAction.java

package struts.app;import com.opensymphony.xwork2.ActionSupport;public class ConversionAction extends ActionSupport{      private int age;        public int getAge() {          return age;      }        public void setAge(int age) {          this.age = age;      }            public String execute(){          System.out.println("age :"+age);          return "success";      }  }  

ConversionAction.properties

invalid.fieldvalue.age=age error message.


fielderror.ftl(将其中的ul,li,span去掉)

<#--  /*   * $Id$   *   * Licensed to the Apache Software Foundation (ASF) under one   * or more contributor license agreements.  See the NOTICE file   * distributed with this work for additional information   * regarding copyright ownership.  The ASF licenses this file   * to you under the Apache License, Version 2.0 (the   * "License"); you may not use this file except in compliance   * with the License.  You may obtain a copy of the License at   *   *  http://www.apache.org/licenses/LICENSE-2.0   *   * Unless required by applicable law or agreed to in writing,   * software distributed under the License is distributed on an   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY   * KIND, either express or implied.  See the License for the   * specific language governing permissions and limitations   * under the License.   */  -->  <#if fieldErrors??><#t/>      <#assign eKeys = fieldErrors.keySet()><#t/>      <#assign eKeysSize = eKeys.size()><#t/>      <#assign doneStartUlTag=false><#t/>      <#assign doneEndUlTag=false><#t/>      <#assign haveMatchedErrorField=false><#t/>      <#if (fieldErrorFieldNames?size > 0) ><#t/>          <#list fieldErrorFieldNames as fieldErrorFieldName><#t/>              <#list eKeys as eKey><#t/>                  <#if (eKey = fieldErrorFieldName)><#t/>                      <#assign haveMatchedErrorField=true><#t/>                      <#assign eValue = fieldErrors[fieldErrorFieldName]><#t/>                      <#if (haveMatchedErrorField && (!doneStartUlTag))><#t/>                          <#assign doneStartUlTag=true><#t/>                      </#if><#t/>                      <#list eValue as eEachValue><#t/>                          <#if parameters.escape>${eEachValue!?html}<#else>${eEachValue!}</#if>                      </#list><#t/>                  </#if><#t/>              </#list><#t/>          </#list><#t/>          <#if (haveMatchedErrorField && (!doneEndUlTag))><#t/>              <#assign doneEndUlTag=true><#t/>          </#if><#t/>          <#else><#t/>          <#if (eKeysSize > 0)><#t/>              <#list eKeys as eKey><#t/>                  <#assign eValue = fieldErrors[eKey]><#t/>                  <#list eValue as eEachValue><#t/>                      <#if parameters.escape>${eEachValue!?html}<#else>${eEachValue!}</#if>                  </#list><#t/>              </#list><#t/>          </#if><#t/>      </#if><#t/>  </#if><#t/>  





原创粉丝点击