项目的组成目录,首先需要 案例的运行过程,了解struts的加载过程。第一步创建Web项目 第二步添加Struts2的Jar包。
第三步在WEB-INF下面创建一个 web.文件,下面是wen.xml文件内容
<web-app id="starter" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <!-- 配置Struts2核心过滤器 --> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
第四步 处理用户请求的 Action类
package cn.itcast.action; import com.opensymphony.xwork2.ActionSupport; public class HelloWorldAction extends ActionSupport { /** * */ private static final long serialVersionUID = 1L; public String execute() throws Exception{ return SUCCESS; } }
第五步 编写Struts2的配置文件,
<?xml version="1.0" encoding="UTF-8"?> <!-- 配置Struts2配置文件的DTD信息 --> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <!-- Struts2的Action必须放到指定的包空间下定义 --> <package name="hello" namespace="/" extends="struts-default"> <!-- 定义action 该action对应的类为 cn.itcast.action.HelloWordAction --> <action name="helloWorld" class="cn.itcast.action.HelloWorldAction"> <result name="success">/success.jsp</result> </action> </package> </struts>第六步创建视图
index.jsp
<%@page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <title>首页</title> </head> <body> <h1>Welcome To Struts2!<h1> <a href="${pageContext.request.contentpath}/helloWorld.action"> Hello World </a> </body> </html>success.jsp
<%@page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>成功页面</title> </head> <body> 欢迎学习第一个Struts程序 </body> </html> 整个案例的运行流程如下图所示
