Example usage for javax.servlet ServletRequest setCharacterEncoding

List of usage examples for javax.servlet ServletRequest setCharacterEncoding

Introduction

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

Prototype

public void setCharacterEncoding(String env) throws UnsupportedEncodingException;

Source Link

Document

Overrides the name of the character encoding used in the body of this request.

Usage

From source file:cn.bc.web.filter.SetCharacterEncodingFilter.java

/**
 * Select and set (if specified) the character encoding to be used to
 * interpret request parameters for this request.
 *
 * @param request The servlet request we are processing
 * @param result The servlet response we are creating
 * @param chain The filter chain we are processing
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 *///w  w  w.java2  s . com
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // Conditionally select and set the character encoding to be used
    if (ignore || (request.getCharacterEncoding() == null)) {
        String encoding = this.encoding;
        if (encoding != null) {
            request.setCharacterEncoding(encoding);
            response.setContentType("text/html;charset=" + encoding);
            if (logger.isDebugEnabled()) {
                logger.debug(":response.setCharacterEncoding(\"" + encoding + "\"");
            }
        }
    }

    // Pass control on to the next filter
    chain.doFilter(request, response);
}

From source file:org.nuxeo.ecm.platform.web.common.encoding.NuxeoEncodingFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request != null) {
        // NXP-5555: set encoding to UTF-8 in case this method is called
        // before
        // encoding is set to UTF-8 on the request
        if (request.getCharacterEncoding() == null) {
            try {
                request.setCharacterEncoding("UTF-8");
            } catch (UnsupportedEncodingException e) {
                log.error(e, e);/*  w  ww .  ja va2 s  .  c o  m*/
            }
        }

        RequestControllerManager rcm = Framework.getLocalService(RequestControllerManager.class);
        for (String headerName : rcm.getResponseHeaders().keySet()) {
            if (response instanceof HttpServletResponse
                    && !((HttpServletResponse) response).containsHeader(headerName)) {
                ((HttpServletResponse) response).addHeader(headerName,
                        rcm.getResponseHeaders().get(headerName));
            }
        }
    }

    chain.doFilter(request, response);
}

From source file:eionet.gdem.web.filters.SetCharacterEncodingFilter.java

/**
 * Select and set (if specified) the character encoding to be used to interpret request parameters for this request.
 *
 * @param request// w w w  .java2  s .co m
 *            The servlet request we are processing
 * @param response
 *            The servlet response we are creating
 * @param chain
 *            The filter chain we are processing
 *
 * @exception IOException
 *                if an input/output error occurs
 * @exception ServletException
 *                if a servlet error occurs
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // Conditionally select and set the character encoding to be used
    if (ignore || (request.getCharacterEncoding() == null)) {
        String encoding = selectEncoding(request);
        if (encoding != null)
            request.setCharacterEncoding(encoding);
    }

    // Pass control on to the next filter
    try {
        chain.doFilter(request, response);
    } catch (Exception e) {
        // Logging unhandled exception
        LOGGER.error("Unhandled exception caught", e);
        throw new ServletException(e);
    }

}

From source file:info.magnolia.cms.filters.ContentTypeFilter.java

private void setContentType(ServletRequest req, ServletResponse resp) {
    resp.setContentType(MIMEMapping.getMIMEType((HttpServletRequest) req));
    String characterEncoding = MIMEMapping.getContentEncoding((HttpServletRequest) req);

    if (StringUtils.isEmpty(characterEncoding)) {
        characterEncoding = "UTF-8"; //$NON-NLS-1$
    }//from  ww  w. ja  va 2s .c  o  m

    resp.setCharacterEncoding(characterEncoding);

    try {
        req.setCharacterEncoding(characterEncoding);
    } catch (IllegalStateException e) {
        log.debug("can't set character encoding for the request", e); //$NON-NLS-1$
    } catch (UnsupportedEncodingException e) {
        log.error("can't set character encoding for the request", e); //$NON-NLS-1$
    }
}

From source file:org.codelabor.system.web.filter.EncodingFilter.java

@Override
public void preprocessFilterChain(ServletRequest request, ServletResponse response)
        throws IOException, ServletException {
    String requestBeforeEncoding = request.getCharacterEncoding();
    String responseBeforeEncoding = response.getCharacterEncoding();

    if (encoding.equalsIgnoreCase(requestBeforeEncoding)) {
        logger.debug("request character encoding: {}", encoding);
    } else {/*from ww  w . j ava  2s.c om*/
        request.setCharacterEncoding(encoding);
        String requestAfterEncoding = request.getCharacterEncoding();
        logger.debug("request character encoding: {} -> {}", requestBeforeEncoding, requestAfterEncoding);
    }
    if (encoding.equalsIgnoreCase(responseBeforeEncoding)) {
        logger.debug("response character encoding: {}", encoding);
    } else {
        response.setCharacterEncoding(encoding);
        String responseAfterCharacterEncoding = response.getCharacterEncoding();
        logger.debug("response character encoding: {} -> {}", responseBeforeEncoding,
                responseAfterCharacterEncoding);
    }
}

From source file:com.sourcesense.alfresco.opensso.AlfrescoOpenSSOFilter.java

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

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpSession httpSession = httpRequest.getSession();

    request.setCharacterEncoding("UTF-8");

    SSOToken token = getOpenSSOClient().createTokenFrom(httpRequest);

    boolean isLoginRequest = isLoginRequest(httpRequest);
    boolean isLogoutRequest = isLogoutRequest(httpRequest);
    boolean isGuestRequest = (token == null && !isLoginRequest && !isLogoutRequest);
    boolean isNormalRequest = (token != null && !isLoginRequest && !isLogoutRequest);

    if (isLoginRequest) {
        httpSession.invalidate();//from  www.j  a  v  a  2s . c  o  m
        httpResponse.sendRedirect(buildURLForRedirect(request));
    }

    if (isGuestRequest) {
        getAlfrescoFacade().authenticateAsGuest(httpSession);
        chain.doFilter(request, response);
    }

    if (isLogoutRequest) {
        doLogout(httpSession, token);
        httpResponse.sendRedirect(buildURLForRedirect(request));
    }

    if (isNormalRequest) {
        String principal = getOpenSSOClient().getPrincipal(token);
        if (!getAlfrescoFacade().existUser(principal)) {
            String email = getOpenSSOClient().getUserAttribute(OpenSSOClient.ATTR_EMAIL, token);
            String fullName = getOpenSSOClient().getUserAttribute(OpenSSOClient.ATTR_FULL_NAME, token);
            String firstName = getOpenSSOClient().getUserAttribute(OpenSSOClient.ATTR_LAST_NAME, token);
            getAlfrescoFacade().createUser(principal, email, firstName, fullName);
        }
        List<String> groups = getOpenSSOClient().getGroups(token);
        getAlfrescoFacade().createOrUpdateGroups(principal, groups);
        getAlfrescoFacade().setAuthenticatedUser(httpRequest, httpResponse, httpSession, principal);
        chain.doFilter(request, response);
    }

}

From source file:com.googlecode.jtiger.modules.ecside.filter.ECSideFilter.java

public void doEncoding(ServletRequest request, ServletResponse response) throws IOException, ServletException {
    if (useEncoding || (request.getCharacterEncoding() == null)) {
        if (encoding != null)
            // Set the same character encoding for the request and the
            // response
            request.setCharacterEncoding(encoding);
        // response.setCharacterEncoding(encoding);
    }/*w  ww  .j  a va 2 s .  c  om*/
}

From source file:org.toobsframework.servlet.filters.compression.CompressionFilter.java

/**
 * The filter intercepts the querystring for this request
 * and will reject the request if any of the filtered characters are found
 *
 * @param request The servlet request object
 * @param response The servlet response object
 * @param chain The servlet chain/*from  www .  j a  v  a 2 s .c o m*/
 *
 * @throws ServletException
 */
@SuppressWarnings("unchecked")
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (log.isDebugEnabled()) {
        log.debug("Begin [doFilter]");
    }

    request.setCharacterEncoding("UTF-8");

    String query = ((HttpServletRequest) request).getQueryString();
    boolean noFilter = (query != null && query.indexOf("DisableWhiteSpace") != -1);
    boolean compressible = false;
    //long startTime = 0L;
    if (!filterEnabled || noFilter) { // || ((HttpServletRequest)request).getRequestURI().endsWith("application.do")
        chain.doFilter(request, response);
    } else {
        if (filterCompress) {
            Enumeration<String> headers = ((HttpServletRequest) request).getHeaders("Accept-Encoding");
            while (headers.hasMoreElements()) {
                String value = (String) headers.nextElement();
                if (value.indexOf(compressionType) != -1) {
                    compressible = true;
                    break;
                }
            }
        }
        if (smartCompress) {
            for (int i = 0; i < excludedHosts.size(); i++) {
                if (("" + ((HttpServletRequest) request).getRemoteAddr())
                        .startsWith((String) excludedHosts.get(i))) {
                    compressible = false;
                }
            }
        }
        FilterResponseWrapper wrapper = new FilterResponseWrapper((HttpServletResponse) response);
        chain.doFilter(request, wrapper);
        byte[] input = wrapper.getData();
        byte[] output = null;

        OutputStream servletoutputstream = null;
        String content = wrapper.getContentType();
        if (content != null && content.toUpperCase().indexOf("TEXT/") >= 0) {
            response.setContentType(content);
            if (filterCompress && compressible) {
                HttpServletResponse httpResponse = (HttpServletResponse) response;
                httpResponse.addHeader("Content-Encoding", compressionType);
                servletoutputstream = new GZIPOutputStream(response.getOutputStream(), bufferSize);
            } else {
                servletoutputstream = response.getOutputStream();
            }
            if (filterWhitespace) {
                output = new byte[input.length];
                int i = 0;
                int o = 0;
                boolean htComment = false;
                boolean inScript = false;
                while (i < input.length) {
                    if (input[i] == 13 || input[i] == 9) { // 13=CR, 9=TAB
                        // nothing
                    } else if (input[i] == 10) { // 10=LF
                        if (inScript) {
                            output[o] = input[i];
                            o++;
                        }
                    } else if (input[i] == 32) { // 32=Space
                        if (!htComment && !inScript && i + 1 < input.length && input[i + 1] == 32) {
                            i++;
                            while (i + 1 < input.length && input[i + 1] == 32) {
                                i++;
                            }
                        } else if (!htComment) {
                            output[o] = input[i];
                            o++;
                        }
                    } else if (input[i] == 60) { // 60=<
                        if (!inScript && (i + 2 < input.length) && (input[i + 1] == 33)
                                && (input[i + 2] == 45)) {
                            i += 3;
                            htComment = true;
                        } else if (!htComment && i + 2 < input.length
                                && (input[i + 1] == 83 || input[i + 1] == 115)
                                && (input[i + 2] == 67 || input[i + 2] == 99)) {
                            inScript = true;
                            output[o] = input[i];
                            output[o + 1] = input[i + 1];
                            output[o + 2] = input[i + 2];
                            o += 3;
                            i += 2;
                        } else if (!htComment && i + 3 < input.length && (input[i + 1] == 47)
                                && (input[i + 2] == 83 || input[i + 2] == 115)
                                && (input[i + 3] == 67 || input[i + 3] == 99)) {
                            inScript = false;
                            output[o] = input[i];
                            output[o + 1] = input[i + 1];
                            output[o + 2] = input[i + 2];
                            output[o + 3] = input[i + 3];
                            o += 4;
                            i += 3;
                        } else if (!htComment) {
                            output[o] = input[i];
                            o++;
                        }
                    } else if (input[i] == 62) { // 62 = >
                        if (htComment && input[i - 1] == 45 && input[i - 2] == 45) {
                            htComment = false;
                        } else if (!htComment) {
                            output[o] = input[i];
                            o++;
                        }
                    } else if (!htComment) {
                        output[o] = input[i];
                        o++;
                    }
                    i++;
                }
                servletoutputstream.write(output, 0, o);
            } else {
                servletoutputstream.write(input);
            }
        } else {
            servletoutputstream = response.getOutputStream();
            servletoutputstream.write(input);
        }

        if (servletoutputstream != null) {
            servletoutputstream.flush();
            servletoutputstream.close();
        }
        input = null;
        output = null;
    }
    if (log.isDebugEnabled()) {
        log.debug("End [doFilter]");
    }
}

From source file:com.scooterframework.web.controller.ScooterRequestFilter.java

/**
 * Time the processing that is performed by all subsequent filters in the
 * current filter stack, including the ultimately invoked servlet.
 *
 * @param request The servlet request we are processing
 * @param chain The filter chain we are processing
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 *//*from www.  java  2 s .c om*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    boolean staticContent = isStaticContentRequest((HttpServletRequest) request);

    if (encoding != null) {
        request.setCharacterEncoding(encoding);
        if (!staticContent) {
            response.setCharacterEncoding(encoding);
        }
    }

    // boolean skip = skippedRequestPath((HttpServletRequest)request);
    boolean skip = staticContent;

    long before = System.currentTimeMillis();

    if (!skip) {
        initializeActionContext((HttpServletRequest) request, (HttpServletResponse) response);
    } else {
        request.setAttribute(Constants.SKIP_PATH, "Y");
    }

    if (isAjaxRequest((HttpServletRequest) request)) {
        request.setAttribute(Constants.SITEMESH_FILTERAPPLIED, Boolean.TRUE);
    }

    String requestPathKeyWithQueryString = requestInfo(skip, (HttpServletRequest) request);
    log.debug("============>>\"" + requestPathKeyWithQueryString + "\"");

    try {
        chain.doFilter(request, response);
    } catch (Throwable ex) {
        log.error("Error from chain.doFilter: " + ex.getMessage(), ex);
    }

    long after = System.currentTimeMillis();

    if (EnvConfig.getInstance().allowRecordBenchmark()) {
        log.info("\"" + requestPathKeyWithQueryString + "\" takes: " + (after - before) + " ms");
        if (EnvConfig.getInstance().allowRecordBenchmarkInHeader()) {
            HttpServletResponseWrapper resw = new HttpServletResponseWrapper((HttpServletResponse) response);
            resw.addHeader("Exec-Time", (after - before) + " ms");
        }
    }

    clearCachedRequestData();
}

From source file:org.ecside.filter.ECSideFilter.java

 public void doEncoding(ServletRequest request, ServletResponse response)
      throws IOException, ServletException {
   if (useEncoding || (request.getCharacterEncoding() == null)) {
      if (encoding != null)
         // Set the same character encoding for the request and the
         // response
         request.setCharacterEncoding(encoding);
      // response.setCharacterEncoding(encoding);
   }//  www  .ja  v  a  2 s.  co  m
}