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

本文介绍了在Struts2.0框架中获取项目上下文路径的两种方法。第一种方法利用了`ServletActionContext.getServletContext().getRealPath()`来获取实际路径;第二种方法通过自定义`RequestUtils`类来获取请求的上下文路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值