首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

struts2 运作原理

2012-08-24 
struts2 运行原理1.1简单例子先做一个最简单的struts2的例子:在浏览器中请求一个action,然后返回一个字符

struts2 运行原理
1.1         简单例子
先做一个最简单的struts2的例子:在浏览器中请求一个action,然后返回一个字符串到jsp页面上显示出来。

第一步:把struts2最低配置的jar包加入的项目中。
         commons-logging-1.0.4.jar
    freemarker-2.3.8.jar
    ognl-2.6.11.jar
    struts2-core-2.0.11.jar
    xwork-2.0.4.jar

第二步:在web.xml中加入拦截器配置。
         <filter>
        <filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

第三步:把空的struts.xml配置文件放到项目src下面。
         <struts>
  
</struts>

第四部:编写自定义的action类。
package test;
import com.opensymphony.xwork2.ActionSupport;
public class HelloAction extends ActionSupport {
    private String str;
    public String hello() {
       this.str = "hello!!!";
       return "success";
    }
    public String getStr() {
       return str;
    }
    public void setStr(String str) {
       this.str = str;
    }
}

第五步:编写struts.xml配置文件。
<struts>
    <package name="test" namespace="/np" extends="struts-default">
       <action name="hello" method="hello">
           <result name="success">/hello.jsp</result>
       </action>
    </package>
</struts>

第六步:编写hello.jsp文件。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ 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=UTF-8">
<title>Test</title>
</head>
<body>
    <h1><s:property value="str"/></h1>
</body>
</html>

第七步:启动tomcat,在浏览器中访问:
         http://localhost:8080/hello/np/hello.action
         hello 是项目名字
         np 命名空间,对应namespace里面的字符串。
         hello.action 其中hello对应action里面的字符串,“.action”表示请求的是一个action。

1.2         运行机制
1)客户端在浏览器中输入一个url地址。
2)这个url请求通过http协议发送给tomcat。
3)tomcat根据url找到对应项目里面的web.xml文件。
4)在web.xml里面会发现有struts2的配置。
5)然后会找到struts2对应的struts.xml配置文件。
6)根据url解析struts.xml配置文件就会找到对应的class。
7)调用完class返回一个字String,根据struts.xml返回到对应的jsp。


Struts2的核心就是拦截器。Struts.xml中所有的package都要extends="struts-default"。同理与所有的Java类都要extends自Object一样。struts-default.xml里面就是要做以上事情。


注:转自:http://blog.csdn.net/zq9017197/archive/2010/10/22/5958627.aspx

热点排行