Struts入门程序示例及基本执行过程

该入门程序功能很简单,浏览器中输入http://localhost:8080/Struts2Demo/hello.action显示index.jsp页面内容。

程序运行结果如图:

程序运行结果

该Struts2程序目录结构如下图:

程序目录结构

项目部署文件web.xml代码:

  <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Struts2Demo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <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>

HelloAction类代码:

package com.zzw.action;

public class HelloAction {
    public String execute() {
        return "success";
    }
}

struts.xml文件代码:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>
  <package name="default"  namespace="/" extends="struts-default"> 
    <action name="hello" class="com.zzw.action.HelloAction">
      <result name="success">/index.jsp</result>
    </action>
  </package>
</struts>

Index.jsp文件代码:

 <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=ISO-8859-1">
    <title>Hello Struts</title>
  </head>
  <body>
    <h1>Hello Struts...</h1>
  </body>
</html>

该示例基本执行过程:

1.在地址栏中输入:http://localhost:8080/Struts2Demo/hello.action 回车,向服务器发送请求。
2. 在过滤器获取请求的路径,得到路径里的hello值。
3. 到示例项目下找struts.xml,使用dom4j解析得到xml文件中的内容,将hello值到xml文件找action标签和name属性值比对是否一样。
4. 如果属性值一样,找到name属性所在action标签里面的另外一个属性class值,得到的值是HelloAction的全路径,这一功能用反射来实现的。
5. 得到action方法的返回值。在struts.xml文件中,找到action标签里面的result标签,匹配该result标签的name属性值是否一样。如果一样,跳转到index.jsp页面。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值