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

 类型转换概述

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

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

在Struts2中,把请求参数映射到action属性的工作由Parameters拦截器负责,它是默认的defaultStack拦截器中的一员。Parameters拦截器

可以自动完成字符串和基本数据类型之间的转换。


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

 --转到哪个页面

 --显示什么错误信息

类型转换错误

如果类转型失败

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

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

 

类型转换错误消息的定制

作为默认的default拦截器的一员,Conversion拦截器负责添加与类型转换有关的出错消息(前提:Action类必须实现了ValidationAware接口)和保存各请求参数的原始值。

若字段标签使用的不是simple主题,则非法输入字段将导致一条有着以下格式的出错消息:

Invalid field value for field "fieldname"

覆盖默认的出错信息

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

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

定制出错消息的样式:

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

显示错误消息:如果是simple主题,可以通过<s:fielderror fieldName="fieldname"></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属性显示指定字段的错误。

3)若是simple主题,且使用<s:fielderrorfieldName="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部分即可

完整范例:


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">

        <default-action-ref name="index" />

        <action name="testConversion" class="com.wul.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属性显示指定字段的错误。
    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部分即可	
	 -->
	 <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"%>
<%@ 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>

	<h4>Success Page</h4>
	
</body>
</html>
ConversionAction.java

package com.wul.app;

import com.opensymphony.xwork2.ActionSupport;

public class ConversionAction extends ActionSupport{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	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=\u9519\u8BEF\u7684\u5E74\u9F84\u683C\u5F0F.

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/>

web.xm;

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Struts Blank</display-name>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

</web-app>








  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值