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

The following are Jave code examples for showing how to use getPathInfo() 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: Equella   File: CXFHandler.java   View Source Code Vote up 6 votes
@Override
protected void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException
{
	String pathInfo = request.getPathInfo();
	Extension extension = endpointTracker.getExtension(pathInfo);
	if( extension != null )
	{
		synchronized( extension )
		{
			if( !registeredServices.contains(pathInfo) )
			{
				createService(extension, pathInfo);
				registeredServices.add(pathInfo);
			}
		}
	}
	super.handleRequest(request, response);
}
 
Example 2
Project: lazycat   File: AsyncContextImpl.java   View Source Code Vote up 6 votes
@Override
public void dispatch() {
	check();
	String path;
	String pathInfo;
	ServletRequest servletRequest = getRequest();
	if (servletRequest instanceof HttpServletRequest) {
		HttpServletRequest sr = (HttpServletRequest) servletRequest;
		path = sr.getServletPath();
		pathInfo = sr.getPathInfo();
	} else {
		path = request.getServletPath();
		pathInfo = request.getPathInfo();
	}
	if (pathInfo != null) {
		path += pathInfo;
	}
	if (this.context.getDispatchersUseEncodedPaths()) {
		path = URLEncoder.DEFAULT.encode(path, "UTF-8");
	}
	dispatch(path);
}
 
Example 3
Project: oscm   File: ManageReviewCtrl.java   View Source Code Vote up 6 votes
private void setForwardUrl(HttpServletRequest httpRequest) {
    String relativePath = "";
    if (httpRequest.getServletPath() != null) {
        relativePath += httpRequest.getServletPath();
    }
    if (httpRequest.getPathInfo() != null) {
        relativePath += httpRequest.getPathInfo();
    }
    String queryPart = getServiceDetailsQueryPart(httpRequest,
            ui.findSessionBean());
    if (queryPart != null) {
        relativePath += queryPart;
    }
    httpRequest.getSession().setAttribute(Constants.SESS_ATTR_FORWARD_URL,
            relativePath);
}
 
Example 4
Project: microprofile-jwt-auth   File: ServiceServlet.java   View Source Code Vote up 6 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Principal user = req.getUserPrincipal();
    String pathInfo = req.getPathInfo();
    System.out.printf("pathInfo=%s\n", pathInfo);

    String result = "";
    if(pathInfo.endsWith("/getSubject")) {
        System.out.printf("Calling getSubject\n");
        result = getSubject(resp);
    }
    else {
        System.out.printf("Calling getPrincipalClass\n");
        result = getPrincipalClass(user);
    }
    resp.getWriter().write(result);
}
 
Example 5
Project: Equella   File: AbstractIdPathServlet.java   View Source Code Vote up 6 votes
@Override
protected final void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
	IOException
{
	String path = request.getPathInfo();
	int i = path.indexOf('/', 1);
	if( i < 0 )
	{
		throw new NotFoundException(path, true);
	}

	if( path.startsWith("/") )
	{
		path = path.substring(1);
	}

	int firstPart = path.indexOf('/');
	if( firstPart < 0 )
	{
		throw new NotFoundException(path, true);
	}

	service(request, response, path.substring(0, firstPart), path.substring(firstPart + 1));
}
 
Example 6
Project: webhook-step   File: WebhookRootAction.java   View Source Code Vote up 5 votes
@Override
public boolean process(HttpServletRequest req, HttpServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    String pathInfo = req.getPathInfo();
    if (pathInfo != null && pathInfo.startsWith("/webhook-step/")) {
        chain.doFilter(req, resp);
        return true;
    }

    return false;
}
 
Example 7
Project: Alpine   File: HstsFilter.java   View Source Code Vote up 5 votes
@Override
public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain)
        throws ServletException, IOException {

    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) resp;

    if (request.isSecure()) {
        if (includeSubdomains) {
            response.setHeader("Strict-Transport-Security", "max-age=" + maxAge + "; includeSubDomains");
        } else {
            response.setHeader("Strict-Transport-Security", "max-age=" + maxAge + ";");
        }
    } else {
        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        final StringBuilder sb = new StringBuilder();
        sb.append("https://").append(request.getServerName());

        if (httpsPort != DEFAULT_HTTPS_PORT) {
            sb.append(":").append(httpsPort);
        }
        if (request.getContextPath() != null) {
            sb.append(request.getContextPath());
        }
        if (request.getServletPath() != null) {
            sb.append(request.getServletPath());
        }
        if (request.getPathInfo() != null) {
            sb.append(request.getPathInfo());
        }
        if (request.getQueryString() != null && request.getQueryString().length() > 0) {
            sb.append("?").append(request.getQueryString());
        }
        response.setHeader("Location", sb.toString());
        return;
    }
    chain.doFilter(request, response);
}
 
Example 8
Project: apache-tomcat-7.0.73-with-comment   File: TestRestCsrfPreventionFilter2.java   View Source Code Vote up 5 votes
private String getRequestedPath(HttpServletRequest request) {
    String path = request.getServletPath();
    if (request.getPathInfo() != null) {
        path = path + request.getPathInfo();
    }
    return path;
}
 
Example 9
Project: personium-core   File: BoxResource.java   View Source Code Vote up 5 votes
/**
 * Constructor.
 * @param cell CELL Object
 * @param boxName Box Name
 * @param cellRsCmp cellRsCmp
 * @param accessContext AccessContextオブジェクト
 * @param request HTTPリクエスト
 * @param jaxRsRequest JAX-RS用HTTPリクエスト
 */
public BoxResource(final Cell cell, final String boxName, final AccessContext accessContext,
        final CellRsCmp cellRsCmp, final HttpServletRequest request, Request jaxRsRequest) {
    // 親はなし。パス名としてとりあえずboxNameをいれておく。
    this.cell = cell;
    this.boxName = boxName;
    // this.path= path;
    this.accessContext = accessContext;

    // Boxの存在確認
    // 本クラスではBoxが存在していることを前提としているため、Boxがない場合はエラーとする。
    // ただし、boxインストールではBoxがないことを前提としているため、以下の条件に合致する場合は処理を継続する。
    // -HTTPメソッドが MKCOL である。かつ、
    // -PathInfoが インストール先Box名 で終了している。
    // (CollectionへのMKCOLの場合があるため、boxインストールであることを確認する)
    this.box = this.cell.getBoxForName(boxName);
    // boxインストールではCellレベルで動作させる必要がある。
    this.cellRsCmp = cellRsCmp;
    if (this.box != null) {
        //BoxCmp is necessary only if this Box exists
        BoxCmp davCmp = ModelFactory.boxCmp(this.box);
        this.boxRsCmp = new BoxRsCmp(cellRsCmp, davCmp, this.accessContext, this.box);
    } else {
        //This box does not exist.
        String reqPathInfo = request.getPathInfo();
        if (!reqPathInfo.endsWith("/")) {
            reqPathInfo += "/";
        }
        String pathForBox = boxName;
        if (!pathForBox.endsWith("/")) {
            pathForBox += "/";
        }
        // Unless the HTTP method is MKCOL, respond with 404.
        if (!("MKCOL".equals(jaxRsRequest.getMethod()) && reqPathInfo.endsWith(pathForBox))) {
            throw PersoniumCoreException.Dav.BOX_NOT_FOUND.params(this.cell.getUrl() + boxName);
        }
    }

}
 
Example 10
Project: febit   File: ServletUtil.java   View Source Code Vote up 5 votes
public static String getRequestPath(HttpServletRequest request) {
    String path = getServletPath(request);
    if (path == null || path.isEmpty()) {
        path = request.getPathInfo();
    }
    return path;
}
 
Example 11
Project: lams   File: UrlPathHelper.java   View Source Code Vote up 5 votes
/**
 * Return the path within the servlet mapping for the given request,
 * i.e. the part of the request's URL beyond the part that called the servlet,
 * or "" if the whole URL has been used to identify the servlet.
 * <p>Detects include request URL if called within a RequestDispatcher include.
 * <p>E.g.: servlet mapping = "/test/*"; request URI = "/test/a" -> "/a".
 * <p>E.g.: servlet mapping = "/test"; request URI = "/test" -> "".
 * <p>E.g.: servlet mapping = "/*.test"; request URI = "/a.test" -> "".
 * @param request current HTTP request
 * @return the path within the servlet mapping, or ""
 */
public String getPathWithinServletMapping(HttpServletRequest request) {
	String pathWithinApp = getPathWithinApplication(request);
	String servletPath = getServletPath(request);
	String path = getRemainingPath(pathWithinApp, servletPath, false);
	if (path != null) {
		// Normal case: URI contains servlet path.
		return path;
	}
	else {
		// Special case: URI is different from servlet path.
		String pathInfo = request.getPathInfo();
		if (pathInfo != null) {
			// Use path info if available. Indicates index page within a servlet mapping?
			// e.g. with index page: URI="/", servletPath="/index.html"
			return pathInfo;
		}
		if (!this.urlDecode) {
			// No path info... (not mapped by prefix, nor by extension, nor "/*")
			// For the default servlet mapping (i.e. "/"), urlDecode=false can
			// cause issues since getServletPath() returns a decoded path.
			// If decoding pathWithinApp yields a match just use pathWithinApp.
			path = getRemainingPath(decodeInternal(request, pathWithinApp), servletPath, false);
			if (path != null) {
				return pathWithinApp;
			}
		}
		// Otherwise, use the full servlet path.
		return servletPath;
	}
}
 
Example 12
Project: validator-web   File: UrlProcessor.java   View Source Code Vote up 5 votes
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null || pathInfo.length() == 0 || "/".equals(pathInfo)) {
            notFoundHandler.handle(request, response);
        } else {
            // Loop through all the known URLs
            for (Map.Entry<String, Handler> entry : urlMapping.entrySet()) {
                String url = entry.getKey();
                // If this URL matches, call the handler
                if (pathInfo.startsWith(url)) {
                    Handler handler = entry.getValue();
                    handler.handle(request, response);
                    return;
                }
            }
            notFoundHandler.handle(request, response);
        }
    } catch (SecurityException se) {
        // We don't want to give the client any information about the security error, handle it with a 404.
        log.error("Security Exception: ", se);
        notFoundHandler.handle(request, response);
    } catch (Exception e) {
        exceptionHandler.setException(e);
        exceptionHandler.handle(request, response);
    }
}
 
Example 13
Project: apache-tomcat-7.0.73-with-comment   File: HTMLHostManagerServlet.java   View Source Code Vote up 5 votes
/**
 * Process a GET request for the specified resource.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet-specified error occurs
 */
@Override
public void doGet(HttpServletRequest request,
                  HttpServletResponse response)
    throws IOException, ServletException {

    StringManager smClient = StringManager.getManager(
            Constants.Package, request.getLocales());

    // Identify the request parameters that we need
    String command = request.getPathInfo();

    // Prepare our output writer to generate the response message
    response.setContentType("text/html; charset=" + Constants.CHARSET);

    String message = "";
    // Process the requested command
    if (command == null) {
        // No command == list
    } else if (command.equals("/list")) {
        // Nothing to do - always generate list
    } else if (command.equals("/add") || command.equals("/remove") ||
            command.equals("/start") || command.equals("/stop")) {
        message = smClient.getString(
                "hostManagerServlet.postCommand", command);
    } else {
        message = smClient.getString(
                "hostManagerServlet.unknownCommand", command);
    }

    list(request, response, message, smClient);
}
 
Example 14
Project: apache-tomcat-7.0.73-with-comment   File: HTMLHostManagerServlet.java   View Source Code Vote up 5 votes
/**
 * Process a POST request for the specified resource.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet-specified error occurs
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    StringManager smClient = StringManager.getManager(
            Constants.Package, request.getLocales());

    // Identify the request parameters that we need
    String command = request.getPathInfo();

    String name = request.getParameter("name");
 
    // Prepare our output writer to generate the response message
    response.setContentType("text/html; charset=" + Constants.CHARSET);

    String message = "";
    
    // Process the requested command
    if (command == null) {
        // No command == list
    } else if (command.equals("/add")) {
        message = add(request, name, smClient);
    } else if (command.equals("/remove")) {
        message = remove(name, smClient);
    } else if (command.equals("/start")) {
        message = start(name, smClient);
    } else if (command.equals("/stop")) {
        message = stop(name, smClient);
    } else {
        //Try GET
        doGet(request, response);
    }

    list(request, response, message, smClient);
}
 
Example 15
Project: lazycat   File: WsFilter.java   View Source Code Vote up 5 votes
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {

	// This filter only needs to handle WebSocket upgrade requests
	if (!sc.areEndpointsRegistered() || !UpgradeUtil.isWebSocketUpgradeRequest(request, response)) {
		chain.doFilter(request, response);
		return;
	}

	// HTTP request with an upgrade header for WebSocket present
	HttpServletRequest req = (HttpServletRequest) request;
	HttpServletResponse resp = (HttpServletResponse) response;

	// Check to see if this WebSocket implementation has a matching mapping
	String path;
	String pathInfo = req.getPathInfo();
	if (pathInfo == null) {
		path = req.getServletPath();
	} else {
		path = req.getServletPath() + pathInfo;
	}
	WsMappingResult mappingResult = sc.findMapping(path);

	if (mappingResult == null) {
		// No endpoint registered for the requested path. Let the
		// application handle it (it might redirect or forward for example)
		chain.doFilter(request, response);
		return;
	}

	UpgradeUtil.doUpgrade(sc, req, resp, mappingResult.getConfig(), mappingResult.getPathParams());
}
 
Example 16
Project: careconnect-reference-implementation   File: OAuth2Interceptor.java   View Source Code Vote up 5 votes
@Override
public boolean incomingRequestPreProcessed(HttpServletRequest theRequest, HttpServletResponse theResponse) {

    String resourcePath = theRequest.getPathInfo();
    logger.info("Accessing Resource" + resourcePath);
    if (excludedPaths.contains(resourcePath)){
        logger.info("Accessing unprotected resource" + resourcePath);
        return true;
    }

    String authorizationHeader = theRequest.getHeader(HttpHeaders.AUTHORIZATION);
    if (authorizationHeader == null){
        logger.warn("OAuth2 Authentication failure.  No OAuth Token supplied in Authorization Header on Request.");
        throw new AuthenticationException("Unauthorised access to protected resource");
    }
    OAuthToken oAuthToken = OAuthTokenUtil.parseOAuthToken(authorizationHeader);

    // Check that the OAuth Token has not expired
    if (oAuthToken.isExpired()){
        logger.warn("OAuth2 Authentication failure due to expired token");
        throw new AuthenticationException("OAuth2 Authentication Token has expired.");
    }

    // Check that the Scopes on the Token allow access to the specified resource
    String resourceName = extractResourceName(resourcePath);
    if (!allowedAccess(resourceName, theRequest.getMethod(), oAuthToken)){
        logger.warn("OAuth2 Authentication failed due to insufficient access rights: ");
        throw new ForbiddenOperationException(String.format("Insufficient Access Rights to access %s.", resourceName));
    }

    logger.debug("Authenticated Access to " + resourcePath);
    return true;
}
 
Example 17
Project: tomcat7   File: HTMLHostManagerServlet.java   View Source Code Vote up 5 votes
/**
 * Process a POST request for the specified resource.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet-specified error occurs
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    StringManager smClient = StringManager.getManager(
            Constants.Package, request.getLocales());

    // Identify the request parameters that we need
    String command = request.getPathInfo();

    String name = request.getParameter("name");
 
    // Prepare our output writer to generate the response message
    response.setContentType("text/html; charset=" + Constants.CHARSET);

    String message = "";
    
    // Process the requested command
    if (command == null) {
        // No command == list
    } else if (command.equals("/add")) {
        message = add(request, name, smClient);
    } else if (command.equals("/remove")) {
        message = remove(name, smClient);
    } else if (command.equals("/start")) {
        message = start(name, smClient);
    } else if (command.equals("/stop")) {
        message = stop(name, smClient);
    } else {
        //Try GET
        doGet(request, response);
    }

    list(request, response, message, smClient);
}
 
Example 18
Project: Equella   File: ThumbInProgressServlet.java   View Source Code Vote up 4 votes
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
	IOException
{
	String path = request.getPathInfo();
	if( path.startsWith("/") )
	{
		path = Utils.safeSubstring(path, 1);
	}

	final int i;
	if( STANDARD.equals(path) )
	{
		i = 0;
	}
	else if( GALLERY_THUMBNAIL.equals(path) )
	{
		i = 1;
	}
	else
	{
		response.sendError(404);
		return;
	}

	final String filename = PLACEHOLDERS[i];
	final URL res = new URL(ThumbInProgressServlet.class.getClassLoader().getResource("web/images/"), filename);
	final File file = IoUtil.url2file(res);

	ContentStream stream;
	if( file != null )
	{
		stream = new FileContentStream(file, filename, "image/jpeg");
	}
	else
	{
		stream = new URLContentStream(res, filename, "image/jpeg");
	}
	stream.setCacheControl("max-age=31556926");
	contentStreamWriter.outputStream(request, response, stream);
}
 
Example 19
Project: tomcat7   File: CGIServlet.java   View Source Code Vote up 4 votes
/**
 * Uses the HttpServletRequest to set most CGI variables
 *
 * @param  req   HttpServletRequest for information provided by
 *               the Servlet API
 * @throws UnsupportedEncodingException Unknown encoding
 */
protected void setupFromRequest(HttpServletRequest req)
        throws UnsupportedEncodingException {

    boolean isIncluded = false;

    // Look to see if this request is an include
    if (req.getAttribute(
            RequestDispatcher.INCLUDE_REQUEST_URI) != null) {
        isIncluded = true;
    }
    if (isIncluded) {
        this.contextPath = (String) req.getAttribute(
                RequestDispatcher.INCLUDE_CONTEXT_PATH);
        this.servletPath = (String) req.getAttribute(
                RequestDispatcher.INCLUDE_SERVLET_PATH);
        this.pathInfo = (String) req.getAttribute(
                RequestDispatcher.INCLUDE_PATH_INFO);
    } else {
        this.contextPath = req.getContextPath();
        this.servletPath = req.getServletPath();
        this.pathInfo = req.getPathInfo();
    }
    // If getPathInfo() returns null, must be using extension mapping
    // In this case, pathInfo should be same as servletPath
    if (this.pathInfo == null) {
        this.pathInfo = this.servletPath;
    }

    // If the request method is GET, POST or HEAD and the query string
    // does not contain an unencoded "=" this is an indexed query.
    // The parsed query string becomes the command line parameters
    // for the cgi command.
    if (req.getMethod().equals("GET")
        || req.getMethod().equals("POST")
        || req.getMethod().equals("HEAD")) {
        String qs;
        if (isIncluded) {
            qs = (String) req.getAttribute(
                    RequestDispatcher.INCLUDE_QUERY_STRING);
        } else {
            qs = req.getQueryString();
        }
        if (qs != null && qs.indexOf('=') == -1) {
            StringTokenizer qsTokens = new StringTokenizer(qs, "+");
            while ( qsTokens.hasMoreTokens() ) {
                cmdLineParameters.add(URLDecoder.decode(qsTokens.nextToken(),
                                      parameterEncoding));
            }
        }
    }
}
 
Example 20
Project: jerrydog   File: CGIServlet.java   View Source Code Vote up 2 votes
/**
 * Uses the HttpServletRequest to set most CGI variables
 *
 * @param  req   HttpServletRequest for information provided by
 *               the Servlet API
 */
protected void setupFromRequest(HttpServletRequest req) {
    this.contextPath = req.getContextPath();
    this.pathInfo = req.getPathInfo();
    this.servletPath = req.getServletPath();
}