Java Code Examples for javax.servlet.http.HttpServletRequest.getContextPath()

The following are Jave code examples for showing how to use getContextPath() of the javax.servlet.http.HttpServletRequest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ramus   File: JNLPHTTPServlet.java   View Source Code Vote up 6 votes
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();
    }

}
 
Example 2
Project: lams   File: ApplicationHttpRequest.java   View Source Code Vote up 6 votes
/**
 * 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();

}
 
Example 3
Project: https-github.com-apache-zookeeper   File: ZNodeResource.java   View Source Code Vote up 6 votes
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);
}
 
Example 4
Project: bdf2   File: ControllerFilter.java   View Source Code Vote up 6 votes
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;
}
 
Example 5
Project: pub-service   File: RequestUtil.java   View Source Code Vote up 6 votes
/**
 * 根据 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;
}
 
Example 6
Project: netty-socketio-demo   File: CookieUtils.java   View Source Code Vote up 5 votes
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);
}
 
Example 7
Project: acmeair-modular   File: RESTCookieSessionFilter.java   View Source Code Vote up 5 votes
@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);
}
 
Example 8
Project: JInsight   File: JettyRuleHelper.java   View Source Code Vote up 5 votes
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;
}
 
Example 9
Project: quartz-web   File: ResourceServlet.java   View Source Code Vote up 5 votes
/**
 * 复写父类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);
}
 
Example 10
Project: bdf2   File: DesignerController.java   View Source Code Vote up 5 votes
@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;
}
 
Example 11
Project: easycms   File: ActionEnter.java   View Source Code Vote up 5 votes
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() );
	
}
 
Example 12
Project: xxl-web   File: XxlWebHandlerFactory.java   View Source Code Vote up 5 votes
/**
 * 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;
}
 
Example 13
Project: netty-socketio-demo   File: CookieUtils.java   View Source Code Vote up 5 votes
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);
    }
}
 
Example 14
Project: bfmvc   File: DispatherServlet.java   View Source Code Vote up 5 votes
@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);
        }
    }
}
 
Example 15
Project: lams   File: Util.java   View Source Code Vote up 5 votes
/** 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);
        }
    }
}
 
Example 16
Project: jerrydog   File: AuthenticatorBase.java   View Source Code Vote up 5 votes
/**
 * Return the SecurityConstraint configured to guard the request URI for
 * this request, or <code>null</code> if there is no such constraint.
 *
 * @param request Request we are processing
 */
protected SecurityConstraint findConstraint(HttpRequest request) {

    // Are there any defined security constraints?
    SecurityConstraint constraints[] = context.findConstraints();
    if ((constraints == null) || (constraints.length == 0)) {
        if (debug >= 2)
            log("  No applicable constraints defined");
        return (null);
    }

    // Check each defined security constraint
    HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
    String uri = request.getDecodedRequestURI();
    String contextPath = hreq.getContextPath();
    if (contextPath.length() > 0)
        uri = uri.substring(contextPath.length());
    String method = hreq.getMethod();
    for (int i = 0; i < constraints.length; i++) {
        if (debug >= 2)
            log("  Checking constraint '" + constraints[i] +
                "' against " + method + " " + uri + " --> " +
                constraints[i].included(uri, method));
        if (constraints[i].included(uri, method))
            return (constraints[i]);
    }

    // No applicable security constraint was found
    if (debug >= 2)
        log("  No applicable constraint located");
    return (null);

}
 
Example 17
Project: acmeair   File: RESTCookieSessionFilter.java   View Source Code Vote up 4 votes
private void doFilter(RequestContext context) throws IOException, ServletException {
	HttpServletRequest request = context.getRequest();

	String path = request.getContextPath() + request.getServletPath();
	if (request.getPathInfo() != null) {
		path = path + request.getPathInfo();
	}
	logger.debug("Get the request path {}", path);
	
	
	if (path.endsWith(LOGIN_PATH) || path.endsWith(LOGOUT_PATH) || path.endsWith(LOADDB_PATH) ||
			path.contains(CONFIG_PATH) || path.contains(LOADER_PATH)) {
		// if logging in, logging out, lookup configuration, or loading the database , let the request flow
		return;
	}
	
	Cookie cookies[] = request.getCookies();
	Cookie sessionCookie = null;
	if (cookies != null) {
		for (Cookie c : cookies) {
			if (c.getName().equals(CustomerSession.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("")) {
			logger.warn("Session id is empty");
			setFailedRequest(HttpServletResponse.SC_FORBIDDEN);
			return;
		}
		// Need the URLDecoder so that I can get @ not %40
		CustomerSession cs = getCustomerSession(sessionId);
		if (cs != null) {
			context.addZuulRequestHeader(LOGIN_USER, cs.getCustomerid());
			logger.info("Customer {} validated with session id {}", cs.getCustomerid(), sessionId);
			return;
		}
		else {
			logger.warn("No customer session found with session id {}", sessionId);
			setFailedRequest(HttpServletResponse.SC_FORBIDDEN);
			return;
		}
	}

	logger.warn("No session cookie provided");
	// if we got here, we didn't detect the session cookie, so we need to return 404
	setFailedRequest(HttpServletResponse.SC_FORBIDDEN);

}
 
Example 18
Project: bdf2   File: JasperreportsDisplayController.java   View Source Code Vote up 4 votes
@Override
protected ModelAndView doHandleRequest(HttpServletRequest req,HttpServletResponse res) throws Exception {
	String reportFile=req.getParameter(IExporter.REPORT_FILE_PARAMETER_KEY);
	if(StringUtils.isEmpty(reportFile)){
		throw new RuntimeException("Report file can not be null!");
	}
	String fileSource=req.getParameter(IExporter.FILE_SOURCE_PARAMETER_KEY);
	if(StringUtils.isEmpty(reportFile)){
		throw new RuntimeException("File source can not be null!");
	}
	String dt=req.getParameter(IExporter.DATASOURCE_TYPE_PARAMETER_KEY);
	String dataSourceProvider=req.getParameter(IExporter.DATASOURCE_PROVIDER_PARAMETER_KEY);
	String reportParameters=req.getParameter(IExporter.REPORT_PARAMETERS_PARAMETER_KEY);
	String cache=req.getParameter(IExporter.CACHE_PARAMETER_KEY);
	String exportFileType=req.getParameter(IExporter.EXPORT_FILE_TYPE_PARAMETER_KEY);
	StringBuffer sb=new StringBuffer();
	String url=buildUrl(req)+req.getContextPath();
	if(url.endsWith("/")){
		sb.append(url+"dorado/bdf2/jasperreports/report.exporter?");			
	}else{
		sb.append(url+"/dorado/bdf2/jasperreports/report.exporter?");						
	}
	sb.append(IExporter.REPORT_FILE_PARAMETER_KEY+"="+reportFile);
	sb.append("&"+IExporter.FILE_SOURCE_PARAMETER_KEY+"="+fileSource);
	if(dt!=null){
		sb.append("&"+IExporter.DATASOURCE_TYPE_PARAMETER_KEY+"="+dt);			
	}
	if(dataSourceProvider!=null){
		sb.append("&"+IExporter.DATASOURCE_PROVIDER_PARAMETER_KEY+"="+dataSourceProvider);			
	}
	if(reportParameters!=null){
		sb.append("&"+IExporter.REPORT_PARAMETERS_PARAMETER_KEY+"="+reportParameters);			
	}
	if(cache!=null){
		sb.append("&"+IExporter.CACHE_PARAMETER_KEY+"="+cache);			
	}
	if(exportFileType!=null){
		sb.append("&"+IExporter.EXPORT_FILE_TYPE_PARAMETER_KEY+"="+exportFileType);			
	}
	String targetUrl=sb.toString();
	res.setContentType("text/html; charset=utf-8");
	String baseUrl=req.getContextPath()+"/dorado/res/dorado/resources/jasperreportsviewer/";
	PrintWriter pw=res.getWriter();
	pw.write(this.buildContent(baseUrl, targetUrl));
	pw.flush();
	pw.close();
	return null;
}
 
Example 19
Project: oscm   File: AdmServer.java   View Source Code Vote up 4 votes
/**
 * Create a new server for each request so that we can store some data in
 * the member variables of the rule while the request is processed.
 * 
 * @see net.sf.j2ep.model.ServerContainer#getServer(javax.servlet.http.HttpServletRequest)
 */
public Server getServer(HttpServletRequest request) {
    Server server = (Server) request.getAttribute("proxyServer");
    if (server != null) {
        return server;
    }

    String contextPath = request.getContextPath();
    String uri = request.getRequestURI().substring(contextPath.length());
    String domainName = null;
    String path = "";
    Matcher matcher = AdmRule.getMatchPattern().matcher(uri);
    if (matcher.matches()) {
        String key = matcher.group(1);
        if (key == null || key.length() <= 1) {
            return null;
        }
        // remove the leading slash
        key = key.substring(1);
        Map<?, ?> map = (Map<?, ?>) request.getSession().getAttribute(
                Constants.SESS_ATTR_ACTIVE_SUB_MAP);
        String url = null;
        if (map != null) {
            VOSubscription sub = (VOSubscription) map.get(key);
            if (sub != null) {
                url = sub.getServiceBaseURL();
            }
        }
        if (url == null) {
            return null;
        }
        // ignore the http:// or https://
        int begin = url.indexOf("://");
        if (begin < 0) {
            return null;
        }
        begin += 3; // the length of "://"
        int end = url.indexOf("/", begin);
        if (end < 0) {
            domainName = url.substring(begin);
            path = "";
        } else {
            domainName = url.substring(begin, end);
            path = url.substring(end);

        }
    }

    AdmServer admServer = new AdmServer();
    admServer.setDomainName(domainName);
    admServer.setPath("");
    AdmRule rule = new AdmRule();
    rule.setRewriteTo(path + "$2"); // $1 is the subscription id
    rule.setRevertPattern(Pattern.compile("^" + path + "(/.*)?"));
    admServer.setRule(rule);
    return admServer;
}
 
Example 20
Project: lazycat   File: DefaultServlet.java   View Source Code Vote up 2 votes
/**
 * Determines the appropriate path to prepend resources with when generating
 * directory listings. Depending on the behaviour of
 * {@link #getRelativePath(HttpServletRequest)} this will change.
 * 
 * @param request
 *            the request to determine the path for
 * @return the prefix to apply to all resources in the listing.
 */
protected String getPathPrefix(final HttpServletRequest request) {
	return request.getContextPath();
}