1. 程式人生 > >SpringMVC @SessionAttributes 使用詳解以及原始碼分析

SpringMVC @SessionAttributes 使用詳解以及原始碼分析

複製程式碼
public class SessionAttributesHandler {

    private final Set<String> attributeNames = new HashSet<String>();

    private final Set<Class<?>> attributeTypes = new HashSet<Class<?>>();

    private final Set<String> knownAttributeNames = Collections.synchronizedSet(new
HashSet<String>(4)); private final SessionAttributeStore sessionAttributeStore; public SessionAttributesHandler(Class<?> handlerType, SessionAttributeStore sessionAttributeStore) { Assert.notNull(sessionAttributeStore, "SessionAttributeStore may not be null.");
this.sessionAttributeStore = sessionAttributeStore; SessionAttributes annotation = AnnotationUtils.findAnnotation(handlerType, SessionAttributes.class); if (annotation != null) { this.attributeNames.addAll(Arrays.asList(annotation.value())); this.attributeTypes.addAll(Arrays.<Class<?>>asList(annotation.types())); }
this.knownAttributeNames.addAll(this.attributeNames); } public boolean hasSessionAttributes() { return ((this.attributeNames.size() > 0) || (this.attributeTypes.size() > 0)); } public boolean isHandlerSessionAttribute(String attributeName, Class<?> attributeType) { Assert.notNull(attributeName, "Attribute name must not be null"); if (this.attributeNames.contains(attributeName) || this.attributeTypes.contains(attributeType)) { this.knownAttributeNames.add(attributeName); return true; } else { return false; } } public void storeAttributes(WebRequest request, Map<String, ?> attributes) { for (String name : attributes.keySet()) { Object value = attributes.get(name); Class<?> attrType = (value != null) ? value.getClass() : null; if (isHandlerSessionAttribute(name, attrType)) { this.sessionAttributeStore.storeAttribute(request, name, value); } } } public Map<String, Object> retrieveAttributes(WebRequest request) { Map<String, Object> attributes = new HashMap<String, Object>(); for (String name : this.knownAttributeNames) { Object value = this.sessionAttributeStore.retrieveAttribute(request, name); if (value != null) { attributes.put(name, value); } } return attributes; } public void cleanupAttributes(WebRequest request) { for (String attributeName : this.knownAttributeNames) { this.sessionAttributeStore.cleanupAttribute(request, attributeName); } } Object retrieveAttribute(WebRequest request, String attributeName) { return this.sessionAttributeStore.retrieveAttribute(request, attributeName); } }
複製程式碼