Struts2的HelloWorld

<package name="tutorial" extends="struts-default">的name属性是什么

    当提交一个Html的Form给Struts2框架时,数据不再是提交给服务器端的某一个JSP页面,而是提交给一个Action类。而框架根据配置文件把与该Action类对应的页面(这个页面可以是JSP页面,也可以是PDF、Excel或Applet)返回给客户端。

写一个Struts2的HelloWorld , 我们需要做三件事:

1. 创建一个显示信息的JSP文件

2. 创建一个生成信息的Action类

3. 建立JSP页面和Action的mapping(映射)


创建MainJsp.jsp文件

Html代码

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
 <titie>
 Hello World!
 </titie>
 <body>
  <h2>
   <s:property value="message" />
  </h2>
 </body>
</html>

创建Action类MainAction.java

Java代码

package action;

import com.opensymphony.xwork2.ActionSupport;

public class MainAction extends ActionSupport {
 public static final String MESSAGE = "struts is up and running";
 private String message;

 public String execute() {
  setMessage(MESSAGE);
  return SUCCESS;

 }

 private void setMessage(String message) {
  this.message = message;
 }

 public String getMessage() {
  return message;
 }
}

在struts.xml建立映射

Xml代码

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
    "http://struts.apache.org/dtds/struts-2.1.7.dtd">

<struts>
 <package name="action" extends="struts-default">
  <!--  -->
  <action name="MainAction" class="action.MainAction">
  <result>/main/MainJsp.jsp</result>
  </action>
 </package>
</struts>

创建web.xml

Xml代码

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
   </filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>web.xml毫无疑问放在WEB-INF下

运行
现在,启动tomcat,访问http://localhost:8080/action/MainAction.action,能看到页面的title为"Hello World!" ,页面上显示"Struts is up and running!".

它们怎么运行的
1、       struts2容器收到MainAction.action请求,从web.xml获取设置,org.apache.struts2.dispatcher.FilterDispatcher是所有应用(包括*.action)的入口点。
2、       struts2在struts.xml中找到MainAction类(Action),并调用它的execute方法。
3、       execute方法给message变量赋值,并返回SUCCESS,struts2收到SUCCESS标志,按照映射关系,把MainJsp.jsp返回客户端。
4、       当MainJsp.jsp开始运行,<s:property value="message" />会调用MainAction类getMessage方法,把结果显示在页面上。

原文地址:https://www.cnblogs.com/asijack/p/3145603.html