Request get path java
Best Java code snippets using javax.servlet.http.HttpServletRequest.getPathInfo (Showing top 20 results out of 9,180)
Refine search
private String getRequestPath(HttpServletRequest request) String url = request.getServletPath(); if (request.getPathInfo() != null) url += request.getPathInfo(); > return url; >
/** */ public String getPath() String path = request.getContextPath(); if (request.getPathInfo() != null) path += request.getPathInfo(); > if (path.charAt(0) == '/') path = path.substring(1); > return path; >
private RequestUrlParts getRequestPath(HttpServletRequest request) String url = request.getServletPath(); if (request.getPathInfo() != null) url += request.getPathInfo(); > url = url.toLowerCase(); String queryString = request.getQueryString(); return new RequestUrlParts(url, queryString); >
public static String getURL(HttpServletRequest req) String scheme = req.getScheme(); // http String serverName = req.getServerName(); // hostname.com int serverPort = req.getServerPort(); // 80 String contextPath = req.getContextPath(); // /mywebapp String servletPath = req.getServletPath(); // /servlet/MyServlet String pathInfo = req.getPathInfo(); // /a/b;c=123 String queryString = req.getQueryString(); // d=789 // Reconstruct original requesting URL StringBuilder url = new StringBuilder(); url.append(scheme).append("://").append(serverName); if (serverPort != 80 && serverPort != 443) url.append(":").append(serverPort); > url.append(contextPath).append(servletPath); if (pathInfo != null) url.append(pathInfo); > if (queryString != null) url.append("?").append(queryString); > return url.toString(); >
final String requestPath = ( httpServletRequest.getContextPath() + httpServletRequest.getServletPath() + httpServletRequest.getPathInfo() ).toLowerCase();
@Test public void testNotFound() throws ServletException, IOException StaticContentServlet servlet = new StaticContentServlet(); ServletContext context = mock(ServletContext.class); when(context.getServletContextName()).thenReturn("foo"); when(context.getMimeType(anyString())).thenReturn("image/jpeg"); ServletConfig config = mock(ServletConfig.class); when(config.getInitParameterNames()).thenReturn(Collections.enumeration(Arrays.asList("root"))); when(config.getInitParameter("root")).thenReturn(getFileSystemRoot()); when(config.getServletContext()).thenReturn(context); servlet.init(config); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getMethod()).thenReturn("GET"); when(request.getPathInfo()).thenReturn("/missing.jpg"); when(request.getRequestURI()).thenReturn("/foo/missing.jpg"); when(request.getContextPath()).thenReturn("/foo"); HttpServletResponse response = mock(HttpServletResponse.class); servlet.service(request, response); verify(response).sendError(HttpServletResponse.SC_NOT_FOUND, "/foo/missing.jpg"); >
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException if (Strings.isNullOrEmpty(req.getPathInfo())) try (final PrintWriter output = resp.getWriter()) resp.setContentType(CONTENT_TYPE); getTasks().stream() .map(Task::getName) .sorted() .forEach(output::println); > > else if (tasks.containsKey(req.getPathInfo())) resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); > else resp.sendError(HttpServletResponse.SC_NOT_FOUND); > >
HttpServletResponse resp) throws ServletException, IOException try final StringBuilder builder = new StringBuilder(req.getServletPath()); if (req.getPathInfo() != null) builder.append(req.getPathInfo()); resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; resp.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; ranges = parseRangeHeader(rangeHeader, resourceLength); > catch (NumberFormatException e) resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; resp.setHeader(ETAG, cachedAsset.getETag()); final String mediaType = Optional.ofNullable(req.getServletContext().getMimeType(req.getRequestURI())) .orElse(DEFAULT_MEDIA_TYPE); if (mediaType.startsWith("video") || mediaType.startsWith("audio") || usingRanges)
throws IOException req.setCharacterEncoding("utf-8"); String file = req.getPathInfo(); if (file == null) resp.sendRedirect(req.getRequestURI() + "/"); return; > else if (file.startsWith("/")) while (en.hasMoreElements()) String name = en.nextElement().toString(); String value = req.getAttribute(name).toString(); attributes.put(name, value); resp.sendError(HttpServletResponse.SC_NOT_FOUND); bytes = ("File not found: " + file).getBytes(StandardCharsets.UTF_8); > else
/** * Gets a resource from a servlet request * * @param request the servlet request * @return the resource or null if not found * @throws java.net.MalformedURLException thrown when malformed URL. */ public AbstractFileResolvingResource getResource(HttpServletRequest request) throws MalformedURLException String servletPath; String pathInfo; boolean included = request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null; if (included) servletPath = (String) request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH); pathInfo = (String) request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO); if (servletPath == null && pathInfo == null) servletPath = request.getServletPath(); pathInfo = request.getPathInfo(); > > else servletPath = request.getServletPath(); pathInfo = request.getPathInfo(); > String pathInContext = addPaths(servletPath, pathInfo); return getResource(pathInContext); >
@Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException String absoluteDiskPath = getServletContext().getRealPath(req.getPathInfo()); File requestedFile = new File(absoluteDiskPath); // async-profiler version 1.4 writes 'Started [cpu] profiling' to output file when profiler is running which // gets replaced by final output. If final output is not ready yet, the file size will be if (requestedFile.length() 100) LOG.info("<> is incomplete. Sending auto-refresh header..", requestedFile); resp.setHeader("Refresh", "2," + req.getRequestURI()); resp.getWriter().write("This page will auto-refresh every 2 second until output file is ready.."); > else super.doGet(req, resp); > > >
out.println("\t" + request.getPathInfo()); out.println("\t" + request.getQueryString());
HttpServletResponse response) throws ServletException, IOException if (!DAO.writeDump) response.sendError(HttpServletResponse.SC_FORBIDDEN, "Dump generation is disabled on this peer"); String path = request.getPathInfo(); final long now = System.currentTimeMillis(); response.sendError(404, request.getContextPath() + " " + limitedMessage); return; File dump = ownDumps.size() == 0 ? null : new File(ownDumps.iterator().next().getParentFile(), path); if (dump == null || !dump.exists()) response.sendError(404, request.getContextPath() + " not available");
String path = request.getPathInfo(); Log.debug("WebDAVLiteServlet: PUT with path = "+path); if (request.getContentLength() 0) response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; if (overwriteFile) response.setStatus(HttpServletResponse.SC_NO_CONTENT); response.setHeader("Location", request.getRequestURI()); response.setHeader("Location", request.getRequestURI());
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException Object obj = request.getAttribute(ServletController.AUTH_SERVICE_LIST); boolean isAuthServiceList = false; if (obj != null) String authServiceListRealm = (String)request.getAttribute(ServletController.AUTH_SERVICE_LIST_REALM); ServiceListJAASAuthenticator authenticator = new ServiceListJAASAuthenticator(); authenticator.setRealm(authServiceListRealm); String servletPath = request.getServletPath(); if (servletPath != null) styleSheetPath += servletPath; String pathInfo = request.getPathInfo(); if (pathInfo != null) styleSheetPath += pathInfo; Object basePath = request.getAttribute(Message.BASE_PATH); serviceListWriter.writeServiceList(response.getWriter(), basePath == null ? null : basePath.toString(),
String path = req.getServletPath(); if (req.getPathInfo() != null) path += req.getPathInfo(); resp.sendError(404,e.toString()); resp.sendError(500);
How do I get servlet request URL information?
In the code example below we will extract information regarding the HTTP (Hypertext Transport Protocol) from the request object ( HttpServletRequest ). We will extract the protocol used (http / https), server name and its assigned port number. We will also read our application context path, servlet path, path info and the query string. If we combine all the previously mentioned information we will get something equals to the value returned by request.getRequestURL() method.
Let’s check the code snippet below to see what method of the HttpServletRequest class that we can call to get the information regarding the HTTP request object that we can collect.
package org.kodejava.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet(urlPatterns = "/url-info") public class ServletUrlInformation extends HttpServlet < @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < doPost(request, response); >@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < // Getting servlet request URL String url = request.getRequestURL().toString(); // Getting servlet request query string. String queryString = request.getQueryString(); // Getting request information without the hostname. String uri = request.getRequestURI(); // Below we extract information about the request object path // information. String scheme = request.getScheme(); String serverName = request.getServerName(); int portNumber = request.getServerPort(); String contextPath = request.getContextPath(); String servletPath = request.getServletPath(); String pathInfo = request.getPathInfo(); String query = request.getQueryString(); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.print("Url: " + url + "
"); pw.print("Uri: " + uri + "
"); pw.print("Scheme: " + scheme + "
"); pw.print("Server Name: " + serverName + "
"); pw.print("Port: " + portNumber + "
"); pw.print("Context Path: " + contextPath + "
"); pw.print("Servlet Path: " + servletPath + "
"); pw.print("Path Info: " + pathInfo + "
"); pw.print("Query: " + query); > >
When you access this servlet using the following url http://localhost:8080/url-info?x=1&y=1, you’ll get the following output in your browser:
Url: http://localhost:8080/url-info Uri: /url-info Scheme: http Server Name: localhost Port: 8080 Context Path: Servlet Path: /url-info Path Info: null Query: x=1&y=1
Maven dependencies
javax.servlet javax.servlet-api 4.0.1