学习是一个积累的过程,今天把自己看了的一些关于struts2的资料或是一些文档,通过这个helloworld小实例联系一下。
首先,导包 在lib下导入构建struts2框架所必须的包:
commons-logging-1.0.4.jar
freemarker-2.3.8.jar
ognl-2.6.11.jar
struts2-core-2.0.12.jar
xwork-2.0.6.jar
只要有着5个包就可以运行一个struts2的helloworld。
第二,配置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>
第三,在src目录下复制一个struts.xml 仅仅保留
<struts></struts>
第四,编写action类
package com.zxt.actionTest;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldAction extends ActionSupport {
private String a;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String helloWorld(){
this.a="helloWorld!!!";
return SUCCESS;
}
}
第五,配置struts.xml
<package name="com.zxt.actionTest" namespace="/np" extends="struts-default">
<action name="helloWorld" class="com.zxt.actionTest.HelloWorldAction" method="helloWorld">
<result name="success">/HelloWorld.jsp</result>
</action>
</package>
namespace 表示命名空间
第六,编写HelloWorld.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>HelloWorld</title>
</head>
<body>
<h1>我想说<s:property value="a"/></h1>
</body>
</html>
<%@ taglib prefix="s" uri="/struts-tags"%> 就是在地址/struts-tags下寻找标签库。
最后,启动tomcat在浏览器输入:
http://localhost:8080/Struts2Test/np/helloWorld.action
其中Struts2Test表示项目名
helloWorld对应action中的helloWorld()
运行机制
客户在浏览器中输入一个url,
浏览器通过HTTP协议将这个路径tomcat,
tomcat会根据这个路径找到对应项目下的web.XML,
在web.XML中可以找到有struts2的配置,
然后会找到struts2对应的struts.xml配置文件,
根据url解析struts.xml可以找到相应的class,
调用class返回String 根据 struts.xml找到相对应的jsp