struts2–第一个应用 Hello World
当点击一个struts2应用时,请求没有直接发送到view层,而是一个java类,也就是action层。然后action 处理数据层,将内容重定向到view层。所以想要创建一个hello world应用,需要做:
- 创建一个类存储数据(model)
- 创建一个前端页面展示数据(view)
- 创建一个类处理用户,model,view之间的关系(controller/ action)
- 添加配置文件struts.xml
1. 创建model类 MessageStore.java
public class MessageStore {
private String message;
public MessageStore(){
message = "hello world user";
}
public String getMessage() {
return message;
}
}
2. 创建一个action类 HelloWorldAction.java
用户点击访问路径,struts2 框架创建HelloWorldAction类调用execute方法响应用户请求。
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldAction extends ActionSupport{
private MessageStore messageStore;
public String execute(){
messageStore = new MessageStore();
return SUCCESS;
}
public MessageStore getMessageStore(){
return messageStore;
}
}
3. 创建view HelloWorld.jsp
在 src/main/webapp 目录下创建jsp文件, 其中使用到了struts的标签。
<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World!</title>
</head>
<body>
<h2><s:property value="messageStore.message" /></h2>
</body>
</html>
4.添加配置文件 struts.xml
我们需要构建一个url, action类,和view层之间的映射关系。在struts.xml文件中,配置如下
<action name="hello" class="HelloWorldAction" method="execute">
<result name = "success">/HelloWorld.jsp</result>
</action>
该配置文件表征 HelloWorldAction类响应名字为hello.action的URI; 其中执行方法为 execute;重定向的视图层文件为 HelloWorld.jsp。
5.启动应用
6. 工作流
当用户在浏览器中点击 http://localhost:8080/struts-demo1/hello.action
- 容器收到hello.action的请求,加载web.xml文件,发现全部请求通过 org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter过滤,.action后缀可以通过。
- 框架遍历action名字为“hello”的action, 发现处理的类为 “HelloWorldAction”, 实例化该类,并之执行execute方法。
- “execute”方法,执行其中的业务步骤,并返回一个框架状态“SUCCESS”;框架检查struts.xml文件,发现收到“SUCCESS”状态后,可以重定向到视图层JSP文件。
- 在jsp文件中, 框架标签会调用action类中的方法,继而调用数据层中方法,填充数据到视图层中。
- 一个完整的html响应返回到浏览器。