當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpServletRequest.getContextPath方法代碼示例

本文整理匯總了Java中javax.servlet.http.HttpServletRequest.getContextPath方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpServletRequest.getContextPath方法的具體用法?Java HttpServletRequest.getContextPath怎麽用?Java HttpServletRequest.getContextPath使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在javax.servlet.http.HttpServletRequest的用法示例。


在下文中一共展示了HttpServletRequest.getContextPath方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: accept

import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
private void accept(HttpServletRequest req, HttpServletResponse resp) {
    try {
        String localAddr = req.getLocalAddr();
        Properties properties = EngineFactory.getPropeties();
        if (properties.getProperty("hostname") != null) {
            localAddr = properties.getProperty("hostname");
        }
        String path = "http://" + localAddr + ":" + req.getLocalPort() + req.getContextPath();
        InputStream is = getClass().getResourceAsStream(
                "/com/ramussoft/jnlp/ramus-http-client.jnlp");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int r;
        while ((r = is.read()) >= 0)
            out.write(r);
        String string = MessageFormat.format(new String(out.toByteArray(),
                "UTF8"), path);
        resp.setContentType("application/x-java-jnlp-file");
        OutputStream o = resp.getOutputStream();
        o.write(string.getBytes("UTF8"));
        o.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
 
開發者ID:Vitaliy-Yakovchuk,項目名稱:ramus,代碼行數:26,代碼來源:JNLPHTTPServlet.java

示例2: setRequest

import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
/**
 * Set the request that we are wrapping.
 *
 * @param request The new wrapped request
 */
void setRequest(HttpServletRequest request) {

    super.setRequest(request);

    // Initialize the attributes for this request
    dispatcherType = request.getAttribute(Globals.DISPATCHER_TYPE_ATTR);
    requestDispatcherPath = 
        request.getAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR);

    // Initialize the path elements for this request
    contextPath = request.getContextPath();
    pathInfo = request.getPathInfo();
    queryString = request.getQueryString();
    requestURI = request.getRequestURI();
    servletPath = request.getServletPath();

}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:23,代碼來源:ApplicationHttpRequest.java

示例3: ZNodeResource

import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
public ZNodeResource(@DefaultValue("") @QueryParam("session") String session,
        @Context UriInfo ui,
        @Context HttpServletRequest request
        )
        throws IOException {

    String contextPath = request.getContextPath();
    if (contextPath.equals("")) {
        contextPath = "/";
    }
    if (session.equals("")) {
        session = null;
    } else if (!ZooKeeperService.isConnected(contextPath, session)) {
        throw new WebApplicationException(Response.status(
                Response.Status.UNAUTHORIZED).build());
    }
    zk = ZooKeeperService.getClient(contextPath, session);
}
 
開發者ID:didichuxing2,項目名稱:https-github.com-apache-zookeeper,代碼行數:19,代碼來源:ZNodeResource.java

示例4: getUrl

import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
private String getUrl(HttpServletRequest request){
	String contextPath=request.getContextPath();
	String uri = request.getRequestURI();
	int pathParamIndex = uri.indexOf(';');
	if (pathParamIndex > 0) {
		// strip everything from the first semi-colon
		uri = uri.substring(0, pathParamIndex);
	}
	int queryParamIndex = uri.indexOf('?');
	if (queryParamIndex > 0) {
		// strip everything from the first question mark
		uri = uri.substring(0, queryParamIndex);
	}
	if(contextPath.length()>1){
		uri=uri.substring(contextPath.length(),uri.length());
	}
	return uri;
}
 
開發者ID:bsteker,項目名稱:bdf2,代碼行數:19,代碼來源:ControllerFilter.java

示例5: getDomain

import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
/**
 * 根據 request獲取完整的域名,如http://www.abc.com:8080
 * 如果端口為80則為:http://www.abc.com
 * @return
 */
public static String getDomain(){
	HttpServletRequest request  = ThreadContextHolder.getHttpRequest();
	if(request==null) return "";
	String port  = ""+request.getServerPort();
	if(port.equals("80")){
		port="";
	}else{
		port =":"+ port;
	}
	
	String contextPath = request.getContextPath();
	if(contextPath.equals("/")){
		contextPath="";
	}
	
	String domain ="http://"+ request.getServerName()+port;
	domain+=contextPath;
	return domain;
}
 
開發者ID:yulele166,項目名稱:pub-service,代碼行數:25,代碼來源:RequestUtil.java

示例6: setSessionCookie

import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
public static void setSessionCookie(HttpServletRequest request, HttpServletResponse response, String name, String value) {
    if (value == null){
        value = StringUtils.EMPTY;
    }
    String path = request.getContextPath() != null ? request.getContextPath() : "/";
    if ("".equals(path)){
        path = "/";
    }
    Cookie cookie = new Cookie(name, value);
    cookie.setPath(path);
    cookie.setVersion(1);
    addSecureParam(request, cookie);
    response.addCookie(cookie);
}
 
開發者ID:bridgeli,項目名稱:netty-socketio-demo,代碼行數:15,代碼來源:CookieUtils.java

示例7: doFilter

import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
@Override
public void doFilter(ServletRequest req, ServletResponse resp,	FilterChain chain) throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest)req;
	HttpServletResponse response = (HttpServletResponse)resp;	
	
	String path = request.getContextPath() + request.getServletPath() + request.getPathInfo();

	
	if (path.endsWith(LOGIN_PATH) || path.endsWith(LOGOUT_PATH) || path.endsWith(LOADDB_PATH)) {
		// if logging in, logging out, or loading the database, let the request flow
		chain.doFilter(req, resp);
		return;
	}
	
	Cookie cookies[] = request.getCookies();
	Cookie sessionCookie = null;

	if (cookies != null) {
		for (Cookie c : cookies) {
			if (c.getName().equals(LoginREST.SESSIONID_COOKIE_NAME)) {
				sessionCookie = c;
			}
			if (sessionCookie!=null)
				break; 
		}
		String sessionId = "";
		if (sessionCookie!=null) // We need both cookie to work
			sessionId= sessionCookie.getValue().trim();
		// did this check as the logout currently sets the cookie value to "" instead of aging it out
		// see comment in LogingREST.java
		if (sessionId.equals("")) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return;
		}
		
		JSONObject jsonObject = authService.validateSession(sessionId);
		if (jsonObject != null) {
			String loginUser=(String) jsonObject.get("customerid");				
			request.setAttribute(LOGIN_USER, loginUser);
			chain.doFilter(req, resp);
			return;
		} else {
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return;
		}
	}
	
	// if we got here, we didn't detect the session cookie, so we need to return 404
	response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
 
開發者ID:ibmruntimes,項目名稱:acmeair-modular,代碼行數:51,代碼來源:RESTCookieSessionFilter.java

示例8: extractContextPath

import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
private String extractContextPath(HttpServletRequest request) {
  Handler[] handlers = this.getHandlers();
  String contextPath = request.getContextPath();
  for (Handler handler : handlers) {
    if (handler instanceof ServletContextHandler) {
      contextPath = ((ServletContextHandler) handler).getContextPath();
      break;
    }
  }

  if (contextPath == null || contextPath.length() == 1) {
    contextPath = "";
  }
  return contextPath;
}
 
開發者ID:ApptuitAI,項目名稱:JInsight,代碼行數:16,代碼來源:JettyRuleHelper.java

示例9: service

import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
/**
 * 複寫父類service方法,進行請求轉發
 *
 * @param request  請求
 * @param response 應答
 * @throws ServletException 異常
 * @throws IOException      異常
 */
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 項目根路徑
    String contextPath = request.getContextPath();
    // servlet訪問路徑
    String servletPath = request.getServletPath();
    // 訪問全路徑
    String requestURI = request.getRequestURI();
    // 設置編碼
    response.setCharacterEncoding("utf-8");
    // 根目錄為空的情況為,root context
    if (contextPath == null) {
        contextPath = "";
    }
    String uri = contextPath + servletPath;
    String path = requestURI.substring(contextPath.length() + servletPath.length());
    // request是否合法
    if (!isPermittedRequest(request, response)) {
        return;
    }
    //
    if ("/submitLogin".equals(path)) {
        response.getWriter().print(this.submitLogin(path, request, response));
        return;
    }
    if ("/submitLogout".equals(path)) {
        response.getWriter().print(this.submitLogout(path, request, response));
        return;
    }
    // 沒有權限直接返回
    if (!hasPermission(path, request, response)) {
        return;
    }

    if ("".equals(path)) {
        if (contextPath.equals("") || contextPath.equals("/")) {
            response.sendRedirect(servletPath + "/index.html");
        } else {
            response.sendRedirect(requestURI + "/index.html");
        }
        return;
    }
    if ("/".equals(path)) {
        response.sendRedirect("index.html");
        return;
    }

    if (path.startsWith(servicePathPrefix)) {
        LOG.debug("path:" + path);
        response.getWriter().print(this.process(path, request, response));
        return;
    }
    // 其他
    this.returnResourceFile(path, uri, response);
}
 
開發者ID:quartzweb,項目名稱:quartz-web,代碼行數:63,代碼來源:ResourceServlet.java

示例10: doHandleRequest

import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
@Override
protected ModelAndView doHandleRequest(HttpServletRequest request,
		HttpServletResponse response) throws Exception {
	Properties properties=new Properties();
       properties.setProperty("resource.loader", "file");
       properties.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
       String contextPath=request.getContextPath();
       if(!contextPath.endsWith("/")){
       	contextPath+="/";
       }
       VelocityEngine velocityEngine=new VelocityEngine(properties);
       VelocityContext context=new VelocityContext();
       StringBuffer sb=new StringBuffer();
       sb.append("\r");
       sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\""+contextPath+"dorado/res/dorado/resources/jquery.contextMenu.css\" />");
       sb.append("\r");
       sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\""+contextPath+"dorado/res/dorado/resources/jquery-ui-1.8.19.custom.css\" />");
       sb.append("\r");
       sb.append("<script type=\"text/javascript\" src=\""+contextPath+"dorado/res/dorado/scripts/jbpm4-designer-all-in-one.js\"></script>");
       sb.append("\r");
       
       String serverUrl=this.buildServerUrl(request.getScheme(),request.getServerName(),request.getServerPort());
       if(contextPath.endsWith("/")){
       	serverUrl+=contextPath.substring(0,contextPath.length()-1);
       }
       context.put("cssandscript", sb.toString());
       context.put("baseIconsDir", contextPath+"dorado/res/dorado/resources");
       context.put("serverUrl", serverUrl);
       StringWriter writer=new StringWriter();
       velocityEngine.mergeTemplate("dorado/resources/jbpm4-designer.html","utf-8", context, writer);
       response.setContentType("text/html; charset=utf-8");
       PrintWriter out=response.getWriter();
       out.write(writer.toString());
       out.flush();
       out.close();
	return null;
}
 
開發者ID:bsteker,項目名稱:bdf2,代碼行數:38,代碼來源:DesignerController.java

示例11: ActionEnter

import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
public ActionEnter ( HttpServletRequest request, String rootPath ) {
	
	this.request = request;
	this.rootPath = rootPath;
	this.actionType = request.getParameter( "action" );
	this.contextPath = request.getContextPath();
	this.configManager = ConfigManager.getInstance( this.rootPath, this.contextPath, request.getRequestURI() );
	
}
 
開發者ID:gingerjiang,項目名稱:easycms,代碼行數:10,代碼來源:ActionEnter.java

示例12: buildMapping

import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
/**
 * parse mapping
 *
 * @param request
 * @return
 */
private static String buildMapping(HttpServletRequest request) {
    String requestURI = request.getRequestURI();
    String contextPath = request.getContextPath();
    if (requestURI.length() <= contextPath.length() + 1) {
        logger.warn("buildMapping fail:" + requestURI);
        return null;
    }
    String mapping = requestURI.substring(contextPath.length() + 1).toLowerCase();
    return mapping;
}
 
開發者ID:xuxueli,項目名稱:xxl-web,代碼行數:17,代碼來源:XxlWebHandlerFactory.java

示例13: deleteCookie

import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,
        Cookie cookie) {
    if (cookie != null) {
        String path = request.getContextPath() != null ? request.getContextPath() : "/";
        if ("".equals(path)) {
            path = "/";
        }
        cookie.setPath(path);
        cookie.setValue("");
        response.addCookie(cookie);
    }
}
 
開發者ID:bridgeli,項目名稱:netty-socketio-demo,代碼行數:13,代碼來源:CookieUtils.java

示例14: service

import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //獲取請求方法
    String requestMethod = req.getMethod().toLowerCase(Locale.ENGLISH);
    //請求路徑url
    String url = req.getRequestURI();
    String contextPath = req.getContextPath();
    String requestPath = null;
    if (contextPath != null && contextPath.length() > 0) {
        requestPath = url.substring(contextPath.length());
    }
    //獲取處理處理這個請求的handler
    Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
   // System.out.println(requestMethod + "  " + requestPath);
    if (handler != null) {
        Class<?> controllerClass = handler.getControllerClass();
        Object controllerBean = BeanContainer.getBean(controllerClass.getName());
        //解析請求參數
        Param param = ParameterUtil.createParam(req);
        Object result;//請求返回對象
        Method method = handler.getMethod();//處理請求的方法
        if (param.isEmpty()) {
            result = BeanFactory.invokeMethod(controllerBean, method);
        } else {
            result = BeanFactory.invokeMethod(controllerBean, method, param);
        }
        if (result instanceof ModelAndView) {
            handleViewResult((ModelAndView) result, req, resp);
        } else {
            handleDataResult((Data) result, resp);
        }
    }
}
 
開發者ID:CFshuming,項目名稱:bfmvc,代碼行數:34,代碼來源:DispatherServlet.java

示例15: resolveUrl

import javax.servlet.http.HttpServletRequest; //導入方法依賴的package包/類
/** Utility methods
 * taken from org.apache.taglibs.standard.tag.common.core.UrlSupport
 */
public static String resolveUrl(
        String url, String context, PageContext pageContext)
throws JspException {
    // don't touch absolute URLs
    if (isAbsoluteUrl(url))
        return url;
    
    // normalize relative URLs against a context root
    HttpServletRequest request =
        (HttpServletRequest) pageContext.getRequest();
    if (context == null) {
        if (url.startsWith("/"))
            return (request.getContextPath() + url);
        else
            return url;
    } else {
        if (!context.startsWith("/") || !url.startsWith("/")) {
            throw new JspTagException(
            "In URL tags, when the \"context\" attribute is specified, values of both \"context\" and \"url\" must start with \"/\".");
        }
        if (context.equals("/")) {
            // Don't produce string starting with '//', many
            // browsers interpret this as host name, not as
            // path on same host.
            return url;
        } else {
            return (context + url);
        }
    }
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:34,代碼來源:Util.java


注:本文中的javax.servlet.http.HttpServletRequest.getContextPath方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。