下面列出了javax.servlet.http.HttpServletRequest#getPathInfo() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void handle(String target, Request baseRequest, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html;charset=utf-8");
//System.out.println("In handler: " + request.getContentLength());
byte[] bytes = new byte[1024];
InputStream in = request.getInputStream();
while (in.read(bytes) > -1) {
//nothing
}
faultRequestPath = request.getPathInfo();
if ("/faultTo".equals(faultRequestPath)) {
response.setStatus(HttpServletResponse.SC_ACCEPTED);
} else {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
PrintWriter writer = response.getWriter();
writer.println("Received");
writer.close();
baseRequest.setHandled(true);
}
@Override
public void service(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
final String change = getChangeServerPath();
if (change != null && change.equals(req.getPathInfo())) {
try {
changeServer(req, resp);
} catch (QueryResultHandlerException e) {
throw new IOException(e);
}
} else {
final WorkbenchServlet servlet = findWorkbenchServlet(req, resp);
if (servlet == null) {
// Redirect to change-server-path
final StringBuilder uri = new StringBuilder(req.getRequestURI());
if (req.getPathInfo() != null) {
uri.setLength(uri.length() - req.getPathInfo().length());
}
resp.sendRedirect(uri.append(getChangeServerPath()).toString());
} else {
servlet.service(req, resp);
}
}
}
@GET
@Path("/getImage")
@Produces(MediaType.APPLICATION_JSON)
@UserConstraint(functionalities = { SpagoBIConstants.IMAGES_MANAGEMENT })
public void getImage(@Context HttpServletRequest req, @Context HttpServletResponse resp) {
try {
IImagesDAO dao = DAOFactory.getImagesDAO();
IEngUserProfile profile = (IEngUserProfile) req.getSession().getAttribute(IEngUserProfile.ENG_USER_PROFILE);
dao.setUserProfile(profile);
Integer id = Util.getNumberOrNull(req.getParameter("IMAGES_ID"));
String preview = req.getParameter("preview");
SbiImages imageDB = dao.loadImage(id);
String contentType = "";
byte[] content;
if (preview != null) {
content = imageDB.getContentIco();
} else {
content = imageDB.getContent();
}
flushFileToResponse(resp, contentType, content);
} catch (Throwable t) {
logger.error("An unexpected error occured while executing service \"getImage\"", t);
throw new SpagoBIServiceException(req.getPathInfo(), "An unexpected error occured while executing service \"getImage\"", t);
}
}
/**
*
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String lgId = request.getPathInfo();
OutputStream os = null;
try {
if (lgId.length() > 1) {
Language language = LanguageDAO.findByPk(lgId.substring(1)); // The first character / must be removed
if (language != null) {
byte[] img = SecureStore.b64Decode(new String(language.getImageContent()));
response.setContentType(language.getImageMime());
response.setContentLength(img.length);
os = response.getOutputStream();
os.write(img);
os.flush();
}
}
} catch (DatabaseException e) {
log.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(os);
}
}
/**
* respond to an HTTP GET request
*
* @param req
* HttpServletRequest object with the client request
* @param res
* HttpServletResponse object back to the client
* @exception ServletException
* in case of difficulties
* @exception IOException
* in case of difficulties
*/
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
// process any login that might be present
basicAuth.doLogin(req);
// catch the login helper requests
String option = req.getPathInfo();
String[] parts = option.split("/");
if ((parts.length == 2) && ((parts[1].equals("login"))))
{
doLogin(req, res, null);
}
else
{
dispatch(req, res);
}
}
@Override
protected void get(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String path = req.getPathInfo();
if (path == null) {
path = "";
} else if (path.startsWith("/")) {
path = path.substring(1);
}
if (path.isEmpty()) {
if (!getComponents().isPresent()) {
respondWithError(resp, 503, "Unable to load annotator class");
return;
}
respond(resp, MediaType.create("text", "x-yaml"), getComponents().orElse(""));
} else {
try {
Class<?> component = getClassFromString(path, componentPackage);
List<Map<String, Object>> parameters = getParameters(component);
respondWithJson(resp, parameters);
} catch (InvalidParameterException ipe) {
LoggerFactory.getLogger(clazz).warn("Could not find requested resource", ipe);
respondWithNotFound(resp);
}
}
}
@Override
public void service(HttpServletRequest request, HttpServletResponse response) {
String pathInfo = request.getPathInfo();
if (pathInfo == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
else {
try {
final PluginMetadata pluginMetadata = getPluginMetadataFromPath(pathInfo);
if (pluginMetadata.isCsrfProtectionEnabled()) {
if (!passesCsrf(request)) {
request.getSession().setAttribute(FlashMessageTag.ERROR_MESSAGE_KEY, LocaleUtils.getLocalizedString("global.csrf.failed"));
response.sendRedirect(request.getRequestURI());
return;
}
}
// Handle JSP requests.
if (pathInfo.endsWith(".jsp")) {
setCSRF(request);
if (handleDevJSP(pathInfo, request, response)) {
return;
}
handleJSP(pathInfo, request, response);
}
// Handle servlet requests.
else if (getServlet(pathInfo) != null) {
setCSRF(request);
handleServlet(pathInfo, request, response);
}
// Handle image/other requests.
else {
handleOtherRequest(pathInfo, response);
}
}
catch (Exception e) {
Log.error(e.getMessage(), e);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
}
private void service(final String repoID, final HttpServletRequest req, final HttpServletResponse resp)
throws RepositoryConfigException, RepositoryException, ServletException, IOException {
LOGGER.info("Servicing repository: {}", repoID);
setCredentials(req, resp);
final DynamicHttpRequest http = new DynamicHttpRequest(req);
final String path = req.getPathInfo();
final int idx = path.indexOf(repoID) + repoID.length();
http.setServletPath(http.getServletPath() + path.substring(0, idx));
final String pathInfo = path.substring(idx);
http.setPathInfo(pathInfo.length() == 0 ? null : pathInfo);
if (repositories.containsKey(repoID)) {
repositories.get(repoID).service(http, resp);
} else {
final Repository repository = manager.getRepository(repoID);
if (repository == null) {
final String noId = config.getInitParameter(NO_REPOSITORY);
if (noId == null || !noId.equals(repoID)) {
resp.setHeader("Cache-Control", "no-cache, no-store");
throw new BadRequestException("No such repository: " + repoID);
}
}
final ProxyRepositoryServlet servlet = new ProxyRepositoryServlet();
servlet.setRepositoryManager(manager);
if (repository != null) {
servlet.setRepositoryInfo(manager.getRepositoryInfo(repoID));
servlet.setRepository(repository);
}
servlet.init(new BasicServletConfig(repoID, config));
repositories.putIfAbsent(repoID, servlet);
repositories.get(repoID).service(http, resp);
}
}
/**
* 获得当前的ServletPath
* @param req
* @return
*/
public static final String getRecentPath(HttpServletRequest req) {
String uri = (String) req.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
String suf = (String) req.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
if (uri == null) {
uri = req.getServletPath();
suf = req.getPathInfo();
}
if (suf != null) {
uri += suf;
}
return uri;
}
@Override
protected StaticResource getStaticResource(HttpServletRequest request) throws IllegalArgumentException {
final String pathInfo = request.getPathInfo();
if (pathInfo == null || pathInfo.isEmpty() || "/".equals(pathInfo)) {
throw new IllegalArgumentException();
}
String name = "";
try {
name = URLDecoder.decode(pathInfo.substring(1), StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
LOGGER.error(e.getMessage());
}
final ServletContext context = request.getServletContext();
final File file = absolute ? new File(directory, name) : new File(context.getRealPath("/"), name).getAbsoluteFile();
return !file.exists() ? null : new StaticResource() {
@Override
public long getLastModified() {
return file.lastModified();
}
@Override
public InputStream getInputStream() throws IOException {
return Files.newInputStream(file.toPath());
}
@Override
public String getFileName() {
return file.getName();
}
@Override
public long getContentLength() {
return file.length();
}
};
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String pathInfo = req.getPathInfo();
if (CREATE_PATH.equals(pathInfo)) {
doRegisterGet(req, resp, "");
} else {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
String resourceURI = "META-INF/resources" + request.getServletPath() + request.getPathInfo();
InputStream inputStream = getResourceAsStream(resourceURI);
if (inputStream != null) {
String[] tokens = resourceURI.split("/");
String fileName = tokens[tokens.length - 1];
if (!disableCache && tokens.length > 4) {
String version = tokens[3];
response.setHeader("ETag", fileName + "_" + version);
response.setDateHeader("Expires",
System.currentTimeMillis() + XtextResourcesServlet.DEFAULT_EXPIRE_TIME_MS);
response.addHeader("Cache-Control",
("private, max-age=" + XtextResourcesServlet.DEFAULT_EXPIRE_TIME_S));
}
String mimeType = getServletContext().getMimeType(fileName);
String contentType = null;
if (mimeType != null) {
contentType = mimeType;
} else {
contentType = "application/octet-stream";
}
response.setContentType(contentType);
ByteStreams.copy(inputStream, response.getOutputStream());
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
} catch (IOException e) {
throw Exceptions.sneakyThrow(e);
}
}
@Override
protected void doGet(MCRServletJob job) throws Exception {
HttpServletRequest request = job.getRequest();
String pathInfo = request.getPathInfo();
HttpServletResponse response = job.getResponse();
if (pathInfo != null) {
List<String> splitted = PATH_SPLITTER.splitToList(pathInfo);
if (splitted.size() == 2) {
String collection = splitted.get(0);
String action = splitted.get(1);
String url = MCRURLRetriever.getURLforCollection(action, collection, true);
if (url != null) {
//MCR-1172 check if we redirect to a valid URI
URI uri = URI.create(url);
response.sendRedirect(response.encodeRedirectURL(uri.toString()));
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
return;
}
//misses action
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
//should never happen:
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Not thread safe
pathInfo = req.getPathInfo();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getPathInfo().equals("/tickets.json")) {
String resource = TestUtils.getResourceValue(FakeZendeskAPIServlet.class, "/tickets.json");
response.getOutputStream().print(resource);
} else {
throw new IllegalStateException("Unknown path: " + request.getPathInfo());
}
}
boolean isCacheableResourceRequest(HttpServletRequest request) {
String requestPath = request.getPathInfo();
if (requestPath == null) {
return false;
}
for (String resourcePrefix : resourcePrefixes) {
if (requestPath.startsWith(resourcePrefix)) {
return true;
}
}
return false;
}
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8")
public String getEngine(@Context HttpServletRequest req) {
logger.debug("IN");
try {
return serializeEngine();
} catch (Exception e) {
throw new SpagoBIServiceException(req.getPathInfo(), "An unexpected error occured while executing service", e);
} finally {
logger.debug("OUT");
}
}
/**
* getContextPath and getContextPath are defined in terms of servlets which we bypass completely.
* we may need to amend this implementation
*
* @param request
* @return
*/
private final void buildPathInfo(final HttpServletRequest request) {
fullPath = request.getContextPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());
// Strip the binding protocolBindingRoot off the front.
if (protocolBindingRoot != null && protocolBindingRoot.length() > 0) {
operationPath = fullPath.substring(protocolBindingRoot.length());
} else {
operationPath = fullPath;
}
}
@SuppressWarnings("unchecked")
@Override
public void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Object obj = request.getAttribute(ServletController.AUTH_SERVICE_LIST);
boolean isAuthServiceList = false;
if (obj != null) {
isAuthServiceList = Boolean.valueOf(obj.toString());
}
if (isAuthServiceList) {
String authServiceListRealm = (String)request.getAttribute(ServletController.AUTH_SERVICE_LIST_REALM);
ServiceListJAASAuthenticator authenticator = new ServiceListJAASAuthenticator();
authenticator.setRealm(authServiceListRealm);
if (!authenticator.authenticate(request, response)) {
return;
}
request.removeAttribute(ServletController.AUTH_SERVICE_LIST);
request.removeAttribute(ServletController.AUTH_SERVICE_LIST_REALM);
}
AbstractDestination[] destinations = destinationRegistry.getSortedDestinations();
if (request.getParameter("stylesheet") != null) {
renderStyleSheet(request, response);
return;
}
List<String> privateEndpoints;
if (bus == null) {
bus = BusFactory.getDefaultBus(false);
}
if (bus != null) {
privateEndpoints = (List<String>)bus.getProperty("org.apache.cxf.private.endpoints");
} else {
privateEndpoints = new ArrayList<>();
}
AbstractDestination[] soapEndpoints = getSOAPEndpoints(destinations, privateEndpoints);
AbstractDestination[] restEndpoints = getRestEndpoints(destinations, privateEndpoints);
ServiceListWriter serviceListWriter;
if ("false".equals(request.getParameter("formatted"))) {
boolean renderWsdlList = "true".equals(request.getParameter("wsdlList"));
serviceListWriter = new UnformattedServiceListWriter(renderWsdlList, bus);
} else {
String styleSheetPath;
if (serviceListStyleSheet != null) {
styleSheetPath = request.getContextPath() + "/" + serviceListStyleSheet;
} else {
styleSheetPath = "";
String contextPath = request.getContextPath();
if (contextPath != null) {
styleSheetPath += contextPath;
}
String servletPath = request.getServletPath();
if (servletPath != null) {
styleSheetPath += servletPath;
}
String pathInfo = request.getPathInfo();
if (pathInfo != null) {
styleSheetPath += pathInfo;
}
if (!styleSheetPath.endsWith("/")) {
styleSheetPath += "/";
}
styleSheetPath += "?stylesheet=1";
}
serviceListWriter =
new FormattedServiceListWriter(styleSheetPath, title, showForeignContexts, bus);
}
response.setContentType(serviceListWriter.getContentType());
Object basePath = request.getAttribute(Message.BASE_PATH);
serviceListWriter.writeServiceList(response.getWriter(),
basePath == null ? null : basePath.toString(),
soapEndpoints, restEndpoints);
}
/**
* 获取请求路径
* /servlet/MyServlet/a/b
*
* @param request
* @return
*/
public static String getRequestPath(HttpServletRequest request) {
String servletPath = request.getServletPath(); // /servlet/MyServlet
String pathInfo = request.getPathInfo(); // /a/b
return (null != servletPath ? servletPath : "") + StringUtils.defaultIfEmpty(pathInfo, StringUtils.EMPTY);
}