struts2学习篇(一)之helloWorld

Struts2在用户请求和模块化处理方面以及页面的展现这块,Struts2 发挥的屌炸天作用;相对于传统的 Jsp+Servlet 模式,Struts2 更适合企业级团队开发,方便系统的维护

 

二、helloWorld:

1)项目的结构:

struts2学习篇(一)之helloWorld

HelloWorldAction.java:

 

package com.cy.action;

import com.opensymphony.xwork2.Action;

public class HelloWorldAction implements Action{

     //进入该类会默认执行execute方法

    public String execute() throws Exception {
        System.out.println("执行了Action的默认方法");
        return SUCCESS;
    }

}

 

struts.xml配置文件:

 

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

<struts>

    <!-- 可以创建很多的package,用name来区分,name="helloWorld"没有实际意义,比如说区分前后台-->
    <package name="helloWorld" extends="struts-default">
        <action name="hello" class="com.cy.action.HelloWorldAction">
            <!-- 默认是转发,转发到helloWorld.jsp -->
            <result name="success">helloWorld.jsp</result>
        </action>
    </package>

</struts>

 

web.xml配置文件:

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee" 
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
         id="WebApp_ID" version="2.5">
  <display-name>Struts2Chap01</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>
        <!-- struts2的核心控制器 -->
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <!-- /*表示会拦截所有的请求 -->
    <filter-mapping>
        <filter-name>Struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
        
</web-app>

 

helloWorld.jsp:

<body>
    struts2你好!!
</body>

2)测试结果:

浏览器中访问:http://localhost:8080/Struts2Chap01/hello

struts2学习篇(一)之helloWorld

 

控制台打印出来执行了Action的默认方法

 

整个流程简单分析:struts2的核心控制器拦截浏览器地址中url请求,找到对应的action处理类

 

<!-- 默认是转发,转发到helloWorld.jsp -->

 <action name="hello" class="com.cy.action.HelloWorldAction"> <result name="success">helloWorld.jsp</result>

</action>

 

然后进入HelloWorldAction类中执行execute方法

return SUCCESS,对应name="success",然后转发到helloWorld.jsp前台页面