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" class="test.HelloAction" 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值