SessionHelper

来源:互联网 发布:cosme淘宝旗舰店真假 编辑:程序博客网 时间:2024/06/04 19:05

问题描述:

        strut2 的织入 Session 为原始 Map 类型,没有泛型化,在添加属性时就会有一个恼人的警告。

功能:

1、安全的消除警告

2、插入时检查类型,如果不符就提前报错(免得取值时才报转换异常的错误)


源代码:

package com.gq.util;import java.util.Map;public class SessionHelper {private Map session;private Class valueType;private SessionHelper( Map session, Class valueType ){this.session = session;this.valueType = valueType;}public static SessionHelper newInstance( Map session, Class valueType ){// valid parameterif( session == null ){throw new NullPointerException("session can't be null, but is null.");}if( valueType == null ){throw new NullPointerException("valueType can't be null, but is null.");}return new SessionHelper( session, valueType );}@SuppressWarnings("unchecked")// safe cast, because just put object of calss what you want.public void putIntoSession( Object key, Object value ){// valid parameterif( key == null || value == null ){throw new NullPointerException("key and value must not be null.");}// valid value's type weather what you wantif( value.getClass() != valueType ){throw new RuntimeException( "need class: " + valueType.getName() + " but is: " + value.getClass().getName() );}session.put(key, value);}}

使用示例:

//session.put(USER_SESSION_KEY, user);SessionHelper.newInstance( session, User.class ).putIntoSession( USER_SESSION_KEY, user );

原创粉丝点击