---
title: "SSH中的重构 web状态Session的管理"
author: "newzhq"
date: "2014-12-26T00:38:21Z"
tags: []
categories: ["企业架构"]
slug: "ssh-web-session"
draft: false
lastmod: "2014-12-26T00:46:18Z"
id: 2170204
url: "https://newzhq.iteye.com/blog/2170204"
---

SSH中的Session管理

最近又看起了《重构》，还是觉得经典，从小点出发，比模式来的实际轻量，下面是对SSH做的一些优化，让代码看起来结构更清楚，以后会更多的尝试《重构》的方法来改变SSH，更接地气一点。

目的：单独一个类来处理Session数据

做法：建立一个类，通过私有静态变量和存取方法存储Session值。

 

```
public class SessionInfo {
    private static final String JXC_VALIDATECODE = "JXC_VALIDATECODE";

    public static void setValidateCode(String code) {
        put(JXC_VALIDATECODE, code);
    }

    public static String getValidateCode() {
        if (get(JXC_VALIDATECODE) == null) return null;
        return (String) get(JXC_VALIDATECODE);
    }

    private static Map getSession() {
        if (ActionContext.getContext().getSession() == null) {
            ActionContext.getContext().setSession(new HashMap());
        }

        return ActionContext.getContext().getSession();
    }

    private static void put(String key, Object code) {
        getSession().put(key, code);
    }

    private static Object get(String key) {
        return getSession().get(key);
    }
}
```

 由于在项目开发中可能多个开发人员都需要在存取Session中的某个值，所以等于把Session封装在类中，使其更安全更方便来使用。

 

也考虑通过单例来生成来用，但是有几个问题，一个是ActionContext是变化的不同的用户会话会重建ActionContext，使用单例也没多大意义，而且静态方法变成对象方法，单例至少还需要一个getInstance()方法后面才能跟方法增加调用方法时代码长度，所以没必要。