Example usage for javax.servlet ServletRequest getAttribute

List of usage examples for javax.servlet ServletRequest getAttribute

Introduction

In this page you can find the example usage for javax.servlet ServletRequest getAttribute.

Prototype

public Object getAttribute(String name);

Source Link

Document

Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.

Usage

From source file:org.apache.struts2.components.Include.java

public static String getContextRelativePath(ServletRequest request, String relativePath) {
    String returnValue;/*from   w w  w.  ja  v a2 s.  c  o m*/

    if (relativePath.startsWith("/")) {
        returnValue = relativePath;
    } else if (!(request instanceof HttpServletRequest)) {
        returnValue = relativePath;
    } else {
        HttpServletRequest hrequest = (HttpServletRequest) request;
        String uri = (String) request.getAttribute("javax.servlet.include.servlet_path");

        if (uri == null) {
            uri = RequestUtils.getServletPath(hrequest);
        }

        returnValue = uri.substring(0, uri.lastIndexOf('/')) + '/' + relativePath;
    }

    // .. is illegal in an absolute path according to the Servlet Spec and will cause
    // known problems on Orion application servers.
    if (returnValue.indexOf("..") != -1) {
        Stack stack = new Stack();
        StringTokenizer pathParts = new StringTokenizer(returnValue.replace('\\', '/'), "/");

        while (pathParts.hasMoreTokens()) {
            String part = pathParts.nextToken();

            if (!part.equals(".")) {
                if (part.equals("..")) {
                    stack.pop();
                } else {
                    stack.push(part);
                }
            }
        }

        StringBuffer flatPathBuffer = new StringBuffer();

        for (int i = 0; i < stack.size(); i++) {
            flatPathBuffer.append("/").append(stack.elementAt(i));
        }

        returnValue = flatPathBuffer.toString();
    }

    return returnValue;
}

From source file:org.opencms.xml.page.CmsXmlPageFactory.java

/**
 * Factory method to unmarshal (read) a XML page instance from
 * a resource, using the request attributes as cache.<p>
 * //from  w  w  w .j a  v  a2s. co m
 * @param cms the current OpenCms user context
 * @param resource the resource to unmarshal
 * @param req the current request
 * 
 * @return the unmarshaled XML page, or null if the given resource was not of type {@link CmsResourceTypeXmlPage}
 * 
 * @throws CmsException in something goes wrong
 */
public static CmsXmlPage unmarshal(CmsObject cms, CmsResource resource, ServletRequest req)
        throws CmsException {

    String rootPath = resource.getRootPath();

    if (!CmsResourceTypeXmlPage.isXmlPage(resource)) {
        // sanity check: resource must be of type XML page
        throw new CmsXmlException(Messages.get().container(Messages.ERR_XML_PAGE_FACT_NO_XMLPAGE_TYPE_1,
                cms.getSitePath(resource)));
    }

    // try to get the requested page form the current request attributes 
    CmsXmlPage page = (CmsXmlPage) req.getAttribute(rootPath);

    if (page == null) {
        // unmarshal XML structure from the file content
        page = unmarshal(cms, cms.readFile(resource));
        // store the page that was read as request attribute for future read requests
        req.setAttribute(rootPath, page);
    }

    return page;
}

From source file:com.redhat.rhn.frontend.taglibs.list.ListTagUtil.java

/**
 * Returns a link containing the URL + ALL the parameters of the
 * request query string minus the sort links, and the alpha link +
 * the additional params passed in the paramsToAdd map. The resulting
 * string is urlEncode'd with & encoded as &amp; so it can be used
 * in a href directly.//from ww  w.  j  a va 2  s .  c o  m
 *
 * @param request the Servlet Request
 * @param listName the current list name
 * @param paramsToAdd the params you might want to append to the url
 *                  for example makeSortLink passes in sortByLabel
 *                  while alpha bar passes in params that are specific to it.
 *  @param paramsToIgnore params to not include that would be normally
 * @return a link containing the URL  + (OtherParams - Sort - Alpha) + paramsToAdd
 */
public static String makeParamsLink(ServletRequest request, String listName, Map<String, String> paramsToAdd,
        List<String> paramsToIgnore) {
    String url = (String) request.getAttribute(ListTagHelper.PARENT_URL);
    String sortByLabel = makeSortByLabel(listName);
    String sortByDir = makeSortDirLabel(listName);
    String alphaKey = AlphaBarHelper.makeAlphaKey(listName);
    StringBuilder params = new StringBuilder();
    if (url.indexOf('?') < 0) {
        params.append("?");
    } else if (url.indexOf('?') != url.length() - 1) {
        url += "&amp;";
    }

    for (Enumeration<String> en = request.getParameterNames(); en.hasMoreElements();) {
        String paramName = en.nextElement();
        if (!sortByLabel.equals(paramName) && !sortByDir.equals(paramName) && !alphaKey.equals(paramName)
                && !paramsToIgnore.contains(paramName)) {
            if (params.length() > 1) {
                params.append("&amp;");
            }
            params.append(StringUtil.urlEncode(paramName)).append("=")
                    .append(StringUtil.urlEncode(request.getParameter(paramName)));
        }
    }
    for (String key : paramsToAdd.keySet()) {
        if (params.length() > 1) {
            params.append("&amp;");
        }
        params.append(StringUtil.urlEncode(key)).append("=").append(StringUtil.urlEncode(paramsToAdd.get(key)));
    }

    return url + params.toString();
}

From source file:com.xsw.utils.Servlets.java

/**
 * ???Request Parameters, copy from spring WebUtils.
 * //from   www. j a  va  2  s .  c  o  m
 * Parameter???.
 */
public static Map<String, Object> getParametersStartingWith(ServletRequest request, String prefix) {
    Validate.notNull(request, "Request must not be null");
    Map<String, Object> params = new TreeMap<String, Object>();
    if (prefix == null) {
        prefix = "";
    }
    // process Attribute
    Enumeration<String> paramNames = request.getAttributeNames();
    while (paramNames != null && paramNames.hasMoreElements()) {
        String paramName = paramNames.nextElement();
        if ("".equals(prefix) || paramName.startsWith(prefix)) {
            String unprefixed = paramName.substring(prefix.length());
            Object attobj = request.getAttribute(paramName);
            String[] values = null;
            if (attobj instanceof String[]) {
                values = (String[]) attobj;
            } else {
                values = new String[1];
                values[0] = String.valueOf(attobj);
            }
            if (values == null || values.length == 0) {
                // Do nothing, no values found at all.
            } else if (values.length > 1) {
                params.put(unprefixed, values);
            } else {
                params.put(unprefixed, values[0]);
            }
        }
    }
    // process parameter
    paramNames = request.getParameterNames();
    while (paramNames != null && paramNames.hasMoreElements()) {
        String paramName = paramNames.nextElement();
        if ("".equals(prefix) || paramName.startsWith(prefix)) {
            String unprefixed = paramName.substring(prefix.length());
            String[] values = request.getParameterValues(paramName);
            if (values == null || values.length == 0) {
                // Do nothing, no values found at all.
            } else if (values.length > 1) {
                params.put(unprefixed, values);
            } else {
                params.put(unprefixed, values[0]);
            }
        }
    }
    return params;
}

From source file:no.sesat.search.http.filters.SiteLocatorFilter.java

private static String getServerName(final ServletRequest servletRequest) {

    // find the current site. Since we are behind a ajp13 connection request.getServerName() won't work!
    // httpd.conf needs:
    //      1) "JkEnvVar SERVER_NAME" inside the virtual host directive.
    //      2) "UseCanonicalName Off" to assign ServerName from client's request.
    return null != servletRequest.getAttribute("SERVER_NAME")
            ? (String) servletRequest.getAttribute("SERVER_NAME")
            // falls back to this when not behind Apache. (Development machine).
            : servletRequest.getServerName() + ":" + servletRequest.getServerPort();
}

From source file:org.rhq.enterprise.gui.legacy.util.RequestUtils.java

public static String dumpRequestAttributesToString(ServletRequest request) {
    StringBuffer output = new StringBuffer();
    for (Enumeration e = request.getAttributeNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        Object value = request.getAttribute(name);
        output.append("name = '" + name + "'\n");
        output.append("type = '" + value.getClass().getCanonicalName() + "'\n");
        output.append("value = '" + value.toString() + "'\n\n");
    }//from w w w.  j  av a2s .  co m

    return output.toString();
}

From source file:org.surfnet.oaaas.auth.AbstractFilter.java

public final String getReturnUri(ServletRequest request) {
    String returnUri = (String) request.getAttribute(RETURN_URI);
    if (StringUtils.isEmpty(returnUri)) {
        returnUri = request.getParameter(RETURN_URI);
    }/* www .ja va 2  s  .c  o  m*/

    return returnUri;
}

From source file:org.surfnet.oaaas.auth.AbstractFilter.java

/**
 * Get the attribute value that serves as session state.
 * @param request the HttpServletRequest
 *//*from  w  w  w .  j a  va 2 s.  c om*/
public final String getAuthStateValue(ServletRequest request) {
    String authStateValue = (String) request.getAttribute(AUTH_STATE);
    if (StringUtils.isEmpty(authStateValue)) {
        authStateValue = request.getParameter(AUTH_STATE);
    }
    return authStateValue;
}

From source file:com.acme.demo.web.CSRFController.java

@RequestMapping("/csrf")
public Map<String, Boolean> auth(Principal principal, ServletRequest request, HttpServletResponse response) {
    CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
    Map<String, Boolean> result = new HashMap<String, Boolean>();
    if (principal == null || token == null) {
        result.put("authenticated", false);
    } else {/*from   ww  w.jav  a  2s  .  c o m*/
        //  Spring Security will allow the Token to be included in this header name
        response.setHeader("X-CSRF-HEADER", token.getHeaderName());
        // Spring Security will allow the token to be included in this parameter name
        response.setHeader("X-CSRF-PARAM", token.getParameterName());
        // this is the value of the token to be included as either a header or an HTTP parameter
        response.setHeader("X-CSRF-TOKEN", token.getToken());
        response.setHeader("X-USER-NAME", principal.getName());
        result.put("authenticated", true);
    }
    return result;
}

From source file:org.surfnet.oaaas.auth.AbstractUserConsentHandler.java

/**
 * // ww  w . j ava2  s .c o m
 * Get the Client from the request context to use in handling user consent
 * 
 * @param request
 *          the {@link ServletRequest}
 * @return the Client which is asking for consent
 */
public final Client getClient(ServletRequest request) {
    return (Client) request.getAttribute(CLIENT);
}