1.WebApplicationContextUtils
当 Web 应用集成 Spring 容器后,代表 Spring 容器的 WebApplicationContext 对象将以 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 为键存放在 ServletContext 属性列表中。
WebApplicationContext wac = (WebApplicationContext)servletContext. getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); |
但通过位于 org.springframework.web.context.support 包中的 WebApplicationContextUtils 工具类获取 WebApplicationContext 更方便:
WebApplicationContext wac =WebApplicationContextUtils. getWebApplicationContext(servletContext); |
当 ServletContext 属性列表中不存在 WebApplicationContext 时,getWebApplicationContext() 方法不会抛出异常,它简单地返回 null。如果后续代码直接访问返回的结果将引发一个 NullPointerException 异常,而 WebApplicationContextUtils 另一个 getRequiredWebApplicationContext(ServletContext sc) 方法要求 ServletContext 属性列表中一定要包含一个有效的 WebApplicationContext 对象,否则马上抛出一个 IllegalStateException 异常。
2.WebUtils
下面这些方法为访问 HttpServletRequest 和 HttpSession 中的对象和属性带来了方便:
方法 | 说明 |
---|---|
Cookie getCookie(HttpServletRequest request, String name) | 获取 HttpServletRequest 中特定名字的 Cookie 对象。如果您需要创建 Cookie, Spring 也提供了一个方便的 CookieGenerator 工具类; |
Object getSessionAttribute(HttpServletRequest request, String name) | 获取 HttpSession 特定属性名的对象,否则您必须通过request.getHttpSession.getAttribute(name) 完成相同的操作; |
Object getRequiredSessionAttribute(HttpServletRequest request, String name) | 和上一个方法类似,只不过强制要求 HttpSession 中拥有指定的属性,否则抛出异常; |
String getSessionId(HttpServletRequest request) | 获取 Session ID 的值; |
void exposeRequestAttributes(ServletRequest request, Map attributes) | 将 Map 元素添加到 ServletRequest 的属性列表中,当请求被导向(forward)到下一个处理程序时,这些请求属性就可以被访问到了; |
此外,WebUtils还提供了一些和ServletContext相关的方便方法:
方法 | 说明 |
---|---|
String getRealPath(ServletContext servletContext, String path) | 获取相对路径对应文件系统的真实文件路径; |
File getTempDir(ServletContext servletContext) | 获取 ServletContex 对应的临时文件地址,它以 File 对象的形式返回。 |
下面的片断演示了使用 WebUtils 从 HttpSession 中获取属性对象的操作:
protected Object formBackingObject(HttpServletRequest request) throws Exception { UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession"); if (userSession != null) { return new AccountForm(this.petStore.getAccount( userSession.getAccount().getUsername())); } else { return new AccountForm(); } } |