1 52 53 package freemarker.ext.servlet; 54 55 import javax.servlet.http.HttpServletRequest ; 56 import javax.servlet.http.HttpServletResponse ; 57 import javax.servlet.http.HttpSession ; 58 59 import freemarker.template.ObjectWrapper; 60 import freemarker.template.TemplateHashModel; 61 import freemarker.template.TemplateModel; 62 import freemarker.template.TemplateModelException; 63 64 69 70 public final class HttpSessionHashModel 71 implements 72 TemplateHashModel 73 { 74 private HttpSession session; 75 private final ObjectWrapper wrapper; 76 77 private final FreemarkerServlet servlet; 79 private final HttpServletRequest request; 80 private final HttpServletResponse response; 81 82 87 public HttpSessionHashModel(HttpSession session, ObjectWrapper wrapper) 88 { 89 this.session = session; 90 this.wrapper = wrapper; 91 92 this.servlet = null; 93 this.request = null; 94 this.response = null; 95 } 96 97 108 public HttpSessionHashModel(FreemarkerServlet servlet, HttpServletRequest request, HttpServletResponse response, ObjectWrapper wrapper) 109 { 110 this.wrapper = wrapper; 111 112 this.servlet = servlet; 113 this.request = request; 114 this.response = response; 115 } 116 117 public TemplateModel get(String key) throws TemplateModelException 118 { 119 checkSessionExistence(); 120 return wrapper.wrap(session != null ? session.getAttribute(key) : null); 121 } 122 123 private void checkSessionExistence() throws TemplateModelException 124 { 125 if(session == null) { 126 session = request.getSession(false); 127 if(session != null && servlet != null) { 128 try { 129 servlet.initializeSession(request, response); 130 } 131 catch(Exception e) { 132 throw new TemplateModelException(e); 133 } 134 } 135 } 136 } 137 138 public boolean isEmpty() 139 throws 140 TemplateModelException 141 { 142 checkSessionExistence(); 143 return session == null || !session.getAttributeNames().hasMoreElements(); 144 } 145 } 146 | Popular Tags |