Struts 2 验证和输入字段重新填充 [英] Struts 2 Validation and Input fields repopulation

查看:19
本文介绍了Struts 2 验证和输入字段重新填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下 struts.xml 配置:

<结果>/jsp/input.jsp</result></动作><动作名称=结果"><result>/jsp/result.jsp</result><结果名称="输入">/jsp/input.jsp</result></动作>

还有一个只有一个字段的简单表单:

<s:textfield name="firstName" label="First Name"/><s:提交/></s:form>

当验证失败时,假设每次我提交操作(结果)时都会验证 firstName 长度大于 3.当它失败时,它将返回输入页面,在本例中为 input.jsp 但带有字段 firstName已经填充(使用我刚刚提交的错误值.Struts 2 是如何做到这一点的?我想知道,因为据我所知,当我提交时,默认方法是将输入数据发布到操作中,并且那些与验证匹配的请求参数名称将是验证.如果验证失败,它将返回输入页面(作为 POST 的响应),只有那些请求参数可用.所以我想到的唯一想法是输入字段填充了这些请求参数但例如,如果我进行以下测试.假设我将使用以下内容进行模拟:

http://domain/myApp/input.action?firstName=alfredo不会填充输入字段 firstName.

但是当结果来自验证时,它将被填充.我想知道 Struts 2 是否为了获得应该在请求参数上的那些值,推送请求参数对象(#parameters)并以这种方式填充.

谁能给我解释一下?Struts 2 如何实现重新填充?

谢谢.

解决方案

我认为您误解了一些 Struts2 概念和术语.你为什么称你的行动为输入"和结果"?这是不好的做法,并且会引起混淆——特别是因为输入"是标准 Struts2结果"的名称.

应根据它们执行的操作调用操作.

基本模式很简单.URL(http 请求、GET 或 POST)对应于用户(浏览器、客户端)请求服务器(webapp,顶部带有 struts2)执行某些操作.该操作可以给出多个结果,每个结果都会向用户返回一些信息(视图)(通常是通过 JSP 页面生成的 HTML).

一个简单的例子.假设我想添加 2 个数字并显示结果.(我从 此处.

网址:http://...../addnumbers.action

这里的动作名称是addnumbers"——这个请求将执行添加(不要被欺骗并认为它还会显示一个输入表单——它会,现在——它只是执行加法,顾名思义)

典型的实现.在 struts.xml 中指定映射:

 <result name="success">/AddNumbersResult.jsp</result><!-- 'success' 在这里可以省略--></动作>

您的 Java 操作:

 public class AddNumbersAction extends ActionSupport {私有整数 x;私有整数 x;私人内部 z;公共字符串执行(){z = x + y;返回成功;}//省略了 getter 和 setter}

还有你的 AddNumbersResult.jsp :

添加结果:+ = <s:property value="z">

您可以(您应该!)检查输入 url http://.../mywebapp/addnumbers.action?x=10&y=20 是否按预期工作.

在幕后,Struts2(默认配置,默认拦截器栈)正在创建一个AddNumbersAction的实例,并通过反射调用http参数对应的setter(尽最大努力使类型转换 - 从字符串到整数这里).然后调用action的默认方法(execute"),结果为success",使用AddNumbersResult.jsp生成html页面;在此阶段,Action 对象位于值堆栈"(某种范围)中,以便标签调用其 getter.

一旦你明白了这一点,还有两个问题:如何显示以前的 html 页面供用户输入数字(输入表单"),以及如何处理无效或不完整的参数.这些问题是相关的.

有几种(少数)方法.一种可能性:添加另一个动作映射:

 <!-- 未指定操作- 将使用 ActionSupport --><result>/AddNumbersInputForm.jsp</result></动作>

还有你的 /AddNumbersInputForm.jsp:

请输入两个要相加的整数<p><s:actionerrors/><!-- 见下文--><s:textfield name="x" label="X value"/><s:textfield name="y" label="Y value"/><s:提交/></s:form>

由于我们没有指定 Action 类,因此将使用虚拟默认值(并且将返回成功").一种什么都不做"的动作.

实际上,一个普通的 html 页面在这里就足够了,但是使用 struts2 标签我们实现了输入元素与操作字段的绑定",因此我们可以处理错误和重试.根据(仅仅)约定,当参数不充分或无效时,Struts2 操作将返回输入"(而不是成功")(想法是该操作是说您指示我执行此操作 X 但我没有成功,我需要你给我一个正确的输入,拜托 - 也许你想重试?").所以,在我们的例子中,我们得到了这个场景的完整 struts.xml 映射:

 <result>/AddNumbersInputForm.jsp</result></动作><action name="addnumbers" class="example.AddNumbersAction"><result name="input">/AddNumbersInputForm.jsp</result><result name="success">/AddNumbersResult.jsp</result></动作>

在我们的 AddNumbersInputForm.jsp 中,我们可以添加一个标签来显示验证错误(由内部的 Struts2 或我们的代码生成).

然后,如果我们按下带有无效参数的提交按钮,Struts 将在其参数拦截器中检测到这一点(如果您配置它,则加上验证)并在调用 execute() 方法之前返回输入".然后,将呈现 AddNumbersInputForm.jsp,但现在文本输入将重新填充以前的值.从哪里?从操作中,如果可以设置该字段,或者来自请求本身.这个小魔法对于任何用户友好的 html 输入表单都是必不可少的(理解它是必不可少的).

还有其他一些方法,但关键是要区分:这里的用例"只是一个(添加两个数字),但动作(概念上)有两个:第一个只是向用户呈现一个输入形式,第二个实际上做加法.这个概念应该反映在动作/网址的名称中.

If I have the following struts.xml config:

<action name="input">
   <result>/jsp/input.jsp</result>
</action>

<action name="result">
    <result>/jsp/result.jsp</result>
    <result name="input">/jsp/input.jsp</result>
</action>

And a simple form with only one field:

<s:form action="result">
    <s:textfield name="firstName" label="First Name"/>
    <s:submit/>
</s:form>

When validation fails, let's say that every time I submit the action (result) validates that firstName length is longer than 3. When it fails it will return to the input page, in this case input.jsp but with the field firstName already populated (with the incorrect value I just submitted. How does Struts 2 do this? I wonder because as I understand when I submit the default method is to POST the input data to the action and those request parameters names that match the validation will be validated. In case it fails the validation it will return to the input page (as a response of the POST) with only those request parameters available. So the only think that comes to my mind is that the input field gets populated with those request parameters but for example if I do the following test. Let's say I will simulate that with the following:

http://domain/myApp/input.action?firstName=alfredo The input field firstName won't be populate.

But when the result comes from a validation it will be populated. I wonder if Struts 2 in order to get those values that should be on the request parameters, push the request parameter object (#parameters) and this way it gets populated.

Could someone explain that to me? How does Struts 2 achieve that repopulation?

Thank you.

解决方案

I think you are misunderstanding some Struts2 concepts and terms. Why are you calling your actions "input" and "result" ? That's bad practice, and introduce confusion -specially since "input" is the name of a standard Struts2 "result".

Actions should be called according to the action they perform.

The basic pattern is simple. A URL (http request, GET or POST) corresponds to the user (browser, client) asking the server (webapp, with struts2 in top) to perform some action. The action can give several results, each result will return some info (view) (typically a HTML generated via JSP page) to the user.

A simple example. Lets assume I want to add 2 numbers and display the result. (I recycle my answer from here.

URL : http://...../addnumbers.action

Here the name of the action is "addnumbers" - this request will perform the addition (dont get tricked and think it will show also an input form - it will not, for now - it just performs the addition, as its name implies)

A typical implementation. In struts.xml you specify the mapping:

   <action name="addnumbers" class="example.AddNumbersAction">
     <result name="success">/AddNumbersResult.jsp</result> <!-- 'success' can be omitted here -->
   </action>

Your Java action:

   public class AddNumbersAction extends ActionSupport { 
       private int x;
       private int x;
       private int z;
       public String execute() {
           z = x + y; 
           return SUCCESS;
       }
       // getters and setters ommited
   }

And your AddNumbersResult.jsp :

<div>
Result of addition:
<s:property value="x"> + <s:property value="y"> = <s:property value="z">
</div>

You can (you should!) check that typing the url http://.../mywebapp/addnumbers.action?x=10&y=20 works as expected.

Under the scenes, Struts2 (with the default configuration, default stack of interceptors) is creating an instance of AddNumbersAction and calling by reflection the setters corresponding to the http parameters (doing a best effort to make type conversions - from string to integer here). Then the default method of the action ("execute") is called, the result is "success", and the AddNumbersResult.jsp is used to generate the html page ; in this stage, the Action object is in the "value Stack" (sort of scope) so that the tags invoke its getters.

Once you get clear this, there remain two issues: how to display a previous html page for the user to enter the numbers (the "input form"), and how to deal with invalid or incomplete arguments. These issues are related.

There are several (few) approaches. One possiblity: add another action mapping:

   <action name="addnumbersForm"> <!-- no action specified - will use ActionSupport -->
     <result>/AddNumbersInputForm.jsp</result>
   </action>

And your /AddNumbersInputForm.jsp:

<div>
Please type two integer numbers to be added<p>
<s:actionerrors />       <!-- see below -->
<s:form action="addnumbers">
  <s:textfield name="x" label="X value" />
  <s:textfield name="y" label="Y value" />
  <s:submit />
</s:form>
</div>

As we do not specify a Action class, a dummy default will be used (and "success" will be returned). Kind of a "do nothing" action.

Actually, a plain html page would habe been enough here, but using the struts2 tags we attain a "binding" of the input elements with the action fields, and so we can deal with errors and retries. By (mere) convention, an Struts2 action will return "input" (instead of "success") when the arguments are unsufficient or invalid (the idea is that the action is saying "you instructed me to perfom this action X but I was not succesfull, I need that you give me a proper input, please - perhaps you want to retry?"). So, in our case we get this complete struts.xml mapping for the scenario:

   <action name="addnumbersForm"> 
      <result>/AddNumbersInputForm.jsp</result>
   </action>

   <action name="addnumbers" class="example.AddNumbersAction">
     <result name="input">/AddNumbersInputForm.jsp</result>
     <result name="success">/AddNumbersResult.jsp</result>
   </action>

And in our AddNumbersInputForm.jsp we can add a tag to show validation errors (generated by the Struts2 inside, or by our code).

Then, if we press the submit button with invalid arguments Struts will detect this in its parameter intercetor (plus validation if you configure it) and return "input" before calling the execute() method. Then, the AddNumbersInputForm.jsp will be rendered, but now the text inputs will be repopulated with the previous values. From where? From the action, if the field could be set, or from the request itself. This little magic is essential for any user-friendly html input form (and it's essential to understand it).

There are some other ways, but the essential point is to distinguish: the "use case" is just one here (add two numbers), but the actions are (conceptually) two: the first just presents the user with a input form, the second actually does the addition. This concept should be reflected in the name of the actions/urls.

这篇关于Struts 2 验证和输入字段重新填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆