Struts2 官方教程之Hello World Using Struts 2(四)

When you click on a hyperlink or submit an HTML form in a Struts 2 web application, the input is not sent to another server page, but to a Java class that you provide. These classes are called Actions. After the Action fires, a Result selects a resource to render the response. The resource is generally a server page, but it can also be a PDF file, an Excel spreadsheet, or a Java applet window.

这段话,讲得比较笼统,请参考《Struts2 官方教程之Create Struts 2 Web Application (三) 》最后的总结。相信比上面说得更详细。

Suppose you want to create a simple "Hello World" example that displays a welcome message. After setting up an empty basic Struts 2 web application (seeHow To Create A Struts 2 Web Application), to create a "Hello World" example, you need to do four things:

下面是运用struts2显示“Hello World”的步骤。

  1. Create a class to store the welcome message (the model) 创建model类。
  2. Create a server page to present the message (the view) 创建视图页面
  3. Create an Action class to control the interaction between the user, the model, and the view (the controller)创建一个control类
  4. Create a mapping (struts.xml) to couple the Action class and view配置struts.xml文件

    By creating these components, we are separating the work flow into three well-known concerns: the View, the Model, and the Controller. Separating concerns makes it easier to manage applications as they become more complex.

    当组件越来越复杂时,通过创建上面三个组件,其实就是非常有名的MVC,分离这些组件能使非常容易地管理应用程序。

    Let's look at an example model class, Action, server page, and mapping. If you like, fire up your Java IDE, and enter the code as we go.

This tutorial assumes you've completed the How To Create A Struts 2 Web Application tutorial and have a working Basic_Struts2_Ant (or Basic_Struts2_Mvn) project. The example code for this tutorial, Hello_World_Struts2_Ant or Hello_World_Struts2_Mvn, is available on Google Code - http://code.google.com/p/struts2-examples/downloads/list. After downloading and unzipping the file, you'll have a folder named Hello_World_Struts2_Ant (or Hello_World_Struts_Mvn). In that folder will be a README.txt file with instructions on now to build and run the example application.

这段是讲之前做过的小例子。

The Code

Let's modify either the Basic_Struts2_Ant or Basic_Struts2_Mvn project to add a model class to store our message, a view that displays our message, an Action class to act as the controller, and a configuration that ties everything together.

The Struts 2 user mailing list is an excellent place to get help. If you are having a problem getting this application to work search the Struts 2 mailing list. If you don't find an answer to your problem, post a question on the mailing list.

Step 1 - Create The Model Class MessageStore.java 

If you're using the Basic_Struts2_Ant project to start with create the MessageStore class in the src folder and if you're using the Basic_Struts2_Mvn class create the MessageStore class in src/main/java. Be sure to note the package statement below.

Note that in the code shown below the JavaDoc comments are omitted. In the download example, JavaDoc comments are included.

 Message.javapackage org.apache.struts.helloworld.model;

public class MessageStore {
	
	private String message;
	
	public MessageStore() {
		
		setMessage("Hello Struts User");
	}

	public String getMessage() {

		return message;
	}

	public void setMessage(String message) {

		this.message = message;
	}

}


 

In the model class above note the use of public set and get methods to allow access to the private message String attribute. The Struts 2 framework requires that objects you want to expose to the view (HelloWorld.jsp) follow theJavaBean-style conventions.

这话是说,请注意被public 修饰的set和get方法,它们能够访问私有属性,

Step 2 - Create The Action Class HelloWorldAction.java

We need an Action class to act as the Controller. The Action class responds to a user action (in this example that action will be clicking an HTML hyperlink and sending a specific URL to the Servlet container). One or more of the Action class's methods are executed and a String result is returned. Based on the value of the result, a specific view page (in this example that view page is HelloWorld.jsp) is rendered.

Note the package and import statements below.

我们需要一个Action类充当控制器,Action类响应user(这个例子交付点击Html里的超链接然后发送一个URL到Servlet 容器)返回的结果会根据result的值确定。

HelloWorld.java
package org.apache.struts.helloworld.action;

import org.apache.struts.helloworld.model.MessageStore;
import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	private MessageStore messageStore;
	
	public String execute() throws Exception {
		
		messageStore = new MessageStore() ;
		return SUCCESS;
	}

	public MessageStore getMessageStore() {
		return messageStore;
	}

	public void setMessageStore(MessageStore messageStore) {
		this.messageStore = messageStore;
	}

}


 

The Struts 2 framework will create an object of the HelloWorldAction class and call the execute method in response to a user's action (clicking on a hyperlink that sends a specific URL to the Servlet container).当点击Html里的超链接然后发送一个URL到Servlet 容器上面的类将会创建一个对象,然后会执行execute方法

In this example, the execute method creates an object of class MessageStore and then returns the String constant SUCCESS.

Note also the public set and get methods for the private MessageStore object. Since we want to make the MessageStore object available to the view page (HelloWorld.jsp) we need to follow theJavaBean-style of providing get and set methods.

如果我们想让信息显示在视图层,那么一定要有set.get方法

Step 3 - Create The View HelloWorld.jsp

We need a server page to present the message that is stored in the model class MessageStore. Create the below jsp in the WebContent folder (for the Ant project) and in src/main/webapp for the Mvn project).下面使用了,struts2的标签功能,后面会专门讲到

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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World!</title>
</head>
<body>
    <h2><s:property value="messageStore.message" /></h2>
</body>
</html>


 

The taglib directive tells the Servlet container that this page will be using the Struts 2 tags and that these tags will be preceded by s.

标签告诉Servlet 容器,这个页面将会使用struts2的标签功能并且前缀是S

The s:property tag displays the value returned by calling the method getMessageStore of the HelloWorldAction controller class. That method returns a MessageStore object. By adding the .message onto the messageStore part of the value attribute we are telling the Struts 2 framework to then call the getMessage method of that MessageStore object. The getMessage method of class MessageStore returns a String. It is that String that will be displayed by the s:property tag.

We'll learn more about tags in the next tutorial. See the Struts Tags for more information about tags.

s:property 指令将会显示通过getMessageStore()方法返回的值。这个方法会返回一个MessageStore对象。Struts 2会访问MessageStore对象的getMessage()方法,然后getMessage()会返回一个string,这个string就会被显示在页面上

Step 4 - Add The Struts Configuration In struts.xml

We need a mapping to tie the URL, the HelloWorldAction class (controller), and
the HelloWorld.jsp (the view) together. The mapping tells the Struts 2 framework which class will respond to the user's action (the URL), which method of that class will be executed, and what view to render based on the String result that method returns.

Edit the struts.xml file (in the Ant project that file is in the src folder and in the Mvn project that file is in the src/main/resources folder) to add the action mapping. Place the action node (action name="hello") between the opening and closing package node, just after the action mapping with the name="index". Your complete struts.xml should look like:

上面讲的是配置struts.xml注意的地方,比如配置action类什么的,相信大家都知道。

                                                        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="basicstruts2" extends="struts-default">

  <action name="index">
    <result>/index.jsp</result>
  </action>
		
  <action name="hello" class="org.apache.struts.helloworld.action.HelloWorldAction" method="execute">
    <result name="success">/HelloWorld.jsp</result>
  </action>

</package>

</struts>


 

Step 5 - Create The URL Action

In index.jsp (see WebContent folder for Ant project and src/main/webapp for Mvn project) let's add an Action URL the user can click on to tell the Struts 2 framework to run the execute method of the HelloWorldAction class and render the HelloWorld.jsp view.

在index.jsp使用一个超链接传值的方式。这里也使用到了标签。

First add the taglib directive at the top of the jsp <%@ taglib prefix="s" uri="/struts-tags" %>. Next add this p tag<p><a href="<s:url action='hello'/>">Hello World</a></p> after the h1 tag. Your new index.jsp should look like:

index.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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Basic Struts 2 Application - Welcome</title>
</head>
<body>
<h1>Welcome To Struts 2!</h1>
<p><a href="<s:url action='hello'/>">Hello World</a></p>
</body>
</html>



 

The Struts url tag creates the URL with an action of hello. The hello action was mapped to the HelloWorldAction class and its execute method. When the user clicks on the above URL it will cause the Struts 2 framework to run the execute method of the HelloWorldAction class. After that method returns the String success, the view page HelloWorld.jsp will be rendered.

Step 6 - Build the WAR File and Run The Application

If you're using the Ant version, execute ant archive to create the war file. If you're using the Mvn version execute mvn clean package to create the war file.

Copy the war file to your Servlet container. After your Servlet container successfully deploys the war file go to this URLhttp://localhost:8080/Hello_World_Struts2_Ant/index.action (for the Ant project) or go to this URLhttp://localhost:8080/Hello_World_Struts2_Mvn/index.action (for the Mvn project) where you should see the following:

Click on the Hello World link and you should get the HelloWorld.jsp page:

Getting Help

The Struts 2 user mailing list is an excellent place to get help. If you are having a problem getting this application to work search the Struts 2 mailing list. If you don't find an answer to your problem, post a question on the mailing list.

How the Code Works下面是讲整个运行过程

Your browser sends to the web server a request for the URL http://localhost:8080/Hello_World_Struts2_Ant/hello.action.

  1. The container receives from the web server a request for the resource hello.action. According to the settings loaded from theweb.xml, the container finds that all requests are being routed toorg.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter, including the*.action requests. The StrutsPrepareAndExecuteFilter is the entry point into the framework.
  2. The framework looks for an action mapping named "hello", and it finds that this mapping corresponds to the class "HelloWorldAction". The framework instantiates the Action and calls the Action'sexecute method.
  3. The execute method creates the MessageStore object and returns SUCCESS. The framework checks the action mapping to see what page to load ifSUCCESS is returned. The framework tells the container to render as the response to the request, the resourceHelloWorld.jsp.
  4. As the page HelloWorld.jsp is being processed, the <s:property value="messageStore.message" /> tag calls the gettergetMessageStore of the HelloWorld Action and then calls the getMessage of the MessageStore object returned by getMessageStore, and the tag merges into the response the value of the message attribute.
  5. A pure HTML response is sent back to the browser.

请参考上篇的总结。

What to Remember

The framework uses Actions to process HTML forms and other requests. The Action class returns a result-name such asSUCCESS, ERROR, or INPUT. Based on the mappings loaded from thestruts.xml, a given result-name may select a page (as in this example), another action, or some other web resource (image, PDF).

When a server page is rendered, most often it will include dynamic data provided by the Action. To make it easy to display dynamic data, the framework provides a set of tags that can be used along with HTML markup to create a server page.

框架使用Actions处理表单或者其他的请求,Action通过返回一个字符串结果,如SUCCESS, ERROR, or INPUT,通过struts.xml配置时选择响应相应的页面。


总结:其实完全可以把action类和model类结合,不过我不知道官方文档会选择上面的方式。

下面是需要注意的地方:

1.Java的package给我们的类打包,避免类重名,java的package作用也是一样。

2. Namespace是可以不写的,默认为空!

Namespace不写等于Namespace为空,Namespace等于空,意味着:只要你在url敲index.action

不管你在哪里敲,路劲多么深,只有最后是“index.action”就可以访问这个action。

所以namespace为空意味着:只要找到一个index.action,没有找到精确的对应的namespace,全部都交给namespace为空的这个package去处理,所以这个package囊括了其他所有package处理不了的action。

3.在写Action类时,不知道注意到没有,上面是继承了ActionSupport(这是开发中常用的方式,好处在于可以直接使用Struts2封装好的方法),其实还有两种:一是使用Action接口,二是不继承也不实现接口。

4. 在sruts.xml中如果不配置class属性,默认执行xwork框架的ActionSupport这个action,这个action就有execute这个方法,return success。

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值