Example usage for javax.servlet.http HttpServletRequest getServletPath

List of usage examples for javax.servlet.http HttpServletRequest getServletPath

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getServletPath.

Prototype

public String getServletPath();

Source Link

Document

Returns the part of this request's URL that calls the servlet.

Usage

From source file:com.acmeair.web.RESTCookieSessionFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    try {/*from  w w  w.j av  a 2 s  . c  om*/
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String path = request.getContextPath() + request.getServletPath() + request.getPathInfo();
        // The following code is to ensure that OG is always set on the thread
        try {
            TransactionService txService = getTxService();
            if (txService != null)
                txService.prepareForTransaction();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // could do .startsWith for now, but plan to move LOGOUT to its own REST interface eventually
        if (path.endsWith(LOGIN_PATH) || path.endsWith(LOGOUT_PATH)) {
            // if logging in, 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();
            else {
                log.info("falling through with a sessionCookie break, but it was null");
            }
            // 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("")) {
                log.info("sending SC_FORBIDDEN due to empty session cookie");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
            // Need the URLDecoder so that I can get @ not %40
            ValidateTokenCommand validateCommand = new ValidateTokenCommand(sessionId);
            CustomerSession cs = validateCommand.execute();
            if (cs != null) {
                request.setAttribute(LOGIN_USER, cs.getCustomerid());
                chain.doFilter(req, resp);
                return;
            } else {
                log.info("sending SC_FORBIDDEN due  to validateCommand returning null");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
        }

        // if we got here, we didn't detect the session cookie, so we need to return 403
        log.info("sending SC_FORBIDDEN due finding no sessionCookie");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
}

From source file:com.careerly.common.support.resolver.ControllerExceptionResolver.java

@Override
public ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) {/*w  ww.  j  a  va2s  .  c om*/

    ControllerExceptionResolver.logger
            .error(String.format("ERROR ## [%s] happend error,the trace is ", request.getServletPath()), ex);

    String fullClazzName = StringUtils.substringAfterLast(handler.getClass().getName(), ".");
    String clazzName = StringUtils.substringBefore(fullClazzName, "$");

    if (clazzName.endsWith(ControllerExceptionResolver.DATA_CONTROLLER) || clazzName
            .endsWith(ControllerExceptionResolver.API_CONTROLLER)) /** ??DataAPI **/
    {
        if (ex instanceof BusinessException) /** BusinessException?message?ErrorJsonObject **/
        {
            BusinessException be = (BusinessException) ex;
            resolveDataException(request, response, handler,
                    StandardJsonObject.newErrorJsonObject(be.getErrorCode(), be.getLocalizedMessage()));
        } else/** ?BusinessExceptionException"api error"ErrorJsonObject **/
        {
            resolveDataException(request, response, handler,
                    StandardJsonObject.newErrorJsonObject("?!"));
        }

        return null;
    } else /** ?Page **/
    {
        if (ex instanceof BusinessException)/** BusinessException?error? **/
        {
            ModelAndView mv = new ModelAndView();
            mv.addObject("errMsg", ex.getLocalizedMessage());
            mv.setViewName("views/error");
            return mv;
        } else /** ?BusinessExceptionExceptionerror? **/
        {
            return super.doResolveException(request, response, handler, ex);
        }
    }

}

From source file:org.opencron.server.service.SecurityHandlerInterceptor.java

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

    HttpSession session = request.getSession();
    String requestURI = request.getContextPath() + request.getServletPath();

    //???,?//w w  w .  j a  va2s. co m
    if (requestURI.contains("/css/") || requestURI.contains("/fonts/") || requestURI.contains("/img/")
            || requestURI.contains("/js/") || requestURI.contains("/WEB-INF")) {
        return super.preHandle(request, response, handler);
    }

    //
    if (requestURI.contains("/login") || requestURI.contains("/upload")) {
        return super.preHandle(request, response, handler);
    }

    String referer = request.getHeader("referer");
    if (referer != null && !referer.startsWith(WebUtils.getWebUrlPath(request))) {
        response.sendRedirect("/");
        logger.info("[opencron]Bad request,redirect to login page");
        OpencronTools.invalidSession();
        return false;
    }

    User user = OpencronTools.getUser();
    if (user == null) {
        logger.info(request.getRequestURL().toString());
        //?
        response.sendRedirect("/");
        OpencronTools.invalidSession();
        logger.info("[opencron]session is null,redirect to login page");
        return false;
    }

    //????
    if (!OpencronTools.isPermission(session) && (requestURI.contains("/config/")
            || requestURI.contains("/user/view") || requestURI.contains("/user/add")
            || requestURI.contains("/agent/add") || requestURI.contains("/agent/edit"))) {
        logger.info("[opencron]illegal or limited access");
        return false;
    }

    if (handler instanceof HandlerMethod) {
        if (!verifyCSRF(request)) {
            response.sendRedirect("/");
            logger.info("[opencron]Bad request,redirect to login page");
            OpencronTools.invalidSession();
            return false;
        }
    }

    return super.preHandle(request, response, handler);
}

From source file:com.threeti.proxy.RequestFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    String path = request.getServletPath();
    String pathInfo = path.substring(path.lastIndexOf("/"));

    if (pathInfo == null) {
        response.getWriter().write("error");
    } else {// w w  w  .  java  2s. c  o m
        if (path.contains("/proxy")) {
            pathInfo = path.substring(path.lastIndexOf("/proxy") + 6);
            if ("POST".equals(request.getMethod())) { // POST
                String urlString = this.baseURL + pathInfo;
                logger.info(urlString);
                String s = this.getParams(req).substring(0, this.getParams(req).length() - 1);
                byte[] data = s.getBytes("utf-8");
                HttpURLConnection conn = null;
                DataOutputStream outStream = null;
                URL httpUrl = new URL(urlString);
                conn = (HttpURLConnection) httpUrl.openConnection();
                conn.setConnectTimeout(7000);
                conn.setReadTimeout(7000);
                conn.setUseCaches(false);
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Charset", "utf-8");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("Content-Length", String.valueOf(data.length));
                outStream = new DataOutputStream(conn.getOutputStream());
                outStream.write(data);
                outStream.flush();
                if (conn.getResponseCode() == 200) {
                    InputStream in = conn.getInputStream();
                    IOUtils.copy(in, response.getOutputStream());
                } else {
                    try {
                        throw new Exception("ResponseCode=" + conn.getResponseCode());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } else if ("DELETE".equals(request.getMethod())) {
                String urlString = this.baseURL + pathInfo + "?" + this.getParams(req);
                logger.info(urlString);
                HttpURLConnection conn = null;
                URL url = new URL(urlString);
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(7000);
                conn.setReadTimeout(7000);
                conn.setUseCaches(false);
                conn.setDoOutput(true);
                conn.setRequestMethod("DELETE");
                if (conn.getResponseCode() == 200) {
                    InputStream in = conn.getInputStream();
                    IOUtils.copy(in, response.getOutputStream());
                } else {
                    try {
                        throw new Exception("ResponseCode=" + conn.getResponseCode());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                String urlString = this.baseURL + pathInfo + "?" + this.getParams(req);
                logger.info(urlString);
                URL url = new URL(urlString);
                InputStream input = url.openStream();
                IOUtils.copy(input, response.getOutputStream());
            }
        } else {
            chain.doFilter(req, res);
        }
    }
}

From source file:com.wwinsoft.modules.security.jcaptcha.JCaptchaFilter.java

/**
 * Filter?.// w  ww.  j  av a  2 s. co m
 */
public void doFilter(final ServletRequest theRequest, final ServletResponse theResponse,
        final FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) theRequest;
    HttpServletResponse response = (HttpServletResponse) theResponse;
    String servletPath = request.getServletPath();

    //?filterProcessesUrl??,??.
    if (StringUtils.startsWith(servletPath, filterProcessesUrl)) {
        boolean validated = validateCaptchaChallenge(request);
        if (validated) {
            chain.doFilter(request, response);
        } else {
            redirectFailureUrl(request, response);
        }
    } else {
        genernateCaptchaImage(request, response);
    }
}

From source file:com.googlesource.gerrit.plugins.github.oauth.OAuthGitFilter.java

private String getRequestPathWithQueryString(HttpServletRequest httpRequest) {
    String requestPathWithQueryString = httpRequest.getContextPath() + httpRequest.getServletPath()
            + Strings.nullToEmpty(httpRequest.getPathInfo()) + "?" + httpRequest.getQueryString();
    return requestPathWithQueryString;
}

From source file:org.brickred.socialauth.spring.controller.SocialAuthWebController.java

/**
 * Initiates the connection with required provider.It redirects the browser
 * to an appropriate URL which will be used for authentication with the
 * requested provider.//from   w  w w .  j a v a2 s.  c  o m
 */
@SuppressWarnings("unused")
@RequestMapping(params = "id")
private String connect(@RequestParam("id") final String providerId, final HttpServletRequest request)
        throws Exception {
    LOG.debug("Getting Authentication URL for :" + providerId);
    String callbackURL = baseCallbackUrl + request.getServletPath();
    String url = socialAuthManager.getAuthenticationUrl(providerId, callbackURL);
    if (callbackURL.equals(url)) {
        url = successPageURL;
        socialAuthManager.connect(new HashMap<String, String>());
    }
    socialAuthTemplate.setSocialAuthManager(socialAuthManager);
    return "redirect:" + url;
}

From source file:cn.guoyukun.spring.web.filter.BaseFilter.java

/**
 * 1?????/*from   ww  w .ja  va2 s.  c o m*/
 * 2?????
 */
@Override
public final void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String currentURL = httpRequest.getServletPath();

    logger.debug("url filter : current url : [{}]", currentURL);

    if (isBlackURL(currentURL)) {
        chain.doFilter(request, response);
        return;
    }

    if (!isWhiteURL(currentURL)) {
        chain.doFilter(request, response);
        return;
    }
    doFilter(httpRequest, httpResponse, chain);
    return;
}

From source file:com.brokenmodel.swats.RouterServlet.java

private void handleRequest(HttpServletRequest request, HttpServletResponse response,
        ControllerRequest.Type type) {
    try {/*w  w  w .j a va 2s.c o  m*/
        URL rootURL = new URL(request.getScheme(), request.getServerName(), request.getServerPort(),
                request.getContextPath() + request.getServletPath());

        String appRoot = rootURL.getFile();
        String htmlRoot = request.getContextPath();

        MatchedRoute matchedRoute = controllers.matchRoute(request.getPathInfo());
        ControllerRequest controllerRequest = new ControllerRequest(request, response, appRoot, htmlRoot,
                matchedRoute.getUrlParams(), type, handleMultipart(request), getDataSource());
        AbstractController controller = matchedRoute.getController();
        controller.doRequest(controllerRequest);
    } catch (Throwable t) {
        log(t);
        try {
            // only will work if output stream has not been opened
            PrintWriter pw = new PrintWriter(response.getWriter());
            pw.append("<pre>");
            pw.append("We're sorry - an error has occurred:\n\n");
            t.printStackTrace(pw);
            pw.append("</pre>");
        } catch (Throwable t2) {
        }
    }
}

From source file:com.temenos.interaction.core.web.RequestContextFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    final HttpServletRequest servletRequest = (HttpServletRequest) request;

    String requestURI = servletRequest.getRequestURI();
    requestURI = StringUtils.removeStart(requestURI,
            servletRequest.getContextPath() + servletRequest.getServletPath());
    String baseURL = StringUtils.removeEnd(servletRequest.getRequestURL().toString(), requestURI);

    Map<String, List<String>> headersMap = new HashMap<>();
    Enumeration<String> headerNames = servletRequest.getHeaderNames();
    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            List<String> valuesList = Collections.list(servletRequest.getHeaders(headerName));
            headersMap.put(headerName, valuesList);
        }//from  w w w  .  ja v  a2 s . c  o m
    }

    RequestContext ctx;
    Principal userPrincipal = servletRequest.getUserPrincipal();
    if (userPrincipal != null) {
        ctx = new RequestContext(baseURL, servletRequest.getRequestURI(),
                servletRequest.getHeader(RequestContext.HATEOAS_OPTIONS_HEADER), userPrincipal, headersMap);
    } else {
        ctx = new RequestContext(baseURL, servletRequest.getRequestURI(),
                servletRequest.getHeader(RequestContext.HATEOAS_OPTIONS_HEADER), headersMap);
    }

    RequestContext.setRequestContext(ctx);

    try {
        chain.doFilter(request, response);
    } finally {
        RequestContext.clearRequestContext();
    }
}