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:net.ymate.module.webproxy.support.DispatchProxyFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    request.setCharacterEncoding(__charsetEncoding);
    response.setCharacterEncoding(__charsetEncoding);
    ////from w  w  w . j a v a 2s.  c o m
    response.setContentType(
            Type.ContentType.HTML.getContentType().concat("; charset=").concat(__charsetEncoding));
    //
    HttpServletRequest _request = new RequestMethodWrapper((HttpServletRequest) request, __requestMethodParam);
    HttpServletResponse _response = (HttpServletResponse) response;
    IRequestContext _requestContext = new DefaultRequestContext(_request, __requestPrefix);
    if (null == __ignorePatern || !__ignorePatern.matcher(_requestContext.getOriginalUrl()).find()) {
        if (StringUtils.isNotBlank(__prefix)
                && !StringUtils.startsWith(_requestContext.getRequestMapping(), __prefix)
                || __doMatchBlacklist(_requestContext.getRequestMapping())) {
            _response = new GenericResponseWrapper(_response);
            GenericDispatcher.create(WebMVC.get()).execute(_requestContext, __filterConfig.getServletContext(),
                    _request, _response);
        } else {
            try {
                YMP.get().getEvents()
                        .fireEvent(new WebProxyEvent(WebProxy.get(), WebProxyEvent.EVENT.REQUEST_RECEIVED)
                                .addParamExtend(IEvent.EVENT_SOURCE, _requestContext));
                //
                String _requestMapping = _requestContext.getRequestMapping();
                if (StringUtils.isNotBlank(__prefix)) {
                    _requestMapping = StringUtils.substringAfter(_requestMapping, __prefix);
                }
                StringBuilder _url = new StringBuilder(WebProxy.get().getModuleCfg().getServiceBaseUrl())
                        .append(_requestMapping);
                if (Type.HttpMethod.GET.equals(_requestContext.getHttpMethod())) {
                    if (StringUtils.isNotBlank(_request.getQueryString())) {
                        _url.append("?").append(_request.getQueryString());
                    }
                }
                WebProxy.get().transmission(_request, _response, _url.toString(),
                        _requestContext.getHttpMethod());
            } catch (Throwable e) {
                _LOG.warn("An exception occurred: ", RuntimeUtils.unwrapThrow(e));
            } finally {
                YMP.get().getEvents()
                        .fireEvent(new WebProxyEvent(WebProxy.get(), WebProxyEvent.EVENT.REQUEST_COMPLETED)
                                .addParamExtend(IEvent.EVENT_SOURCE, _requestContext));
            }
        }
    } else {
        chain.doFilter(_request, _response);
    }
}

From source file:com.zyeeda.framework.web.CharacterEncodingFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    if (this.encoding != null && (this.forceEncoding || StringUtils.isBlank(req.getCharacterEncoding()))) {
        req.setCharacterEncoding(encoding);
        if (this.forceEncoding) {
            res.setCharacterEncoding(this.encoding);
        }/*from  w ww .j a  v  a 2 s  .c  o m*/
    }

    chain.doFilter(req, res);
}

From source file:com.ideabase.repository.server.impl.JettyRepositoryServerImpl.java

private Context setupWebServiceHandler() throws InterruptedException, IOException {
    final String tmpDir = mConfiguration.getProperty(KEY_TMPDIR);
    final File tmpDirFile = new File(tmpDir);
    if (!tmpDirFile.exists()) {
        tmpDirFile.mkdirs();/* w  w  w .j  av a2  s  .  c o  m*/
    }

    final Context context = new Context(mServer, "/", Context.SESSIONS);

    // add jsp support
    context.addServlet(JspServlet.class, "*.jsp");
    context.setBaseResource(Resource.newClassPathResource("webapp"));
    context.addServlet(DefaultServlet.class, "/");

    // add spring servlet
    final ServletHolder servletHolder = new ServletHolder(DispatcherServlet.class) {
        @Override
        public void handle(final ServletRequest pRequest, final ServletResponse pResponse)
                throws ServletException, UnavailableException, IOException {
            pRequest.setCharacterEncoding(ENCODING_UTF);
            pResponse.setCharacterEncoding(ENCODING_UTF);
            super.handle(pRequest, pResponse);
        }
    };
    servletHolder.setInitParameter("contextConfigLocation", "classpath:/applicationContext.xml");
    servletHolder.setName("webservice-action-servlet");
    context.addServlet(servletHolder, "/rest/*");

    // add spring context listener
    context.getInitParams().put("contextConfigLocation", "classpath:/applicationContext.xml");
    context.addEventListener(new ContextLoaderListener());

    // add log4j servlet
    context.addServlet(Log4jConfigServlet.class, "/log4j");

    return context;
}

From source file:com.sinosoft.one.mvc.web.impl.thread.RootEngine.java

/**
 * {@link RootEngine} ?.?.??/*from w w w . ja va2s  .  c  om*/
 * ?;
 * 
 * @return
 * @throws ServletException
 */

public Object execute(Mvc mvc) throws Throwable {

    InvocationBean inv = mvc.getInvocation();
    ServletRequest request = inv.getRequest();
    //
    if (request.getCharacterEncoding() == null) {
        request.setCharacterEncoding("UTF-8");
        if (logger.isDebugEnabled()) {
            logger.debug("set request.characterEncoding by default:" + request.getCharacterEncoding());
        }
    }

    //
    final RequestPath requestPath = inv.getRequestPath();

    // save before include
    if (requestPath.isIncludeRequest()) {
        saveAttributesBeforeInclude(inv);
        // ??include???(Model)
        mvc.addAfterCompletion(new AfterCompletion() {

            public void afterCompletion(Invocation inv, Throwable ex) throws Exception {
                restoreRequestAttributesAfterInclude(inv);
            }
        });
    }

    // ?
    inv.addModel("invocation", inv);
    inv.addModel("ctxpath", requestPath.getCtxpath());

    // instructionactionInstruction(???)
    Object instruction = mvc.doNext();

    if (Thread.currentThread().isInterrupted()) {
        logger.info("stop to render: thread is interrupted");
    } else {
        // flash?Cookie (include?)
        if (!requestPath.isIncludeRequest()) {
            FlashImpl flash = (FlashImpl) inv.getFlash(false);
            if (flash != null) {
                flash.writeNewMessages();
            }
        }

        // ?
        instructionExecutor.render(inv, instruction);
    }
    return instruction;
}

From source file:cn.vlabs.duckling.vwb.VWBFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    request.setCharacterEncoding(encoding);
    response.setCharacterEncoding(encoding);
    ThreadLocalCache.init(100);/*from   w ww. j  a va2s.c om*/
    if (request instanceof HttpServletRequest) {
        HttpServletRequest req = (HttpServletRequest) request;
        String localeString = getLocaleString(req);
        Locale locale = getLocale(localeString);
        WrapperedRequest wrappered;
        if (locale != null) {
            wrappered = new WrapperedRequest(req, (HttpServletResponse) response, locale);
        } else {
            wrappered = new WrapperedRequest(req, (HttpServletResponse) response);
        }
        filterChain.doFilter(wrappered, response);
    }
    ThreadLocalCache.clear();
}

From source file:net.paoding.rose.web.impl.thread.RootEngine.java

/**
 * {@link RootEngine} ?.?.??//from   www. ja  v a  2  s  . c  o m
 * ?;
 * 
 * @param request
 * @param response
 * @return
 * @throws ServletException
 */

@Override
public Object execute(Rose rose) throws Throwable {

    InvocationBean inv = rose.getInvocation();
    ServletRequest request = inv.getRequest();
    //
    if (request.getCharacterEncoding() == null) {
        request.setCharacterEncoding("UTF-8");
        if (logger.isDebugEnabled()) {
            logger.debug("set request.characterEncoding by default:" + request.getCharacterEncoding());
        }
    }

    //
    final RequestPath requestPath = inv.getRequestPath();

    // save before include
    if (requestPath.isIncludeRequest()) {
        saveAttributesBeforeInclude(inv);
        // ??include???(Model)
        rose.addAfterCompletion(new AfterCompletion() {

            @Override
            public void afterCompletion(Invocation inv, Throwable ex) throws Exception {
                restoreRequestAttributesAfterInclude(inv);
            }
        });
    }

    // ?
    inv.addModel("invocation", inv);
    inv.addModel("ctxpath", requestPath.getCtxpath());

    // instructionactionInstruction(???)
    Object instruction = rose.doNext();

    if (Thread.currentThread().isInterrupted()) {
        logger.info("stop to render: thread is interrupted");
    } else {
        // flash?Cookie (include?)
        if (!requestPath.isIncludeRequest()) {
            FlashImpl flash = (FlashImpl) inv.getFlash(false);
            if (flash != null) {
                flash.writeNewMessages();
            }
        }

        // ?
        instructionExecutor.render(inv, instruction);
    }
    return instruction;
}

From source file:com.laxser.blitz.web.impl.thread.RootEngine.java

/**
 * {@link RootEngine} ?.?.??//from w  w w  . ja  v a  2s  .  co  m
 * ?;
 * 
 * @param request
 * @param response
 * @return
 * @throws ServletException
 */

@Override
public Object execute(Blitz blitz) throws Throwable {

    InvocationBean inv = blitz.getInvocation();
    ServletRequest request = inv.getRequest();
    //
    if (request.getCharacterEncoding() == null) {
        request.setCharacterEncoding("UTF-8");
        if (logger.isDebugEnabled()) {
            logger.debug("set request.characterEncoding by default:" + request.getCharacterEncoding());
        }
    }

    //
    final RequestPath requestPath = inv.getRequestPath();

    // save before include
    if (requestPath.isIncludeRequest()) {
        saveAttributesBeforeInclude(inv);
        // ??include???(Model)
        blitz.addAfterCompletion(new AfterCompletion() {

            @Override
            public void afterCompletion(Invocation inv, Throwable ex) throws Exception {
                restoreRequestAttributesAfterInclude(inv);
            }
        });
    }

    // ?
    inv.addModel("invocation", inv);
    inv.addModel("ctxpath", requestPath.getCtxpath());

    // instructionactionInstruction(???)
    Object instruction = blitz.doNext();

    if (Thread.currentThread().isInterrupted()) {
        logger.info("stop to render: thread is interrupted");
    } else {
        // flash?Cookie (include?)
        if (!requestPath.isIncludeRequest()) {
            FlashImpl flash = (FlashImpl) inv.getFlash(false);
            if (flash != null) {
                flash.writeNewMessages();
            }
        }

        // ?
        instructionExecutor.render(inv, instruction);
    }
    return instruction;
}

From source file:com.esoft.yeepay.user.service.impl.YeePayCorpAccountOperation.java

@Override
@Transactional(rollbackFor = Exception.class)
public void receiveOperationS2SCallback(ServletRequest request, ServletResponse response) {

    try {/*from w ww. j a  v a2 s.co m*/
        request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    // ?? xml?
    String notifyxml = request.getParameter("notify");
    // ??
    String sign = request.getParameter("sign");
    boolean flag = CFCASignUtil.isVerifySign(notifyxml, sign);
    if (flag) {
        // ??
        @SuppressWarnings("unchecked")
        Map<String, String> resultMap = Dom4jUtil.xmltoMap(notifyxml);
        String code = resultMap.get("code");
        String message = resultMap.get("message");
        String platformUserNo = resultMap.get("platformUserNo");
        TrusteeshipOperation to = trusteeshipOperationBO.get(YeePayConstants.OperationType.ENTERPRISE_REGISTER,
                platformUserNo, platformUserNo, "yeepay");
        ht.evict(to);
        to = ht.get(TrusteeshipOperation.class, to.getId(), LockMode.UPGRADE);
        to.setResponseTime(new Date());
        to.setResponseData(notifyxml);

        User user = ht.get(User.class, platformUserNo);
        log.info("code:" + code);
        if ("1".equals(code)) {
            if (user != null) {
                TrusteeshipAccount ta = ht.get(TrusteeshipAccount.class, user.getId());
                if (ta == null) {
                    ta = new TrusteeshipAccount();
                    ta.setId(user.getId());
                    ta.setUser(user);
                }
                ta.setAccountId(user.getId());
                ta.setCreateTime(new Date());
                ta.setStatus(TrusteeshipConstants.Status.PASSED);
                ta.setTrusteeship("yeepay");
                ht.saveOrUpdate(ta);
                userBO.removeRole(user, new Role("WAIT_CONFIRM"));
                userBO.addRole(user, new Role("LOANER"));
                // ??
                springSecurityService.refreshLoginUserAuthorities(user.getId());
                to.setStatus(TrusteeshipConstants.Status.PASSED);
                ht.merge(to);
            }
        } else if ("0".equals(code) || "104".equals(code)) {
            to.setStatus(TrusteeshipConstants.Status.REFUSED);
            ht.merge(to);
            userBO.removeRole(user, new Role("WAIT_CONFIRM"));
            // ??
            springSecurityService.refreshLoginUserAuthorities(user.getId());
        } else {
            // 
            throw new RuntimeException(new TrusteeshipReturnException(code + ":" + message));
        }
    }

    try {
        response.getWriter().write("SUCCESS");
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
    }

}

From source file:com.esoft.yeepay.user.service.impl.YeePayCorpAccountOperation.java

@Override
@Transactional(rollbackFor = Exception.class, noRollbackFor = TrusteeshipReturnException.class)
public void receiveOperationPostCallback(ServletRequest request) throws TrusteeshipReturnException {
    try {//from  w  w  w.  ja  v  a  2 s  .  co m
        request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    // ?? xml?
    String respXML = request.getParameter("resp");
    log.debug(respXML.toString());
    // ??
    String sign = request.getParameter("sign");
    boolean flag = CFCASignUtil.isVerifySign(respXML, sign);
    if (flag) {
        // ??
        @SuppressWarnings("unchecked")
        Map<String, String> resultMap = Dom4jUtil.xmltoMap(respXML);
        // ?? userId
        String requestNo = resultMap.get("requestNo").substring(resultMap.get("requestNo").indexOf("a") + 1);
        // ?
        String code = resultMap.get("code");
        String description = resultMap.get("description");
        TrusteeshipOperation to = trusteeshipOperationBO.get(YeePayConstants.OperationType.ENTERPRISE_REGISTER,
                requestNo, requestNo, "yeepay");
        ht.evict(to);
        to = ht.get(TrusteeshipOperation.class, to.getId(), LockMode.UPGRADE);

        to.setResponseTime(new Date());
        to.setResponseData(respXML);
        // ? ????
        User user = ht.get(User.class, requestNo);
        if ("1".equals(code)) {
            if (user != null) {
                TrusteeshipAccount ta = ht.get(TrusteeshipAccount.class, user.getId());
                if (ta == null) {
                    ta = new TrusteeshipAccount();
                    ta.setId(user.getId());
                    ta.setUser(user);
                }
                ta.setAccountId(user.getId());
                ta.setCreateTime(new Date());
                ta.setStatus(TrusteeshipConstants.Status.PASSED);
                ta.setTrusteeship("yeepay");
                ht.saveOrUpdate(ta);
                userBO.removeRole(user, new Role("WAIT_CONFIRM"));
                userBO.addRole(user, new Role("LOANER"));
                // ??
                springSecurityService.refreshLoginUserAuthorities(user.getId());
                to.setStatus(TrusteeshipConstants.Status.PASSED);
                ht.merge(to);
            }
        } else {
            to.setStatus(TrusteeshipConstants.Status.REFUSED);
            ht.merge(to);
            userBO.removeRole(user, new Role("WAIT_CONFIRM"));
            // ??
            springSecurityService.refreshLoginUserAuthorities(user.getId());
            if ("0".equals(code)) {
                throw new TrusteeshipReturnException(description);
            }
            // 
            throw new TrusteeshipReturnException(code + ":" + description);
        }
    }

}

From source file:com.bluexml.xforms.chiba.XFormsFilter.java

@Override
public void doFilter(ServletRequest srvRequest, ServletResponse srvResponse, FilterChain filterChain)
        throws IOException, ServletException {

    //ensure correct Request encoding
    if (srvRequest.getCharacterEncoding() == null) {
        srvRequest.setCharacterEncoding(defaultRequestEncoding);
    }/*from  w  w  w.  ja  v a2 s.c  o  m*/

    HttpServletRequest request = (HttpServletRequest) srvRequest;

    HttpServletResponse response = (HttpServletResponse) srvResponse;
    HttpSession session = request.getSession(true);

    if ("GET".equalsIgnoreCase(request.getMethod()) && request.getParameter("submissionResponse") != null) {
        doSubmissionResponse(request, response);
    } else {

        /* before servlet request */
        if (isXFormUpdateRequest(request)) {
            LOG.info("Start Update XForm");

            try {
                XFormsSession xFormsSession = WebUtil.getXFormsSession(request, session);
                xFormsSession.setRequest(request);
                xFormsSession.setResponse(response);
                xFormsSession.handleRequest();
            } catch (XFormsException e) {
                throw new ServletException(e);
            }
            LOG.info("End Update XForm");
        } else {

            /* do servlet request */
            LOG.info("Passing to Chain");
            BufferedHttpServletResponseWrapper bufResponse = new BufferedHttpServletResponseWrapper(
                    (HttpServletResponse) srvResponse);
            filterChain.doFilter(srvRequest, bufResponse);
            LOG.info("Returned from Chain");

            // response is already committed to the client, so nothing is to
            // be done
            if (bufResponse.isCommitted())
                return;

            //set mode of operation (scripted/nonscripted) by config
            if (this.mode == null)
                this.mode = "true";

            if (this.mode.equalsIgnoreCase("true")) {
                request.setAttribute(WebFactory.SCRIPTED, "true");
            } else if (this.mode.equalsIgnoreCase("false")) {
                request.setAttribute(WebFactory.SCRIPTED, "false");
            }

            /* dealing with response from chain */
            if (handleResponseBody(request, bufResponse)) {
                byte[] data = prepareData(bufResponse);
                if (data.length > 0) {
                    request.setAttribute(WebFactory.XFORMS_INPUTSTREAM, new ByteArrayInputStream(data));
                }
            }

            if (handleRequestAttributes(request)) {
                bufResponse.getOutputStream().close();
                LOG.info("Start Filter XForm");

                XFormsSession xFormsSession = null;
                try {
                    XFormsSessionManager sessionManager = DefaultXFormsSessionManagerImpl
                            .getXFormsSessionManager();
                    xFormsSession = sessionManager.createXFormsSession(request, response, session);
                    xFormsSession.setBaseURI(request.getRequestURL().toString());
                    xFormsSession.setXForms();
                    xFormsSession.init();

                    // FIXME patch for upload
                    XFormsSessionBase xFormsSessionBase = (XFormsSessionBase) xFormsSession;
                    reconfigure(xFormsSessionBase);

                    xFormsSession.handleRequest();
                } catch (Exception e) {
                    LOG.error(e.getMessage(), e);
                    if (xFormsSession != null) {
                        xFormsSession.close(e);
                    }
                    throw new ServletException(e.getMessage());
                }

                LOG.info("End Render XForm");
            } else {
                srvResponse.getOutputStream().write(bufResponse.getData());
                srvResponse.getOutputStream().close();
            }
        }
    }
}