zoukankan      html  css  js  c++  java
  • Struts2典型应用

    1. Struts2处理表单数据

    例1.1 创建Java Web项目,编写一个Action对象,处理对表单提交的数据,模拟实现对指定用户的问候。

    (1)创建Java Web项目,将Struts的支持类型库添加到WEB-INF目录下的lib文件夹中。之后在web.xml文件中注册Struts2提供的过滤器。过滤器代码如下:

    <?xml version="1.0" encoding="GBK"?>
    <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>java_struts2</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>
      <!-- Struts2过滤器 -->
      <filter>
          <!-- 过滤器名称 -->
          <filter-name>struts2</filter-name>
          <!-- 过滤器类 -->
          <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
      </filter>
      <!-- Struts2过滤器映射 -->
      <filter-mapping>
          <!-- 过滤器名称 -->
          <filter-name>struts2</filter-name>
          <!-- 过滤器映射 -->
          <url-pattern>/*</url-pattern>
      </filter-mapping>
    </web-app>

    (2)创建一个Action对象,其名称为GreetingAction。实例中通过继承于ActionSupport类进行创建,其关键代码如下:

    package com.cn.action;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    public class GreetingAction extends ActionSupport {
        private static final long serialVersionUID = 1L;
        //用户名
        private String username;
        //处理请求
        @Override
        public String execute() throws Exception {
            // 判断用户名是否有效
            if(username==null||"".equals(username)){
                //返回到错误页面
                return ERROR;
            }else {
                return SUCCESS;
            }
        }
        //username属性的getter方法
        public String getUsername() {
            return username;
        }
        //username属性的setter方法
        public void setUsername(String username) {
            this.username = username;
        }
    }

    (3)在Web项目的源码文件夹中,创建名称为struts.xml的配置文件,在该文件中配置GreetingAction。关键代码如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
    <struts>
        <!-- 声明包 -->
        <package name="myPackage" extends="struts-default" namespace="/">        
            <!-- 定义action -->
            <action name="greeting" class="com.cn.action.GreetingAction">
                <!-- 定义成功的映射页面 -->
                <result name="success">success.jsp</result>
                <!-- 定义失败的映射页面 -->
                <result name="error">error.jsp</result>
            </action>
        </package>
    </struts>

    (4)创建程序中的首页面index.jsp,在该页面中编写一个表单,它的提交地址为greeting.action。关键代码如下:

    <%@ page language="java" contentType="text/html; charset=GB18030"
        pageEncoding="GB18030"%>
    <!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=GB18030">
    <title>Insert title here</title>
    </head>
    <body>
        <form action="greeting.action" method="post">
            请输入你的姓名:<input type="text" name="username">
            <input type="submit" value="提交">
        </form>
    </body>
    </html>

    (5)创建success.jsp页面。关键代码如下:

    <%@ page language="java" contentType="text/html; charset=GB18030"
        pageEncoding="GB18030"%>
    <%@ taglib uri="/struts-tags" prefix="s"%>
    <!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=GB18030">
    <title>Insert title here</title>
    </head>
    <body>
        <font color="red">
            <s:property value="username"/>
        </font>
        ,您好!
        <br>
        欢迎来到本站。
    </body>
    </html>

    success.jsp页面中的<s:property>标签是Struts2提供的标签库,主要用于输出Action对象中的信息。

    (6)创建名称为error.jsp页面。关键代码如下:

    <%@ page language="java" contentType="text/html; charset=GB18030"
        pageEncoding="GB18030"%>
    <!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=GB18030">
    <title>Insert title here</title>
    </head>
    <body>
        <font color="red">错误:您没有输入用户名!</font>
    </body>
    </html>

    运行上面的程序,如果出现No result defined for action com.cn.action.GreetingAction and result success错误,在struts.xml的配置文件的package里面增加 namespace="/" 告诉系统是从根本录寻找即可。

    2. 使用Map类型的request、session和application

    例2.1 通过ActionContext对象获取Map类型的requet、session、和application,分别为这3个对象设置一个info属性并赋值,然后在JSP页面获取3种作用域下的info属性信息。

    1)创建Java Web项目,将Struts的支持类型库添加到WEB-INF目录下的lib文件夹中。之后在web.xml文件中注册Struts2提供的过滤器。过滤器代码如下:

    <?xml version="1.0" encoding="GBK"?>
    <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>java_struts2</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>
      <!-- Struts2过滤器 -->
      <filter>
          <!-- 过滤器名称 -->
          <filter-name>struts2</filter-name>
          <!-- 过滤器类 -->
          <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
      </filter>
      <!-- Struts2过滤器映射 -->
      <filter-mapping>
          <!-- 过滤器名称 -->
          <filter-name>struts2</filter-name>
          <!-- 过滤器映射 -->
          <url-pattern>/*</url-pattern>
      </filter-mapping>
    </web-app>

    (2)创建名称为TestAction的类,该类继承于ActionSupport类,是一个Action对象。在这个类中分别创建Map类型的request、session和application,并在execut()方法中对其进行操作。关键代码如下:

    package com.cn.action;
    
    import java.util.Map;
    
    import com.opensymphony.xwork2.ActionContext;
    import com.opensymphony.xwork2.ActionSupport;
    
    public class TestAction extends ActionSupport {
        private static final long serialVersionUID = 1L;
        //Map类型的request
        private Map<String, Object> request;
        //Map类型的session
        private Map<String, Object> session;
        //Map类型的application
        private Map<String, Object> application;
        //构造方法
        @SuppressWarnings("unchecked")
        public TestAction() {
            // 获取ActionContext对象
            ActionContext context = ActionContext.getContext();
            //获取Map类型的request
            request = (Map<String, Object>) context.get("request");
            //获取Map类型的session
            session = context.getSession();
            //获取Map类型的application
            application = context.getApplication();        
        }
        /**
         * 请求处理方法
         * @return String
         */
        public String execute() throws Exception {
            // 字符串信息
            String info="明日科技";
            //向request添加信息
            request.put("info", info);
            //向session添加信息
            session.put("info", info);
            //向application添加信息
            application.put("info", info);
            //成功返回
            return SUCCESS;
        }    
    }

    (3)在Web项目的源码文件夹中,创建名称为struts.xml的配置文件,在该配置文件中配置TestAction。关键代码如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
    <struts>
        <constant name="struts.devMode" value="true"></constant>
        <!-- 声明包 -->
        <package name="myPackage" extends="struts-default" namespace="/">
            <!-- 定义action -->
            <action name="testAction" class="com.cn.action.TestAction">
                <!-- 定义成功的映射页面 -->
                <result name="success">success.jsp</result>
            </action>
        </package>
    </struts>

    (4)创建TestAction处理成功的返回页面success.jsp,在该页面中分别获取JSP内置对象request、session、application的info属性的值,并将这些值输出到JSP页面中。具体代码如下:

    <%@ page language="java" contentType="text/html; charset=GB18030"
        pageEncoding="GB18030"%>
    <!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=GB18030">
    <title>Insert title here</title>
    </head>
    <body>
        request范围内的info值:
        <font color="red"><%=request.getAttribute("info") %></font>
        <br>
        session范围内的info值:
        <font color="red"><%=session.getAttribute("info") %></font>
        <br>
        application范围内的info值:
        <font color="red"><%=application.getAttribute("info") %></font>
    </body>
    </html>

    (5)创建程序的首页index.jsp,在该页面中编辑一个超链接,将这个超链接指向testAction。关键代码如下:

    <%@ page language="java" contentType="text/html; charset=GB18030"
        pageEncoding="GB18030"%>
    <!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=GB18030">
    <title>Insert title here</title>
    </head>
    <body>
        <a href="testAction.action">Map类型的request、session、application</a>
        <br>
    </body>
    </html>

     3. 使用拦截器

    在Struts2框架中,如果创建了一个拦截器对象,需要对拦截器进行配置才可以应用到Action对象上。其中拦截器的创建比较简单,可以通过继承AbstractInterceptor对象进行创建,而它使用<interceptor-ref>标签进行配置。

    例3.1 为Action对象配置输出执行时间的拦截器,查看执行Action所需要的时间。

    (1)创建Java Web项目,将Struts的支持类型库添加到WEB-INF目录下的lib文件夹中。之后在web.xml文件中注册Struts2提供的过滤器。

    (2)创建名称为TestAction的类,该类继承于ActionSupport对象。关键代码如下:

    package com.cn.action;
    
    import com.opensymphony.xwork2.ActionSupport;
    
    public class TestAction extends ActionSupport {
        private static final long serialVersionUID = 1L;
        public String execute() throws Exception{
            //线程休眠1秒
            Thread.sleep(1000);  //方便查看执行时间
            return SUCCESS;
        }
    }

    (3)在struts.xml配置文件中配置TestAction对象,并将输出Action执行时间的拦截器timer应用到TestAction中。关键代码如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
    <struts>
        <!-- 声明常量(开发模式) -->
        <constant name="struts.devMode" value="true"></constant>
        <!-- 声明常量(在Struts的配置文件修改后,自动加载) -->
        <constant name="struts.configuration.xml.reload" value="true"></constant>
        <!-- 声明包 -->
        <package name="myPackage" extends="struts-default" namespace="/">    
            <!-- 定义action -->
            <action name="testAction" class="com.cn.action.TestAction">
                <!-- 配置拦截器 -->
                <interceptor-ref name="timer"/> 
                <!-- 定义成功的映射页面 -->
                <result name="success">success.jsp</result>
            </action>
        </package>
    </struts>

    在TestAction对象的配置中,为其配置了一个拦截器对象timer,其作用是输出TestAction执行的时间。

    (4)创建程序的首页页面index.jsp和TestAction返回的页面success.jsp,具体代码如下:

    <%@ page language="java" contentType="text/html; charset=GB18030"
        pageEncoding="GB18030"%>
    <!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=GB18030">
    <title>Insert title here</title>
    </head>
    <body>
        <a href="testAction.action">执行输出时间拦截器</a>
        <br>
    </body>
    </html>
    <%@ page language="java" contentType="text/html; charset=GB18030"
        pageEncoding="GB18030"%>
    <!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=GB18030">
    <title>Insert title here</title>
    </head>
    <body>
        <a href="index.jsp">返回</a>
        <br>
    </body>
    </html>

    在代码写完后,执行该程序,在控制台会输出TestAction执行所占用的时间。

  • 相关阅读:
    mongo的常用操作——增删改查
    配置我的sublime
    mongo概念
    mongo命令
    mongo安装与配置
    node搭建http基本套路
    模块的导出入
    vue数据绑定原理
    webpack打包速度优化
    工作中的优化之数字键盘优化
  • 原文地址:https://www.cnblogs.com/gaopeng527/p/4466535.html
Copyright © 2011-2022 走看看