论坛首页 Java企业应用论坛

Struts2.0中获取项目的上下文的两种方式

浏览 3760 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (1)
作者 正文
   发表时间:2010-01-19  

  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);
    }

}

 

 

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics