创建一个动作-Action类:

让我们创建一个Java文件HelloWorldAction.java的Java资源> SRC下一个的包名com.yiibai.struts2与下面的内容。

package com.yiibai.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldAction extends ActionSupport{
   private String name;

   public String execute() throws Exception {
      System.out.println("Inside action....");
      return "success";
   }  

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}

在前面的例子中,我们已经看到,这是一个相同的类。我们有标准“name”属性getter和setter方法,返回字符串“success”执行方法。

创建视图

Let us create the below jsp file HelloWorld.jsp in the WebContent folder in your eclipse project.

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
   Hello World, <s:property value="name"/>
</body>
</html>

创建视图:

我们还需要在WebContent文件夹中创建的index.jsp。该文件将作为初始动作URL,用户可以直接点击告诉Struts 2框架调用HelloWorldAction类定义的方法,使HelloWorld.jsp视图。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ 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>
<title>Hello World</title>
</head>
<body>
   <h1>Hello World From Struts2</h1>
   <form action="hello">
      <label for="name">Please enter your name</label><br/>
      <input type="text" name="name"/>
      <input type="submit" value="Say Hello"/>
   </form>
</body>
</html>

hello操作定义在上面的视图文件将被映射到的HelloWorldAction类和它的执行方法使用struts.xml文件。

配置文件

现在,我们需要注册我们的拦截器,然后调用它,因为我们已经在前面的例子中默认的拦截器。要注册一个新定义的拦截器<interceptors>...</interceptors>标签直接放在下的<package>的标记插件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>
   <constant name="struts.devMode" value="true" />
   <package name="helloworld" extends="struts-default">

      <interceptors>
         <interceptor name="myinterceptor"
            class="com.yiibai.struts2.MyInterceptor" />
      </interceptors>

      <action name="hello" 
         class="com.yiibai.struts2.HelloWorldAction" 
         method="execute">
         <interceptor-ref name="params"/>
         <interceptor-ref name="myinterceptor" />
         <result name="success">/HelloWorld.jsp</result>
      </action>

   </package>
</struts>

应该注意的是,你可以注册多个拦截器<package>标签内,同一时间可以调用多个拦截器内的<action>标签。可以调用相同的拦截器与不同的动作。
需要创建WebContent/WEB-INF文件夹下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" 
   xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id="WebApp_ID" version="3.0">
   
   <display-name>Struts 2</display-name>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
   </filter>

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

右键点击项目名称,并单击“导出”> WAR文件创建一个WAR文件。然后,这WAR部署在Tomcat的webapps目录下。最后,启动Tomcat服务器,并尝试访问URL http://localhost:8080/HelloWorldStruts2/index.jsp。这会给你以下画面:

现在,在给定的文本框中输入任何单词,然后单击“Say Hello按钮执行已定义的动作。现在,如果你将检查生成的日志,你会发现下面的文字在底部:

 
Pre-Processing
Inside action....
Post-Processing

堆叠多个拦截器:

正如你想像,配置多个拦截器的每个动作很快就会变得非常难以控制。出于这个原因,拦截器的拦截器栈管理。下面是一个例子,直接从在struts-default.xml文件:

 
<interceptor-stack name="basicStack">
   <interceptor-ref name="exception"/>
   <interceptor-ref name="servlet-config"/>
   <interceptor-ref name="prepare"/>
   <interceptor-ref name="checkbox"/>
   <interceptor-ref name="params"/>
   <interceptor-ref name="conversionError"/>
</interceptor-stack>

上述权被称为basicStack,并且可以用于在您的配置中,如下所示。此配置节点被放置下<package.../>节点。每个<interceptor-ref.../>标签引用了一个拦截器或拦截器栈已配置在当前的拦截器栈。因此,这是非常重要的,以确保名称是唯一在所有拦截器和拦截器栈配置时,配置初始拦截器和拦截器栈。
我们已经看到了如何应用拦截器的作用,应用拦截器栈是没有什么不同。事实上,我们都使用完全相同的标签:

 
<action name="hello" class="com.yiibai.struts2.MyAction">
   <interceptor-ref name="basicStack"/>
   <result>view.jsp</result>
</action

所有的6个拦截器,上述登记注册完成股权“basicStack”hello操作。他们在配置应该指出的是拦截器执行的顺序。例如,在上述情况下,异常将被执行第一,servlet配置第二等。

Struts 2 Results and Result Types

正如前面提到的,<results>标签Struts2的MVC框架的视图中所扮演的角色。动作是负责执行业务逻辑。执行业务逻辑后,下一步是使用<results>标签显示视图。
经常有一些导航规则附加的结果。例如,如果在动作方法是对用户进行验证,有三种可能的结果。 (a)成功登录失败的登录. (b)用户名或密码不正确.(c)帐户锁定。
的操作方法在这种情况下,将配置有三种可能的结果字符串和三种不同的视图呈现结果。在前面的例子我们已经看到。
但是,Struts2不配合使用JSP作为视图技术。毕竟了MVC模式的整个目的是保持层分离和高度可配置。例如,对于一个Web2.0客户端,您可能要返回XML或JSON作为输出。在这种情况下,你可以创建一个新的结果类型为XML或JSON,实现这一目标。
Struts的一些预定义的结果类型,无论我们已经看到了,这是默认的结果类型,这是用来调度派遣到JSP页面。 Struts允许使用的其他标记语言的技术,目前的结果和流行的选择,包括Velocity, Freemaker, XSLT 和Tiles。

分发调度结果类型:

调度的结果类型是默认的类型,是用来指定,如果没有其他的结果类型。它被用来转发到一个servlet,JSP,HTML页面等等,在服务器上它使用RequestDispatcher.forward()方法。
在我们前面的例子中,我们看到了“shorthand”版本,在这里我们提供了一个JSP的路径作为身体的结果标记。

<result name="success">
   /HelloWorld.jsp
</result>

We can also specify the JSP file using a <param name="location"> tag within the <result...> element as follows:

<result name="success" type="dispatcher">
   <param name="location">
      /HelloWorld.jsp
   </param >
</result>

我们还可以提供一个分析参数,默认值是true。解析参数的位置参数确定是否将被解析为OGNL表达式。

FreeMaker结果类型:

在这个例子中,我们将看到我们如何使用FreeMaker作为视图技术。 freemaker是一种流行的模板引擎,用于生成输出,使用预定义的模板。让我们创建一个Freemaker模板文件hello.fm以下内容:

Hello World ${name}

在此以上的文件是一个模板,其中名称是使用已定义的动作外,将通过放慢参数。在你的CLASSPATH中将保存该文件。接下来让我们修改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>
   <constant name="struts.devMode" value="true" />
   <package name="helloworld" extends="struts-default">

      <action name="hello" 
         class="com.yiibai.struts2.HelloWorldAction"
         method="execute">
         <result name="success" type="freemarker">
            <param name="location">/hello.fm</param>
         </result>
      </action>
      
   </package>

</struts>

让我们保持我们的HelloWorldAction.java,HelloWorldAction.jsp和index.jsp文件,为我们创造了他们的例子章。现在,右键单击该项目上的名称和clickExport> WAR文件创建一个WAR文件。然后,这WAR部署在Tomcat的webapps目录下。最后,启动Tomcat服务器,并尝试访问URL http://localhost:8080/HelloWorldStruts2/index.jsp。这会给你以下画面:

值“Struts2”,并提交页面。您应该看到下一页

正如你可以看到,这是完全一样的不同之处在于,我们是不依赖于使用JSP作为视图技术的JSP视图。在这个例子中,我们已经使用Freemaker。

重定向结果类型:

重定向结果的类型调用标准 response.sendRedirect() 方法,使浏览器来创建一个新的请求给定的位置。
我们可以提供的位置无论是在体内的<result...>元素或作为一个<param name="location">元素。重定向也支持解析的参数。下面是一个例子使用XML配置:

<action name="hello" 
   class="com.yiibai.struts2.HelloWorldAction"
   method="execute">
   <result name="success" type="redirect">
       <param name="location">
         /NewWorld.jsp
      </param >
   </result>
</action>

因此,只要修改struts.xml文件中定义重定向上述类型,并创建一个新的的文件NewWorld.jpg在那里你会被重定向hello操作时,将返回成功。

Struts2值栈/ OGNL

值栈:

值栈是一组的几个对象保持中的下列对象提供的顺序:

SN Objects & 描述
1 Temporary Objects
There are various temporary objects which are created during execution of a page. For example the current iteration value for a collection being looped over in a JSP tag.
2 The Model Object
If you are using model objects in your struts application, the current model object is placed before the action on the value stack
3 The Action Object
This will be the current action object which is being executed.
4 Named Objects
These objects include #application, #session, #request, #attr and #parameters and refer to the corresponding servlet scopes

值栈可以通过标签提供JSP,Velocity或者Freemarker的。在单独的章节中,我们将研究有不同的标签,被用来获取和设置Struts 2.0的值栈。您可以在你的行动值栈对象如下:

ActionContext.getContext().getValueStack()

一旦你拥有了值对象,您可以使用以下方法来操作该对象:

SN ValueStack Methods & 描述
1 Object findValue(String expr)
Find a value by evaluating the given expression against the stack in the default search order.
2 CompoundRoot getRoot()
Get the CompoundRoot which holds the objects pushed onto the stack.
3 Object peek()
Get the object on the top of the stack without changing the stack.
4 Object pop()
Get the object on the top of the stack and remove it from the stack.
5 void push(Object o)
Put this object onto the top of the stack.
6 void set(String key, Object o)
Sets an object on the stack with the given key so it is retrievable by findValue(key,...)
7 void setDefaultType(Class defaultType)
Sets the default type to convert to if no type is provided when getting a value.
8 void setValue(String expr, Object value)
Attempts to set a property on a bean in the stack with the given expression using the default search order.
9 int size()
Get the number of objects in the stack.

猜你喜欢

转载自www.cnblogs.com/borter/p/9502148.html