Struts2之HelloWorld

首先既然是开发Struts程序的话,那么自然需要用到Struts2开发包,Struts2是apache旗下的开源框架,所有的开发包和源代码都可以在Apache官网下载。

那么,就来开始编写第一个Struts2程序。

 

 

1、新建一个Dynamic web project。 把必须的java包拷贝到lib目录下。

            至此准备工作就完成了,下面开始编写第一个Hello World!!!

 

        2、首先,struts2采用的是拦截器原理,所有的请求都会被一个过滤器给拦截,所以需要在web.xml文件中配置如下的过滤器,来过滤所有的请求。

1   <filter>
2       <filter-name>struts2</filter-name>
3       <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
4   </filter>
5   <filter-mapping>
6       <filter-name>struts2</filter-name>
7       <url-pattern>/*</url-pattern>
8   </filter-mapping>

 3、编写Action,要想实现Struts2程序有三种方法

①实现Action接口(com.opensymphony.xwork2.Action

②继承ActionSupport类 (com.opensymphony.xwork2.ActionSupport)

③继承一个自定义的类 

    由于ActionSupport类已经实现了Action接口,而且提供了更加丰富的操作方法,所以一般采用继承ActionSupport类的方式。

  1 package com.fuwh.struts2;

 2 
 3 import com.opensymphony.xwork2.Action;
 4 
 5 public class HelloWorld implements Action{
 6     
 7     private String HelloWorld;
 8     public String getHelloWorld() {
 9         return HelloWorld;
10     }
11     public void setHelloWorld(String helloWorld) {
12         HelloWorld = helloWorld;
13     }
14     @Override
15     public String execute() throws Exception {
16         // TODO Auto-generated method stub
17         HelloWorld="世界你好!!!";
18         return SUCCESS;
19     }
20 
21 }

 4、Action编写好了之后,需要编写一个struts.xml的配置文件,来管理Action的跳转关系

 <?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd"
>
<struts>
    <package name="helloWorld" extends="struts-default">
        <action name="hello" class="com.fuwh.struts2.HelloWorld">
            <result name="success">HelloWorld.jsp</result>
        </action>
    </package>
</struts>

 5、最后来编写HelloWorld.jsp页面

 <%@ page language="java" pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
</head>
<body>
${HelloWorld}
</body>
</html>

 6、将项目发布到服务器,请求如下连接,就大功告成了

 http://localhost/Struts2/hello

 

 7,最后来谈谈Struts2的工作原理

 

    

 

 

 

 

当Web容器收到请求(HttpServletRequest)它将请求传递给一个标准的的过滤链包括(ActionContextCleanUp)过滤器
经过Other filters(SiteMesh ,etc),需要调用FilterDispatcher核心控制器,然后它调用ActionMapper确定请求哪个Action,ActionMapper返回一个收集Action详细信息的ActionMaping对象。
FilterDispatcher将控制权委派给ActionProxy,ActionProxy调用配置管理器(ConfigurationManager) 从配置文件中读取配置信息(struts.xml),然后创建ActionInvocation对象。
ActionInvocation在调用Action之前会依次的调用所用配置拦截器(Interceptor N)一旦执行结果返回结果字符串ActionInvocation负责查找结果字符串对应的(Result)然后执行这个Result Result会调用一些模版(JSP)来呈现页面。
拦截器(Interceptor N)会再被执行(顺序和Action执行之前相反)最后响应(HttpServletResponse)被返回在web.xml中配置的那些过滤器和(核心控制器)(FilterDispatcher)。

 

posted @ 2016-06-18 19:15  Ouka傅  阅读(224)  评论(0编辑  收藏  举报