Example usage for javax.servlet.http HttpServletRequest getContextPath

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

Introduction

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

Prototype

public String getContextPath();

Source Link

Document

Returns the portion of the request URI that indicates the context of the request.

Usage

From source file:br.com.flucianofeijao.security.JsfRedirectStrategy.java

/**
 * Redirects the response to the supplied URL.
 * <p>//w  ww  .  java  2s .c om
 * If <tt>contextRelative</tt> is set, the redirect value will be the value after the request context path. Note
 * that this will result in the loss of protocol information (HTTP or HTTPS), so will cause problems if a
 * redirect is being performed to change to HTTPS, for example.
 */
public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url)
        throws IOException {
    String redirectUrl = calculateRedirectUrl(request.getContextPath(), url);
    redirectUrl = response.encodeRedirectURL(redirectUrl);

    if (logger.isDebugEnabled()) {
        logger.debug("Redirecting to '" + redirectUrl + "'");
    }

    //we should redirect using ajax response if the case warrants
    boolean ajaxRedirect = request.getHeader("faces-request") != null
            && request.getHeader("faces-request").toLowerCase().indexOf("ajax") > -1;

    if (ajaxRedirect) {
        //javax.faces.context.FacesContext ctxt = javax.faces.context.FacesContext.getCurrentInstance();
        //ctxt.getExternalContext().redirect(redirectUrl);

        String ajaxRedirectXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                + "<partial-response><redirect url=\"" + redirectUrl + "\"></redirect></partial-response>";
        response.setContentType("text/xml");
        response.getWriter().write(ajaxRedirectXml);
    } else {
        response.sendRedirect(redirectUrl);
    }

}

From source file:br.vschettino.forum.controller.SiteController.java

@RequestMapping(value = "/logout")
@ResponseBody//from www . j  av  a 2  s. c  o m
public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) {
    try {
        request.getSession().removeAttribute("usuario");
        response.sendRedirect(request.getContextPath() + "/web/login?logout=true");

    } catch (IOException ex) {
        Logger.getLogger(SiteController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.jayway.jaxrs.hateoas.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);
    UriBuilder uriBuilder = UriBuilder.fromUri(baseURL);

    RequestContext ctx = new RequestContext(uriBuilder,
            servletRequest.getHeader(RequestContext.HATEOAS_OPTIONS_HEADER));

    RequestContext.setRequestContext(ctx);
    try {/*from w w  w .ja v a  2  s  .  c o  m*/
        chain.doFilter(request, response);
    } finally {
        RequestContext.clearRequestContext();
    }
}

From source file:com.kurniakue.kurse.kursepo.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   ww w.  j  av  a  2s .co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println(request.getContextPath());
    try {
        ReqContext.init(request, response);
        if (!ReqContext.get().process()) {
            processRequest(getRequest(), getResponse());
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        ReqContext.close();
    }
}

From source file:org.shaf.server.security.AuthenticationFailureHandler.java

/**
 * Executes if authentication has failed.
 *//*from   w  ww . ja va  2s.co m*/
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {
    LOG.debug("SECURITY: Authentication failure...");

    response.sendRedirect(request.getContextPath() + "/login.jsp?error=true");
}

From source file:com.clican.pluto.cms.ui.servlet.VelocityResourceServlet.java

@SuppressWarnings("unchecked")
@Override/* ww  w  .j a  v  a2s  .  c  om*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String prefix = request.getContextPath() + request.getServletPath();
    if (request.getRequestURI().startsWith(prefix)) {
        String path = request.getRequestURI().replaceFirst(prefix, "");
        if (path.startsWith("/")) {
            path = path.substring(1, path.indexOf(";"));
        }
        // request.getSession().setAttribute("propertyDescriptionList", new
        // ArrayList<PropertyDescription>());
        Writer w = new OutputStreamWriter(response.getOutputStream(), "utf-8");
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        InputStream is = null;
        try {
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
            byte[] data = new byte[is.available()];
            is.read(data);
            String content = new String(data, "utf-8");
            Template t = null;
            VelocityContext velocityContext = new VelocityContext();
            HttpSession session = request.getSession();
            Enumeration<String> en = session.getAttributeNames();
            while (en.hasMoreElements()) {
                String name = en.nextElement();
                velocityContext.put(name, session.getAttribute(name));
            }
            SimpleNode node = RuntimeSingleton.getRuntimeServices().parse(content, path);
            t = new Template();
            t.setName(path);
            t.setRuntimeServices(RuntimeSingleton.getRuntimeServices());
            t.setData(node);
            t.initDocument();
            Writer wr = new OutputStreamWriter(os);
            t.merge(velocityContext, wr);
            wr.flush();
            byte[] datas = os.toByteArray();
            String s = new String(datas);
            log.info(s);
        } catch (Exception e) {
            log.error("", e);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } finally {
            if (w != null) {
                w.close();
            }
            if (is != null) {
                is.close();
            }
        }
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

}

From source file:br.com.sisped.security.JsfRedirectStrategy.java

/**
 * Redirects the response to the supplied URL.
 * <p>/*from   w ww .  j  a v  a  2 s .  c o  m*/
 * If <tt>contextRelative</tt> is set, the redirect value will be the value
 * after the request context path. Note that this will result in the loss of
 * protocol information (HTTP or HTTPS), so will cause problems if a
 * redirect is being performed to change to HTTPS, for example.
 */
public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url)
        throws IOException {
    String redirectUrl = calculateRedirectUrl(request.getContextPath(), url);
    redirectUrl = response.encodeRedirectURL(redirectUrl);

    if (logger.isDebugEnabled()) {
        logger.debug("Redirecting to '" + redirectUrl + "'");
    }

    // we should redirect using ajax response if the case warrants
    boolean ajaxRedirect = request.getHeader("faces-request") != null
            && request.getHeader("faces-request").toLowerCase().indexOf("ajax") > -1;

    if (ajaxRedirect) {
        // javax.faces.context.FacesContext ctxt =
        // javax.faces.context.FacesContext.getCurrentInstance();
        // ctxt.getExternalContext().redirect(redirectUrl);

        String ajaxRedirectXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                + "<partial-response><redirect url=\"" + redirectUrl + "\"></redirect></partial-response>";
        response.setContentType("text/xml");
        response.getWriter().write(ajaxRedirectXml);
    } else {
        response.sendRedirect(redirectUrl);
    }

}

From source file:com.ideo.jso.tag.includers.RetentionIncluder.java

/**
 * Adds a tag into the flow to include a resource "the classic way", and suffix by a timestamp corresponding to the last modification date of the file
 * @param pageContext/*from  w  w w .j a v a2  s. com*/
 * @param out
 * @param webPath
 * @param tagBegin
 * @param tagEnd
 * @throws IOException
 */
private void includeResource(PageContext pageContext, Writer out, String webPath, String tagBegin,
        String tagEnd) throws IOException {
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

    out.write(tagBegin);
    out.write(URLUtils.concatUrlWithSlaches(request.getContextPath(), webPath));

    //TODO enable ?
    /*if (fileName != null && fileName.length() > 0) {
       long timestamp = new File(fileName).lastModified();
       out.write("?"+JsoServlet.TIMESTAMP+"=" + timestamp);
    }*/
    out.write(tagEnd);
    out.write("\n");
}

From source file:co.com.ppit2.web.controller.handler.MyAccessDeniedHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response,
        AccessDeniedException accessDeniedException) throws IOException, ServletException {
    String uri = request.getRequestURI();
    String cPath = request.getContextPath();
    int longCPath = cPath.length();
    String pagSolicitada = uri.substring(longCPath);

    response.sendRedirect(accessDeniedUrl);
    request.getSession().setAttribute("pagSolicitada", pagSolicitada);

}

From source file:de.otto.jsonhome.example.products.ProductsController.java

@RequestMapping(method = RequestMethod.GET, produces = { "application/example-products", "application/json" })
@ResponseBody/*from w  ww.  jav a 2 s . c o m*/
@Rel("/rel/products")
public Map<String, ?> getProductsJson(final @RequestParam(required = false, defaultValue = "*") String query,
        final HttpServletRequest request) {
    final List<Product> products = productService.findProducts(query);
    return productsToJson(products, request.getContextPath());
}