Struts2.0中获取项目的上下文的两种方式
方法一:
StringBuffer sb=new StringBuffer(); sb.append(File.separator+”images”+File.separator+”vacationImage”); String path=ServletActionContext.getServletContext().getRealPath(sb.toString());
方法二:
通过RequestUtils获取项目的上下文的信息:
String path=RequestUtils.getServletPath(ServletActionContext.getRequest());
源代码如下:
public class RequestUtils {
/** * Retrieves the current request servlet path. * Deals with differences between servlet specs (2.2 vs 2.3+) * * @param request the request * @return the servlet path */ public static String getServletPath(HttpServletRequest request) { String servletPath = request.getServletPath(); String requestUri = request.getRequestURI(); // Detecting other characters that the servlet container cut off (like anything after ‘;’) if (requestUri != null && servletPath != null && !requestUri.endsWith(servletPath)) { int pos = requestUri.indexOf(servletPath); if (pos > -1) { servletPath = requestUri.substring(requestUri.indexOf(servletPath)); } } if (null != servletPath && !”".equals(servletPath)) { return servletPath; } int startIndex = request.getContextPath().equals(“”) ? 0 : request.getContextPath().length(); int endIndex = request.getPathInfo() == null ? requestUri.length() : requestUri.lastIndexOf(request.getPathInfo());
if (startIndex > endIndex) { // this should not happen endIndex = startIndex; }
return requestUri.substring(startIndex, endIndex); }
}