Showing posts with label Struts. Show all posts
Showing posts with label Struts. Show all posts

Wednesday, January 2, 2013

Struts2 校验(XML配置校验)


Struts2 校验(XML配置校验)


基本说明:

Struts校验可以分为两种类型:Annotation型,XML配置型

Annotation型主要使用Annotation来配置Action中的属性,这里我们做过多的介绍,需要看的请参看我的其他相关文章。

XML配置型主要是指,使用XML来描述配置信息,之后提供给Struts框架做校验。

使用Struts2,XML配置型的校验可以使用三种方式:普通的服务器端校验方式,客户纯JavaScript方式端校验,和Ajax方式的校验。

普通的服务器端校验方式:
     客户端提交信息到服务器,在服务器上使用XML配置信息,校验客户端提交的信息,错误的情况下,返回input页面,显示校验错误信息。

客户端纯JavaScript校验方式:
     在输入画面上,根据XML文件中的配置内容生成对应的JavaScript校验脚本,在提交数据的时候首先使用这些生成的JavaScript校验输入信息,错误情况下在画面上显示错误信息,不需要向服务器提交内容,只有输入数据校验正确的情况下才向服务器提交请求。这种方式的校验不支持所有Struts2内置的校验,只支持一部分校验:
    required validator
    requiredstring validator
    stringlength validator
    regex validator
    email validator
    url validator
    int validator
    double validator 
Ajax方式校验
     在提交请求的时候,首先使用AJAX的方式将数据提交到服务器,在校验出错的情况下在页面显示错误信息,但是不刷新页面,在校验成功的情况下,才向服务器提交请求。

三种方式比较
普通的服务端校验方式客户端纯JavaScriptAjax方式
位置服务器客户端 服务器
是否刷新页面是否否
校验代码JavaJavaScriptJava
具体实现1 定义Action类
    Action.java
2 定义配置文件
    Action-validation.xml
3 在struts.xml中定义action,注意由于使用了validation,所以必须定义input名字的result。
    <action name="" class="">
        <result></result>
        <result name="input"></result>
    </action>
4 定义JSP页面的Form,例如:
<s:form action="quizAction" >
    <s:textfield label="Name" name="name"/>
    <s:textfield label="Age" name="age"/>
    <s:textfield label="Favorite color" name="answer"/>
    <s:submit/>
</s:form>
与“普通的服务端校验方式”基本相同,但是需要在form定义的时候添加validate="true",例如:
<s:form action="quizAction"validate="true">
    <s:textfield label="Name" name="name"/>
    <s:textfield label="Age" name="age"/>
    <s:textfield label="Favorite color" name="answer"/>
    <s:submit/>
</s:form>
与“普通的服务端校验方式”基本相同,但是需要做如下修改:
1 安装dojo plugin
2 JSP中使用dojo plugin
<%@ taglib prefix="sx"uri="/struts-dojo-tags" %>
3 在head内部追加head标签(引入dojo的js库)
 <sx:head />
4 修改form定义
<s:form method="post"theme="ajax"  action="quizAjax"id="form">
    <s:textfield label="Name"name="name" />
    <s:textfield label="Age"name="age" />
    <s:textfield label="Favorite color"name="answer"/>
    <sx:submit validate="true" /></s:form>

说明:struts-dojo-plugin在2.1.0的时候可能会Release。现在使用需要从Subversion中去除2.1.0SNAPSHOT代码:

代码示例

// QuizAction 类

package example;
import com.opensymphony.xwork2.ActionSupport;
/**
 * Created by IntelliJ IDEA.
 * User: ma.zhao@dl.cn
 * Date: 2007-9-8
 * Time: 13:58:16
 * To change this template use File | Settings | File Templates.
 */
public class QuizAction extends ActionSupport {
    private static final long serialVersionUID = -7505437345373234225L;
    private String name;
    private int age;
    private String answer;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getAnswer() {
        return answer;
    }
    public void setAnswer(String answer) {
        this.answer = answer;
    }
    public String execute() {
        return SUCCESS;
    }
}
// QuizValidation.xml 校验配置文件

<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
        "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
    <field name="name">
        <field-validator type="requiredstring">
            <message>You must enter a name</message>
        </field-validator>
    </field>
    <field name="age">
        <field-validator type="int">
            <param name="min">13</param>
            <param name="max">19</param>
            <message>Only people ages 13 to 19 may take this quiz</message>
        </field-validator>
    </field>
</validators>
// struts.xml配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="example" namespace="/example" extends="struts-default">
        <action name="quizAction" class="example.QuizAction">
            <result name="input">/example/quiz-ajax.jsp</result>
            <result>/example/quiz-success.jsp</result>
        </action>
    </package>
</struts>

// JSP 文件
<%--
  Created by IntelliJ IDEA.
  User: ma.zhao@dl.cn
  Date: 2007-9-8
  Time: 14:02:17
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>Quiz Action Validation</title></head>
<body>
<s:form action="quizAction" namespace="/example" validate="true">
    <s:textfield label="Name" name="name"/>
    <s:textfield label="Age" name="age"/>
    <s:textfield label="Favorite color" name="answer"/>
    <s:submit/>
</s:form>
</body>
</html>
特别说明(Ajax Validation):
为什么使用AJAX 校验?
纯的JavaScript校验不刷新页面,但是也不能使用所有的Struts2校验方法;服务端校验可以使用所有Struts2的校验方法,但是需要刷新页面。
Struts2 Ajax校验,既不需要刷新页面,又可以使用Struts2内置的所有的校验方法,所以我们比较倾向于使用Ajax校验。

现在(2007/09/08)Struts2的最新版本为2.0.9,还不支持dojo-plugin,所以还没有办法使用Ajax校验。所以要想使用Ajax Validation必须使用Struts2.1.0 SNAPSHOT版本。

下载:
使用Subversion可以从以下位置下载最新的Struts2的源代码:

构造:
在下载的apps目录下blank子目录下可以使用如下命令
mvn compile jar:jar
可以在target目录中看到:struts2-blank.war

在plugins目录dojo子目录下使用如下命令
mvn compile jar:jar
可以在target目录中看到dojo-plugin:struts2-dojo-plugin-2.1.0-SNAPSHOT.jar

按照上述的说明构造AJAX校验

一些变化:
Struts 配置文件:

<action name="quizAjax" class="example.QuizAction">
    <interceptor-ref name="jsonValidationWorkflowStack"/>    <result name="input">/example/quiz-ajax.jsp</result>
    <result>/example/quiz-success.jsp</result>
</action>

这个interceptor是在Struts 2.1.0 才有的。

JSP文件:
<%--
  Created by IntelliJ IDEA.
  User: ma.zhao@dl.cn
  Date: 2007-9-8
  Time: 17:29:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
    <title>Validation - AJAX</title>
    <sx:head />
</head>
<s:url id="url" namespace="/example" action="quizAjax"/>
<body>
<s:form method="post" theme="xhtml" namespace="/example" action="quizAjax" id="form">
    <s:textfield label="Name" name="name" />
    <s:textfield label="Age" name="age" />
    <s:textfield label="Favorite color" name="answer"/>
    <sx:submit validate="true" />
</s:form>
</body>
</html> 

需要注意
<s:url id="url" namespace="/example" action="quizAjax"/>

提供了Dojo校验的URL,一定要注意。

Monday, December 31, 2012

Hello Struts

Go through MVC first:
Figure 1
Project: MyEclipse -> MyHelloStruts


1. Session  

Class ActionContext

static ActionContextgetContext()
          Returns the ActionContext specific to the current thread.
 MapgetSession()
          Gets the Map of HttpSession values when in a servlet environment or a generic session map otherwise.

getContext

public static ActionContext getContext()
Returns the ActionContext specific to the current thread.
Returns:
the ActionContext for the current thread, is never null.

getSession

public Map getSession()
Gets the Map of HttpSession values when in a servlet environment or a generic session map otherwise.
Returns:
the Map of HttpSession values when in a servlet environment or a generic session map otherwise.

Sunday, December 30, 2012

Struts2学习笔记1

struts hello world - useful!
http://www.dzone.com/tutorials/java/struts-2/struts-2-example/struts-2-hello-world-example-1.html


Q:How to generate Bean in Eclipse automatically?
A: Source -> generate getters and setters
See:
Eclipse快速上手Hibernate--1. 入门实例
http://blog.csdn.net/javamxj/article/details/335076


Q:

为什么加filter的struts2找不到jsp页面?不加就没问题

http://www.crazyit.org/thread-7026-1-1.html
A:
Sometime different versions of struts require different library.




Struts 2 Hello World Tutorial



In this tutorial we will see how to create a simpe Struts 2 Hello World Application. The following files are needed to create a Hello World Application.
  • web.xml
  • struts.xml
  • HelloWorld.java
  • index.jsp
  • success.jsp
The following picture shows the directory structure of the Hello World application.

web.xml

web.xml is used to configure the servlet container properties of the hello world appliation. The filter and the filter-mapping elements are used to setup the Struts 2 FilterDispatcher. The filter is mapped to the URL pattern "/*". This means all the incoming request that targets to the Struts 2 action will be handled by FilterDispatcher class.
01.<filter>
02.<filter-name>struts2</filter-name>
03.<filter-class>org.apache.struts2.dispatcher.FilterDispatcher </filter-class>
04.</filter>
05.<filter-mapping>
06.<filter-name>struts2</filter-name>
07.<url-pattern>/*</url-pattern>
08.</filter-mapping>
09.<welcome-file-list>
10.<welcome-file>index.jsp</welcome-file>
11.</welcome-file-list>
The gateway for our hello world application is index.jsp file. The index.jsp file should be mentioned in web.xml as shown above.

struts.xml

The entry point to the XML declarative architecture is struts.xml file. The struts.xml file contains the following action mapping.
1.<struts>
2.<package name="default" extends="struts-default">
3.<action name="HelloWorld" class="vaannila.HelloWorld">
4.<result name="SUCCESS">/success.jsp</result>
5.</action>
6.</package>
7.</struts>

index.jsp

The Struts 2 UI tags are simple and powerful. To use the struts tags in the jsp page the following taglib directive should be included.
PS: You have to use Struts 2 tag otherwise the program won't work. OR you can simply add ".action" like action = "HelloWworld.action" in the form instead of using Struts taglib.

这两种方法都是为了标明这个request是需要拦截并dispatch到相应的.java中去的。filter(拦截器)就是为了-> recognize and then dispatch requests.
01.<%@taglib uri="/struts-tags" prefix="s" %>
02. 
03.<html>
04.<head>
05.<title>Hello World</title>
06.</head>
07.<body>
08.<s:form action="HelloWorld" >
09.<s:textfield name="userName" label="User Name" />
10.<s:submit />
11.</s:form>
12.</body>
13.</html>

form action = "HelloWorld"

HelloWorld must have a execute()

HelloWorld.java

As you see the HelloWorld class is very simple. It contains two properties one for the user name and the other for displaying the message.
01.public class HelloWorld {
02. 
03.private String message;
04. 
05.private String userName;
06. 
07.public HelloWorld() {
08.}
09. 
10.public String execute() {
11.setMessage("Hello " + getUserName());
12.return "SUCCESS";
13.}
14. 
15.public String getMessage() {
16.return message;
17.}
18. 
19.public void setMessage(String message) {
20.this.message = message;
21.}
22. 
23.public String getUserName() {
24.return userName;
25.}
26. 
27.public void setUserName(String userName) {
28.this.userName = userName;
29.}
30. 
31.}
In the execute() method of the HelloWorld action we compose the message to be displayed. Note we need not have a seperate form bean like struts 1 to access the form data. We can have a simple java class as action. The action need not extend any class or implement any interface. The only obligation is that you need to have an execute() method which returns a String and has a public scope.

success.jsp

In the success page we display the "Hello User" message using the property tag.
01.<%@taglib uri="/struts-tags" prefix="s" %>
02.<html>
03.<head>
04.<title>Hello World</title>
05.</head>
06.<body>
07.<h1><s:property value="message" /></h1>
08.</body>
09.</html>
Extract the downloaded files into the webapps folder of Tomcat. Start the Tomcat server. Type the following url in the browser "http://localhost:8080/Example1/index.jsp". The index page will be displayed.
Enter the user name and submit the form. Hello user name message will be displayed.
You can download the Struts 2 Hello World example by clicking the download link.
Source :Download
Source + Lib :Download