Hello World Using Struts 2
2015-08-29 03:13
387 查看
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
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 , to create a “Hello World” example, you need to do four things:
Create a class to store the welcome message (the model)
Create a server page to present the message (the view)
Create an Action class to control the interaction between the user, the model, and the view (the controller)
Create a mapping (
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.
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.
Step 1 - Create The Model Class
If you’re using the Basic_Struts2_Ant project to start with create the
In the model class above note the use of public set and get methods to allow access to the private
Step 2 - Create The Action Class
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
The Struts 2 framework will create an object of the
In this example, the
Note also the public getter and setter methods for the private
The
The
the
Edit the
First add the
The Struts
Copy the war file to your Servlet container. After your Servlet container successfully deploys the war file go to this URL http://localhost:8080/helloworld/index.action where you should see the following:
Click on the Hello World link and you should get the
The container receives from the web server a request for the resource
The framework looks for an action mapping named “
The
As the page
A pure HTML response is sent back to the browser.
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. After the
Actionfires, a
Resultselects 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.
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 , to create a “Hello World” example, you need to do four things:
Create a class to store the welcome message (the model)
Create a server page to present the message (the view)
Create an Action class to control the interaction between the user, the model, and the view (the controller)
Create a mapping (
struts.xml) to couple the Action class and view
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.
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.
The Code
Let’s modify either the basic_struts 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.Step 1 - Create The Model Class MessageStore.java
If you’re using the Basic_Struts2_Ant project to start with create the MessageStoreclass in the
srcfolder and if you’re using the Basic_Struts2_Mvn class create the
MessageStoreclass in
src/main/java. Be sure to note the package statement below.
MessageStore.java
package 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
messageString attribute. The Struts 2 framework requires that objects you want to expose to the view (
HelloWorld.jsp) follow the JavaBean-style conventions.
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 Stringresult is returned. Based on the value of the result, a specific view page (in this example that view page is
HelloWorld.jsp) is rendered.
HelloWorldAction.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
HelloWorldActionclass and call the
executemethod in response to a user’s action (clicking on a hyperlink that sends a specific URL to the Servlet container).
In this example, the
executemethod creates an object of class
MessageStoreand then returns the
Stringconstant
SUCCESS.
Note also the public getter and setter methods for the private
MessageStoreobject. Since we want to make the
MessageStoreobject available to the view page,
HelloWorld.jspwe need to follow the JavaBean-style of providing get and set methods.
Step 3 - Create The View HelloWorld.jsp
We need a server page to present the message that is stored in the model classMessageStore. Create the below JSP in the
WebContentfolder (if using Ant) or in
src/main/webapp(if using Maven).
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
taglibdirective tells the Servlet container that this page will be using the Struts 2 tags and that these tags will be preceded by an
s.
The
<s:property>tag displays the value returned by calling the method
getMessageStoreof the
HelloWorldActioncontroller class. That method returns a
MessageStoreobject. By adding the
.messageonto the
messageStorepart of the value attribute we are telling the Struts 2 framework to call the
getMessagemethod of that
MessageStoreobject. The
getMessagemethod of class
MessageStorereturns a
String. It is that
Stringthat will be displayed by the
<s:property>tag.
Step 4 - Add The Struts Configuration In struts.xml
We need a mapping to tie the URL, theHelloWorldActionclass (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
Stringresult that method returns.
Edit the
struts.xmlfile (in the Mvn project that file is in the
src/main/resourcesfolder) to add the action mapping. Place the
actionnode (
action name="hello") between the opening and closing
packagenode, just after the action mapping with the
name="index". Your complete
struts.xmlshould look like:
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
Inindex.jsp(see
WebContentfolder for Ant project and
src/main/webappfor Mvn project) let’s add an Action URL the user can click on to tell the Struts 2 framework to run the
executemethod of the
HelloWorldActionclass and render the
HelloWorld.jspview.
First add the
taglibdirective at the top of the jsp
<%@ taglib prefix="s" uri="/struts-tags" %>. Next add this
ptag
<p><a href="<s:url action='hello'/>">Hello World</a></p>after the
h1tag. Your new
index.jspshould 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
urltag creates the URL with an action of
hello. The
helloaction was mapped to the
HelloWorldActionclass and its
executemethod. When the user clicks on the above URL it will cause the Struts 2 framework to run the
executemethod of the
HelloWorldActionclass. After that method returns the
Stringsuccess, the view page
HelloWorld.jspwill be rendered.
Step 6 - Build the WAR File and Run The Application
Executemvn clean packageto create the war file.
Copy the war file to your Servlet container. After your Servlet container successfully deploys the war file go to this URL http://localhost:8080/helloworld/index.action where you should see the following:
Click on the Hello World link and you should get the
HelloWorld.jsppage:
How the Code Works
Your browser sends to the web server a request for the URLhttp://localhost:8080/Hello_World_Struts2_Ant/hello.action.
The container receives from the web server a request for the resource
hello.action. According to the settings loaded from the
web.xml, the container finds that all requests are being routed to
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter, including the
*.actionrequests. The
StrutsPrepareAndExecuteFilteris the entry point into the framework.
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’s
executemethod.
The
executemethod creates the
MessageStoreobject and returns
SUCCESS. The framework checks the action mapping to see what page to load if
SUCCESSis returned. The framework tells the container to render as the response to the request, the resource
HelloWorld.jsp.
As the page
HelloWorld.jspis being processed, the
<s:property value="messageStore.message" />tag calls the getter
getMessageStoreof the
HelloWorldAction and then calls the
getMessageof the
MessageStoreobject returned by
getMessageStore, and the tag merges into the response the value of the
messageattribute.
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 the
struts.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.
相关文章推荐
- mybits最基本的例子---------实现增删改查
- hibernate、java、数据库对应类型
- 【SSH快速进阶】——struts2调用action的三种方式
- 细说java.util.Timer
- Java IO编程 学习笔记 (其二:简易记事本)
- Java反射机制调用私有方法
- Introduction to Java Programming编程题9.32<检测ISBN>
- Introduction to Java Programming编程题9.31<刽子手游戏>
- Java 反射
- Java集合之WeakHashMap
- Java集合之WeakHashMap
- [leetcode-179]Largest Number(java)
- Java-WeakHashMap源码分析及示例
- Java集合之Hashtable
- Java集合之Hashtable
- Java-Hashtable源码分析及示例
- SSH---集成Struts2+Spring+Hibernate(一)
- SSH之旅(二)——Struts2 配置文件
- Java集合之TreeMap
- Java集合之TreeMap