---
title: "struts中的action是单态的"
author: "cakin24"
date: "2017-10-26T21:29:42Z"
tags: []
categories: ["编程语言"]
slug: "struts-action"
draft: false
lastmod: "2017-10-26T21:29:42Z"
id: 2397757
url: "https://cakin24.iteye.com/blog/2397757"
---

一 action特性

action是单态的，包括ActionServlet。

单态是指：在整个程序运行过程中，始终是一个对象。

 

二 action单态特性证明

1 LoginAction

package com.cakin.actions;

//这是一个action（表示小队长，需要继承Action）

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;

import org.apache.struts.action.ActionMapping;

import com.cakin.forms.UserForm;

public class LoginAction extends Action {

    private int num=0;

    //我们需要重新编写一个方法：execute会被自动调用，有点类似servlet的service方法。

    @Override

    public ActionForward execute(ActionMapping mapping, ActionForm form,

            HttpServletRequest request, HttpServletResponse response)

            throws Exception {

            //把form转成对应的UserForm对象

        UserForm userForm=(UserForm)form;

        num++;

        //简单验证

        if("123".equals(userForm.getPassword())){

            //把名字存放到request对象域

            //request.setAttribute("username", userForm.getUsername());

            request.setAttribute("num",num+"");

            return mapping.findForward("ok");

        }

        else{

            return mapping.findForward("err");

        }

    }

}

 

2 wel.jsp

&lt;%@ page language="java" import="java.util.\*" import="com.cakin.forms.\*" pageEncoding="utf-8"%&gt;

&lt;%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%&gt;

 

&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;

&lt;html&gt;

  &lt;head&gt;

    &lt;base href="&lt;%=basePath%&gt;"&gt;

   

    &lt;title&gt;My JSP 'wel.jsp' starting page&lt;/title&gt;

   

        &lt;meta http-equiv="pragma" content="no-cache"&gt;

        &lt;meta http-equiv="cache-control" content="no-cache"&gt;

        &lt;meta http-equiv="expires" content="0"&gt;   

        &lt;meta http-equiv="keywords" content="keyword1,keyword2,keyword3"&gt;

        &lt;meta http-equiv="description" content="This is my page"&gt;

        &lt;!--

        &lt;link rel="stylesheet" type="text/css" href="styles.css"&gt;

        --&gt;

 

  &lt;/head&gt;

 

  &lt;body&gt;

    welcome &lt;%=((UserForm)session.getAttribute("userForm")).getUsername() %&gt; &lt;br&gt;

    &lt;a href="/strutslogin/"&gt;返回重新登录&lt;/a&gt;

    num=&lt;%=request.getAttribute("num") %&gt;

  &lt;/body&gt;

&lt;/html&gt;

 

三 测试结果

 

![](http://dl2.iteye.com/upload/attachment/0127/5591/4567be32-ee72-3ad3-87c9-c5962e2400f0.png)