JakartaEE Struts2使用

简介: 1. Struts2下载解压后的目录结构如下:图1.png从一个高水平角度看,Struts2 是一个MVC拉动的(或MVC2)框架,Struts2 的模型-视图-控制器模式是通过以下五个核心部分进行实现的:操作(Actions...

1. Struts2下载

解压后的目录结构如下:


img_37b7ecb8a49e2e2e671a29e6a32278c1.png
图1.png

从一个高水平角度看,Struts2 是一个MVC拉动的(或MVC2)框架,Struts2 的模型-视图-控制器模式是通过以下五个核心部分进行实现的:

  • 操作(Actions)
  • 拦截器(Interceptors)
  • 值栈(Value Stack)/OGNL
  • 结果(Result)/结果类型
  • 视图技术
img_541aa112b85a6dbc3e4717b106d3c8cd.png
图2.png

请求生命周期
通过上述图片的描述,我们可以依照下面几点解释在Struts2 中用户的请求生命周期:

  • 用户发送一个资源需求的请求到服务器(例如:页面)。
  • 核心控制器查看请求后确定适当的动作。
  • 使用验证、文件上传等配置拦截器功能。
  • 执行选择的动作来完成请求的操作。
  • 如果需要的话,配置的拦截器可做任何后期处理。
  • 最后,由视图显示结果并返回给用户。

2. HelloWorld程序

1. 四个组件:
  • Action(操作)
    创建一个动作类,包含完整的业务逻辑并控制用户、模型以及视图间的交互。
  • Interceptors(拦截器)
    这是控制器的一部分,可依据需求创建拦截器,或使用现有的拦截器。
  • View(视图)
    创建一个JSP与用户进行交互,获取输入并呈现最终信息。
  • Configuration Files(配置文件)
    创建配置文件来连接动作、视图以及控制器,这些文件分别是struts.xml、web.xml以及struts.properties。
2. 创建项目
img_937f25158a700b4815dd0302f846ad49.png
图3.png

记得勾选Generate web.xml deployment descriptor.


img_eb041554a43c559431aa81be02119338.png
图4.png

目录结构:


img_a78dd12fde95fd54d215ac9d0a024554.png
图4.png
3. 导入jar包

将struts-2.3.34文件中的lib文件夹中的一下jar包引入项目的WebContent/WEB-INF/lib文件夹中

  • commons-fileupload-1.3.2.jar
  • commons-io-2.2.jar
  • commons-lang-2.4.jar
  • commons-lang3-3.2.jar
  • commons-logging-1.1.3.jar
  • freemarker-2.3.22.jar
  • javassist-3.11.0.GA
  • ognl-3.0.21.jar
  • struts2-core-2.3.34.jar
  • xwork-core.2.3.34.jar
img_4d8b3b3f0ae49676d5d8534a5fb4785c.png
图5.png
4. 创建HelloWorldAction类
public class HelloWorldAction {
    private String name;
    
    public String execute() throws Exception{
        return "success";
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }   
}
5. 创建HelloWorld.jsp页面

在/Webcontent/下创建jsp文件夹,将所有创建的jsp页面存储在这个文件夹,在/Webcontent/jsp/文件夹下创建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="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
    </head>
    <body>
        Hello World, <s:property value="name"/>
    </body>
</html>
6. 在/WebContent/jsp/页面创建index.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="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
    </head>
    <body>
        <h1>Hello World From Struts2</h1>
        <form action="hello">
            <label for="name"> Please enter your name</label><br>
            <input type="text" name="name"/>
            <input type="submit" value="Say Hello"/>
        </form>
    </body>
</html>
7. 在src目录下创建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>
    <constant name="struts.devMode" value="true" />
    <package name="helloworld" extends="struts-default">
        <action name="hello"
            class="com.mazaiting.struct2.HelloWorldAction"
            method="execute">
            <result name="success">/jsp/HelloWorld.jsp</result>
        </action>
    </package>
</struts>
8. 在src目录下创建logging.properties配置文件
org.apache.catalina.core.ContainerBase.[Catalina].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].handlers = \ java.util.logging.ConsoleHandler
9. 在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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>HelloWorld</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>/jsp/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.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
10. 运行项目
img_8155d739977b1114d806cf5ded22f8ef.png
图6.png

在输入框中输入文字,点击Say Hello


img_16de7c3847948a68c5be7cf51c600d4e.png
图7.png
11. 设置索引

修改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>
    <constant name="struts.devMode" value="true" />
    <package name="helloworld" extends="struts-default">
        <action name="index">
            <result>/jsp/index.jsp</result>
        </action>
        <action name="hello"
            class="com.mazaiting.struct2.HelloWorldAction"
            method="execute">
            <result name="success">/jsp/HelloWorld.jsp</result>
        </action>
    </package>
</struts>

在浏览器输入http://localhost:8080/HelloWorld/index.action即可访问.

3. 配置文件

1). 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>
    <constant name="struts.devMode" value="true" />
    <package name="helloworld" extends="struts-default">
        <action name="index">
            <result>/jsp/index.jsp</result>
        </action>
        <action name="hello"
            class="com.mazaiting.struct2.HelloWorldAction"
            method="execute">
            <result name="success">/jsp/HelloWorld.jsp</result>
        </action>
        <!-- more actions can be listed here -->
    </package>
    <!-- more packages can be listed here -->
</struts>
  • <package>标签具有以下属性:
属性 描述
name(必需) 为package的唯一标识
extends 指定package继承另一package的所有配置。通常情况下,我们使用struts-default作为package的基础。
abstract 定义package为抽象的。如果标记为true,则package不能被最终用户使用。
namespace Actions的唯一命名空间
  • <constant>标签以及name和value属性将用于覆盖default.properties中定义的任一属性,就像我们设置的struts.devMode属性一样。设置struts.devMode属性允许我们在日志文件中查看更多的调试消息。

  • Results(结果)确定在执行操作后返回到浏览器的内容,而从操作返回的字符串应该是结果的名称。 Results按上述方式配置,或作为“全局”结果配置,可用于包中的每个操作。 Results有nametype属性可选,默认的name值是“success”。

  • Struts.xml文件可以随着时间的推移而增长,因此通过包打破它是使它模块化的一种方式,但struts提供了另一种模块化struts.xml文件的方法,你可以将文件拆分为多个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>
     <include file="my-struts1.xml"/>
     <include file="my-struts2.xml"/>
</struts>
2). struts.properties文件

配置文件提供了一种机制来改变框架的默认行为。

### When set to true, Struts will act much more friendly for developers
struts.devMode = true

### Enables reloading of internationalization files
struts.i18n.reload = true

### Enables reloading of XML configuration files
struts.configuration.xml.reload = true

### Sets the port that the server is run on
struts.url.http.port = 8080

4. 拦截器

1). 分类
序号 拦截器和说明
1 alias 允许参数在请求之间使用不同的别名。
2 checkbox 通过为未检查的复选框添加参数值false,以辅助管理复选框。
3 conversionError 将字符串转换为参数类型的错误信息放置到action的错误字段中。
4 createSession 自动创建HTTP会话(如果尚不存在)。
5 debugging 为开发人员提供一些不同的调试屏幕。
6 execAndWait 当action在后台执行时,将用户发送到中间的等待页面。
7 exception 映射从action到结果抛出的异常,允许通过重定向自动处理异常。
8 fileUpload 便于文件上传。
9 i18n 在用户会话期间跟踪选定的区域。
10 logger 通过输出正在执行的action的名称提供简单的日志记录。
11 params 设置action上的请求参数。
12 prepare 这通常用于执行预处理工作,例如设置数据库连接。
13 profile 允许记录action的简单分析信息。
14 scope 在会话或应用程序范围内存储和检索action的状态。
15 ServletConfig 提供可访问各种基于servlet信息的action。
16 timer 以action执行时间的形式提供简单的分析信息。
17 token 检查action的有效性,以防止重复提交表单。
18 validation 提供action的验证支持。
2). 使用Struts2中的拦截器

I. 给HelloWorldAction 添加timer拦截器(测量执行action方法所需的时间)及params拦截器(将请求参数发送给action)

<!-- 根标记元素 -->
<struts>
    <!-- 开发模式-默认为false -->
    <constant name="struts.devMode" value="true" />
    <!-- 声明不同的包, 标签允许配置的分离和模块化 -->
    <package name="helloworld" extends="struts-default">
        <action name="index">
            <result>/jsp/index.jsp</result>
        </action>
        <action name="hello"
            class="com.mazaiting.struct2.HelloWorldAction"
            method="execute">
            <!-- 设置action上的请求参数 -->
            <interceptor-ref name="params"/>
            <!-- 以action执行时间的形式提供简单的分析信息  -->
            <interceptor-ref name="timer"/>
            <result name="success">/jsp/HelloWorld.jsp</result>
        </action>
        <!-- more actions can be listed here -->
    </package>
    <!-- more packages can be listed here -->
</struts>

II. 测试


img_af2e255d2dcf011d8a98bcdd8a66b8e4.png
图8.png

在最后两行打印了当前action执行的时间。

3). 自定义拦截器

I. 创建拦截器类

public class MyInterceptor extends AbstractInterceptor {

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        System.out.println("Pre-Processing--先执行");
        
        // 执行方法
        String result = invocation.invoke();
        
        System.out.println("Post-Processing--后执行");
        return result;
    }
}
img_824cf373a54838771f526ff4d10cc6d6.png
图9.png

II. 创建Action类

public class HelloWorldAction extends ActionSupport{
    private String name;
    
    public String execute() throws Exception{
        System.out.println("execute...");
        return "success";
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }   
}

III. structs.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>
    <!-- 开发模式-默认为false -->
    <constant name="struts.devMode" value="true" />
    <!-- 声明不同的包, 标签允许配置的分离和模块化 -->
    <package name="helloworld" extends="struts-default">
        <interceptors>
            <interceptor name="myInterceptor" class="com.mazaiting.struct2.MyInterceptor"/>
        </interceptors>
        <action name="index">
            <result>/jsp/index.jsp</result>
        </action>
        <action name="hello"
            class="com.mazaiting.struct2.HelloWorldAction"
            method="execute">
            <!-- 设置action上的请求参数 -->
            <interceptor-ref name="params"/>
            <!-- 以action执行时间的形式提供简单的分析信息  -->
            <interceptor-ref name="timer"/>
            <!-- 自定义拦截器 -->
            <interceptor-ref name="myInterceptor"/>
            <result name="success">/jsp/HelloWorld.jsp</result>
        </action>
        <!-- more actions can be listed here -->
    </package>
    <!-- more packages can be listed here -->
</struts>

IV. 执行结果


img_7a0f97eb98ebebb74665426366fad682.png
图10.png

5. 文件上传

注意:服务器可能有适当的安全策略,禁止你写入临时目录以外的目录以及属于Web应用程序的目录。使用FileUpload过滤器

1). 创建jsp文件

I. 文件上传fileupload.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="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>File Upload</title>
    </head>
    <body>
        <form action="upload" method="post" enctype="multipart/form-data">
            <label for="myFile">Upload your file</label>
            <input type="file" name="myFile"/>
            <input type="submit" value="upload"/>
        </form>
    </body>
</html>

II. 创建上传成功success.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="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>File Upload Success</title>
    </head>
    <body>
        You have successfully uploaded <s:property value="myFileFileName"/>
    </body>
</html>

III. 创建上传失败error.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="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>File Upload Error</title>
    </head>
    <body>
        There has been an error in uploading the file.
    </body>
</html>
2). 创建FileUploadAction
/**
 *  默认情况下,FileUpload拦截器为你提供三个参数,它们分别按以下方式命名:
 *  [文件名参数] - 这是用户已上传的实际文件。在这个例子中它将是“myFile”
 *  [文件名参数]ContentType - 这是上传的文件的内容类型。在这个例子中,它将是“myFileContentType”
 *  [文件名参数]FileName - 这是上传的文件的名称。在这个例子中,它将是“myFileFileName”
 * @author mazaiting
 */
public class FileUploadAction extends ActionSupport{
    
    private File myFile;
    private String myFileContentType;
    private String myFileFileName;
    private String destPath;
    
    @Override
    public String execute() throws Exception {
        destPath = "E:/file/";
        
        
        try {
            System.out.println("Src File name: " + myFile);
            System.out.println("Dst File name: " + myFileFileName);
            
            File destFile = new File(destPath, myFileFileName);
            FileUtils.copyFile(myFile, destFile);
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
                
        return SUCCESS;
    }

    public File getMyFile() {
        return myFile;
    }

    public void setMyFile(File myFile) {
        this.myFile = myFile;
    }

    public String getMyFileContentType() {
        return myFileContentType;
    }

    public void setMyFileContentType(String myFileContentType) {
        this.myFileContentType = myFileContentType;
    }

    public String getMyFileFileName() {
        return myFileFileName;
    }

    public void setMyFileFileName(String myFileFileName) {
        this.myFileFileName = myFileFileName;
    }

    public String getDestPath() {
        return destPath;
    }

    public void setDestPath(String destPath) {
        this.destPath = destPath;
    }
}
3). 配置文件
序号 属性和说明
1 struts.multipart.maxSize 可接受的上传文件的最大值(以字节为单位),默认值为250M。
2 struts.multipart.parser 用于上传多部分表单的库,默认为jakarta。
3 struts.multipart.saveDir 存储临时文件的位置,默认是javax.servlet.context.tempdir。
<?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>
    <!-- 开发模式-默认为false -->
    <constant name="struts.devMode" value="true" />
    <!-- 可接受的上传文件的最大值(以字节为单位),默认值为250M -->
    <constant name="struts.multipart.maxSize" value="1000000"/>
    <!-- 声明不同的包, 标签允许配置的分离和模块化 -->
    <package name="helloworld" extends="struts-default">
        <interceptors>
            <interceptor name="myInterceptor" class="com.mazaiting.struct2.MyInterceptor"/>
        </interceptors>
        <action name="index">
            <result>/jsp/index.jsp</result>
        </action>
        <action name="hello"
            class="com.mazaiting.struct2.HelloWorldAction"
            method="execute">
            <!-- 设置action上的请求参数 -->
            <interceptor-ref name="params"/>
            <!-- 以action执行时间的形式提供简单的分析信息  -->
            <interceptor-ref name="timer"/>
            <!-- 自定义拦截器 -->
            <interceptor-ref name="myInterceptor"/>
            <result name="success">/jsp/HelloWorld.jsp</result>
        </action>
        <!-- more actions can be listed here -->
        <action name="upload" class="com.mazaiting.struct2.FileUploadAction">
            <!-- 注意过滤器的顺序 -->
            <interceptor-ref name="fileUpload">
                <param name="maximumSize">500000000</param>
                <param name="allowedTypes">image/jpeg,image/gif,text/plain,application/vnd.ms-powerpoint</param>
                <param name="allowedExtensions">.txt,.ppt,.jpeg,.jpg,.gif</param>
            </interceptor-ref>
            <interceptor-ref name="basicStack"/>
            <result name="success">/jsp/success.jsp</result>
            <result name="error">/jsp/error.jsp</result>
        </action>
    </package>
    <!-- more packages can be listed here -->
</struts>

fileUpload拦截器有两个参数:maximumSize和allowedTypes。

  • maximumSize参数是设置所允许的文件大小的最大值(默认约为2MB)。
  • allowedTypes参数是所允许的内容(MIME)类型的用逗号分隔的列表
4). 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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>文件上传</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>/jsp/fileupload.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.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
5). 执行测试
img_828d697b9e1f5d3ab8f8eacd2a3117e8.png
图11.png

点击upload后


img_d9552abf70a0a0441aa4a91db95e54fb.png
图12.png

6. 全局异常映射

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>
    <!-- 开发模式-默认为false -->
    <constant name="struts.devMode" value="true" />
    <!-- 可接受的上传文件的最大值(以字节为单位),默认值为250M -->
    <constant name="struts.multipart.maxSize" value="1000000"/>
    <!-- 声明不同的包, 标签允许配置的分离和模块化 -->
    <package name="helloworld" extends="struts-default">
    
        <!-- interceptors  -->
        <interceptors>
            <interceptor name="myInterceptor" class="com.mazaiting.struct2.MyInterceptor"/>
        </interceptors>
        
        <!-- global-exception-mappings  -->
        <global-exception-mappings>
            <exception-mapping result="error" exception="java.lang.NullPointerException"/>
        </global-exception-mappings>
        
        <!-- action* -->
        <action name="index">
            <result>/jsp/index.jsp</result>
        </action>
        <action name="hello"
            class="com.mazaiting.struct2.HelloWorldAction"
            method="execute">
            <!-- 设置action上的请求参数 -->
            <interceptor-ref name="params"/>
            <!-- 以action执行时间的形式提供简单的分析信息  -->
            <interceptor-ref name="timer"/>
            <!-- 自定义拦截器 -->
            <interceptor-ref name="myInterceptor"/>
            <result name="success">/jsp/HelloWorld.jsp</result>
        </action>
        <!-- more actions can be listed here -->
        <action name="upload" class="com.mazaiting.struct2.FileUploadAction">
            <!-- 注意过滤器的顺序 -->
            <interceptor-ref name="fileUpload">
                <param name="maximumSize">500000000</param>
                <param name="allowedTypes">image/jpeg,image/gif,text/plain,application/vnd.ms-powerpoint</param>
                <param name="allowedExtensions">.txt,.ppt,.jpeg,.jpg,.gif</param>
            </interceptor-ref>
            <interceptor-ref name="basicStack"/>
            <result name="success">/jsp/success.jsp</result>
            <result name="error">/jsp/error.jsp</result>
        </action>
    </package>
    <!-- more packages can be listed here -->
</struts>

6. 注解

1). 添加jar包

在之前导入包的基础上新增antlr-2.7.2.jar、asm.3.3.jar、asm-commons-3.3.jar和struts2-convention-plugin-2.3.34.jar


img_8c34762d28e9434d9df54ca4e3c41db8.png
图13.png
2). 创建视图

I. 创建主页

<%@ 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="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Employee Form</title>
    </head>
    <body>
        <s:form action="empinfo" method="post">
            <s:textfield name="name" label="Name" size="20"/>
            <s:textfield name="age" label="Age" size="20"/>
            <s:submit name="submit" label="Submit" align="center"/>
        </s:form>
    </body>
</html>

II. 创建成功视图

<%@ 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="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Success</title>
    </head>
    <body>
        Employee Information is captured successfully.
    </body>
</html>

III. 创建失败视图

<%@ 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="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Error</title>
    </head>
    <body>
        Employee Information is captured error.
    </body>
</html>
3). 创建Action
@Results({
    @Result(name="success", location="/jsp/success.jsp"),
    @Result(name="error", location="/jsp/error.jsp"),
    @Result(name="input", location="/jsp/index.jsp")
})
public class EmployeeAction extends ActionSupport{
    private String name;
    private int age;
    
    @Action(value="/empinfo")
    @Override
    public String execute() throws Exception {
        return SUCCESS;
    }

    @RequiredFieldValidator(message="The name is required.")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @IntRangeFieldValidator(message="Age must be in between 28 and 65",
            min = "29", max = "65")
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
4). 配置文件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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>StrutsAnnoTest</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>/jsp/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.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    <init-param>
        <param-name>struts.devMode</param-name>
        <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
5. 测试
img_2de7ed01e71c1f95b383ceb0c536ac49.png
图14.png
6. 项目结构图
img_8edd6352e87d64621db5f9a65b57a10d.png
图15.png
目录
相关文章
|
7月前
|
安全 Java API
Struts2
访问web资源 1》使用servlet API解耦的方式,获取的方法较少   1.使用ActionContext,一个一个获取,效率不高   2.实现XxxAware接口(ApplicationAware,SessionAware.....)推荐,
25 0
|
设计模式 开发框架 安全
Struts,你为何死不悔改!
上篇文章《诡异的字符串问题。。。》的问题已经解决了,我一直相信「团队力量的重要性」,虽然我不能保证加入群的每一个人都是乐于分享的同学,但我始终群里的各位同学总会慢慢被我们这种乐于分享的群氛围所影响。就以上篇文章为例,群里的 Univechige 同学专门给 IntelliJ IDEA 官方发邮件寻求原因,这便是一个好的开端,我相信有各位同学的共同维护,后面群氛围会越来越好。下面给出 IDEA 官方的答复,见下图。
141 0
Struts,你为何死不悔改!
|
Java
Struts2【配置】 (一)
上篇Struts博文已经讲解了Struts的开发步骤以及执行流程了…..对Struts的配置文件有了了解…..本博文继续讲解Struts在配置的时候一些值得要学习的细节…
80 0
Struts2【配置】 (一)
|
Web App开发 Java Apache
struts
运行流程 客户端浏览器通过HTTP请求,访问控制器,然后控制器读取配置文件,然后执行服务器端跳转,执行相应的业务逻辑,然后,在调用模型层,取得的结果展示给jsp页面,最后返回给客户端浏览器 组成部分 struts 视图 标签库 控制器 action 模型层 ActionFrom JavaBean struts maven 安装官网 : https://struts.
987 0
|
Java 数据库连接
[Struts]HibernatePlugIn for Struts(转贴)
这个Plugin的作用是在Struts应用程序启动时进行hibernate的初始化操作,原文HibernatePlugIn for Struts,步骤很简单: 1、在struts-config.xml里增加: <plug-in className="org.
1145 0
|
SQL JavaScript 前端开发
|
Java 数据安全/隐私保护 开发者
|
Web App开发 JavaScript Java