Example usage for javax.servlet.http HttpServletResponse setCharacterEncoding

List of usage examples for javax.servlet.http HttpServletResponse setCharacterEncoding

Introduction

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

Prototype

public void setCharacterEncoding(String charset);

Source Link

Document

Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.

Usage

From source file:cn.leancloud.diamond.server.controller.AdminController.java

@RequestMapping(params = "method=batchQuery", method = RequestMethod.POST)
public String batchQuery(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("dataIds") String dataIds, @RequestParam("group") String group, ModelMap modelMap) {

    response.setCharacterEncoding("UTF-8");

    // , 500, sdk, sdk500
    if (StringUtils.isBlank(dataIds)) {
        throw new IllegalArgumentException("?, dataIds?");
    }/* w ww .j a  v a  2 s.c o m*/
    // group??????, ??for?
    if (StringUtils.isBlank(group)) {
        throw new IllegalArgumentException("?, group???");
    }

    // dataId
    String[] dataIdArray = dataIds.split(Constants.WORD_SEPARATOR);
    group = group.trim();

    List<ConfigInfoEx> configInfoExList = new ArrayList<ConfigInfoEx>();
    for (String dataId : dataIdArray) {
        ConfigInfoEx configInfoEx = new ConfigInfoEx();
        configInfoEx.setDataId(dataId);
        configInfoEx.setGroup(group);
        configInfoExList.add(configInfoEx);
        try {
            if (StringUtils.isBlank(dataId)) {
                configInfoEx.setStatus(Constants.BATCH_QUERY_NONEXISTS);
                configInfoEx.setMessage("dataId is blank");
                continue;
            }

            // ?
            ConfigInfo configInfo = this.configService.findConfigInfo(dataId, group);
            if (configInfo == null) {
                // , ?, ??, ???
                configInfoEx.setStatus(Constants.BATCH_QUERY_NONEXISTS);
                configInfoEx.setMessage("query data does not exist");
            } else {
                // , ?, ?, ??
                String content = configInfo.getContent();
                configInfoEx.setContent(content);
                configInfoEx.setStatus(Constants.BATCH_QUERY_EXISTS);
                configInfoEx.setMessage("query success");
            }
        } catch (Exception e) {
            log.error("?, dataId, dataId=" + dataId + ",group=" + group, e);
            // , ??
            configInfoEx.setStatus(Constants.BATCH_OP_ERROR);
            configInfoEx.setMessage("query error: " + e.getMessage());
        }
    }

    String json = null;
    try {
        json = JSONUtils.serializeObject(configInfoExList);
    } catch (Exception e) {
        log.error("??, json=" + json, e);
    }
    modelMap.addAttribute("json", json);

    return "/admin/config/batch_result";
}

From source file:com.taobao.diamond.server.controller.AdminController.java

@RequestMapping(params = "method=batchQuery", method = RequestMethod.POST)
public String batchQuery(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("dataIds") String dataIds, @RequestParam("group") String group, ModelMap modelMap) {

    response.setCharacterEncoding("GBK");

    // , 500, sdk, sdk500
    if (StringUtils.isBlank(dataIds)) {
        throw new IllegalArgumentException(", dataIds");
    }/*from w w  w .ja  v a2 s.c om*/
    // group, for
    if (StringUtils.isBlank(group)) {
        throw new IllegalArgumentException(", group");
    }

    // dataId
    String[] dataIdArray = dataIds.split(Constants.WORD_SEPARATOR);
    group = group.trim();

    List<ConfigInfoEx> configInfoExList = new ArrayList<ConfigInfoEx>();
    for (String dataId : dataIdArray) {
        ConfigInfoEx configInfoEx = new ConfigInfoEx();
        configInfoEx.setDataId(dataId);
        configInfoEx.setGroup(group);
        configInfoExList.add(configInfoEx);
        try {
            if (StringUtils.isBlank(dataId)) {
                configInfoEx.setStatus(Constants.BATCH_QUERY_NONEXISTS);
                configInfoEx.setMessage("dataId is blank");
                continue;
            }

            // 
            ConfigInfo configInfo = this.configService.findConfigInfo(dataId, group);
            if (configInfo == null) {
                // , , , 
                configInfoEx.setStatus(Constants.BATCH_QUERY_NONEXISTS);
                configInfoEx.setMessage("query data does not exist");
            } else {
                // , , , 
                String content = configInfo.getContent();
                configInfoEx.setContent(content);
                configInfoEx.setStatus(Constants.BATCH_QUERY_EXISTS);
                configInfoEx.setMessage("query success");
            }
        } catch (Exception e) {
            log.error(", dataId, dataId=" + dataId + ",group=" + group, e);
            // , 
            configInfoEx.setStatus(Constants.BATCH_OP_ERROR);
            configInfoEx.setMessage("query error: " + e.getMessage());
        }
    }

    String json = null;
    try {
        json = JSONUtils.serializeObject(configInfoExList);
    } catch (Exception e) {
        log.error(", json=" + json, e);
    }
    modelMap.addAttribute("json", json);

    return "/admin/config/batch_result";
}

From source file:com.mengka.diamond.server.controller.AdminController.java

@RequestMapping(params = "method=batchQuery", method = RequestMethod.POST)
public String batchQuery(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("dataIds") String dataIds, @RequestParam("group") String group, ModelMap modelMap) {

    response.setCharacterEncoding("utf-8");

    // , 500, sdk, sdk500
    if (StringUtils.isBlank(dataIds)) {
        throw new IllegalArgumentException("?, dataIds?");
    }/*from w w  w.jav  a  2 s .  c om*/
    // group??????, ??for?
    if (StringUtils.isBlank(group)) {
        throw new IllegalArgumentException("?, group???");
    }

    // dataId
    String[] dataIdArray = dataIds.split(Constants.WORD_SEPARATOR);
    group = group.trim();

    List<ConfigInfoEx> configInfoExList = new ArrayList<ConfigInfoEx>();
    for (String dataId : dataIdArray) {
        ConfigInfoEx configInfoEx = new ConfigInfoEx();
        configInfoEx.setDataId(dataId);
        configInfoEx.setGroup(group);
        configInfoExList.add(configInfoEx);
        try {
            if (StringUtils.isBlank(dataId)) {
                configInfoEx.setStatus(Constants.BATCH_QUERY_NONEXISTS);
                configInfoEx.setMessage("dataId is blank");
                continue;
            }

            // ?
            ConfigInfo configInfo = this.configService.findConfigInfo(dataId, group);
            if (configInfo == null) {
                // , ?, ??, ???
                configInfoEx.setStatus(Constants.BATCH_QUERY_NONEXISTS);
                configInfoEx.setMessage("query data does not exist");
            } else {
                // , ?, ?, ??
                String content = configInfo.getContent();
                configInfoEx.setContent(content);
                configInfoEx.setStatus(Constants.BATCH_QUERY_EXISTS);
                configInfoEx.setMessage("query success");
            }
        } catch (Exception e) {
            log.error("?, dataId, dataId=" + dataId + ",group=" + group, e);
            // , ??
            configInfoEx.setStatus(Constants.BATCH_OP_ERROR);
            configInfoEx.setMessage("query error: " + e.getMessage());
        }
    }

    String json = null;
    try {
        json = JSONUtils.serializeObject(configInfoExList);
    } catch (Exception e) {
        log.error("??, json=" + json, e);
    }
    modelMap.addAttribute("json", json);

    return "/admin/config/batch_result";
}

From source file:com.github.matthesrieke.realty.CrawlerServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/html");

    String itemsMarkup = createGroupedItemsMarkup();
    String content = this.listTemplate.toString().replace("${entries}", itemsMarkup).replace("${meta}",
            createMetaMarkup());/*from  w  w w.ja v a  2 s.  c om*/

    byte[] bytes = content.getBytes("UTF-8");

    resp.setContentLength(bytes.length);
    resp.setCharacterEncoding("UTF-8");
    resp.setStatus(HttpStatus.SC_OK);

    resp.getOutputStream().write(bytes);
    resp.getOutputStream().flush();
}

From source file:edu.education.ucsb.muster.MusterServlet.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*from   ww  w  .  j  a  va 2s. c om*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (reloadFilesHaveChanged()) {
        log("Reinitializing...");
        init();
    }

    // Set headers and get writer
    response.setCharacterEncoding("UTF-8");
    PrintWriter writer = response.getWriter();
    response.setContentType("text/javascript");

    // purge the cache if we're asked to (purge_cache URI is called)
    if (purgeCacheRequested(request.getRequestURI())) {
        purgeCache();
        writer.println("Cache purged");
        return;
    }

    String database = request.getParameter("database");
    String select = request.getParameter("select");
    String from = request.getParameter("from");
    String where = request.getParameter("where");
    String order = request.getParameter("order");
    String callback = request.getParameter("callback");
    String nocache = request.getParameter("nocache");
    long limit = Long.MAX_VALUE;
    try {
        limit = Long.parseLong(request.getParameter("limit"));
    } catch (Exception e) {
        // That's ok. Just use the default -1.
    }

    // output status if requested
    boolean callbackSet = callback != null; // true if callback is set
    if (statusRequested(request.getRequestURI(), callbackSet)) {
        writer.println(getStatus());
        return;
    }

    boolean noCache = false;

    if (nocache != null && nocache.toLowerCase().equals("true")) {
        noCache = true;
    }

    // Construct query string
    String query = "SELECT " + select + " FROM " + from + ((where == null) ? "" : " WHERE " + where)
            + ((order == null) ? "" : " ORDER BY " + order);

    String cacheKey = query + Long.toString(limit);

    // Attempt to retrieve query from cache. If it's expired or not present,
    // perform the query and cache the result.
    String out = null;

    // Just in case the servlet ever decides that the cache thread should be
    // killed check to make sure it's there before we get started.
    try {
        cache.getThread();
    } catch (NullPointerException e) {
        addException(e, "Cache thread died!");
        cache = getCache();
    }

    // If nocache is requested, make sure to get a fresh copy of this record
    if (noCache) {
        try {
            cache.remove(cacheKey);
        } catch (JustacheKeyNotFoundException e) {
            // That's ok. You can request nocache even if nothing is cached.
        }
    }

    try {
        out = cache.get(cacheKey);
    } catch (JustacheKeyNotFoundException e) {
        try {
            out = getOutputAsJson(database, query, limit);
            cache.put(cacheKey, out);
        } catch (SQLException e1) {
            addException(e1, "SQLException: " + query);
        } catch (NullPointerException e1) {
            addException(e1, "NullPointerException: " + query);
        }
    }

    // Write response
    writer.println(callback + '(' + out + ')');

}

From source file:mercury.Controller.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.debug("processRequest start: " + this.getMemoryInfo());

    String submitButton = null;/*from  w  w  w .  jav  a 2  s.  c  o m*/
    String jspURL = null;

    HashMap<String, String> requestParametersHash = null;

    String thisPage = null;
    String lastVisitedPage = null;

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");

    try {
        //--- gets all request parameters, either multipart or not
        this.putAllRequestParametersInAttributes(request);
        requestParametersHash = (HashMap<String, String>) request.getAttribute("REQUEST_PARAMETERS");

        //--- sets the last visited page to errorJsp if it is the first time the controller runs
        lastVisitedPage = (String) request.getSession().getAttribute("LAST_VISITED_PAGE");

        if (StringUtils.isBlank(lastVisitedPage)) {
            lastVisitedPage = errorJsp;
            jspURL = lastVisitedPage;
            request.getSession().setAttribute("LAST_VISITED_PAGE", jspURL);
        }

        submitButton = requestParametersHash.get("submitButton");
        thisPage = requestParametersHash.get("thisPage");

        AuthorizationPoints atps = (AuthorizationPoints) request.getSession().getAttribute("LOGGED_USER_ATPS");
        if (atps == null) {
            atps = new AuthorizationPoints(null);
            request.getSession().setAttribute("LOGGED_USER_ATPS", atps);
        }

        AuthorizationBO authBO = new AuthorizationBO();
        String handlerName = Controller.targetHandlers.getProperty(thisPage);

        if (submitButton.equals("i18n")) {
            request.getSession().setAttribute("I18N", requestParametersHash.get("i18n"));
            jspURL = lastVisitedPage;

        } else if (authBO.authorize(atps, handlerName, submitButton)) {
            BaseHandler handler = (BaseHandler) Class.forName(handlerName).newInstance();
            jspURL = handler.process(request, response);

        } else {
            Dialog.showWarning(request, "ERROR_NO_PERMISSION");
            jspURL = lastVisitedPage;
        }
    } catch (ClassNotFoundException e) {
        System.out.println("====== [mercury.Controller.processRequest()] Exception 1: " + e);
        Dialog.showError(request, "DIALOG_VOID");
        jspURL = lastVisitedPage;

    } catch (ExceptionUser e) {
        System.out.println("====== [mercury.Controller.processRequest()] Exception 2: " + e.getKeyText());
        Dialog.showError(request, e.getKeyText());
        jspURL = lastVisitedPage;

    } catch (DAOException e) {
        System.out.println("====== [mercury.Controller.processRequest()] Exception 3: " + e);
        Dialog.showError(request, "ERROR_DATABASE");
        jspURL = lastVisitedPage;

    } catch (Exception e) {
        System.out.println("====== [mercury.Controller.processRequest()] Exception 4: " + e);
        e.printStackTrace();
        Dialog.showError(request, "DIALOG_VOID");
        jspURL = lastVisitedPage;

    } finally {
        if (jspURL == null || jspURL.equals("")) {
            jspURL = errorJsp;
            request.getSession().setAttribute("LAST_VISITED_PAGE", jspURL);
            return;
        } else if (jspURL.equals("x-download")) {
            return;
        } else if (jspURL.equals("x-json")) {
            return;
        } else {
            request.getSession().setAttribute("LAST_VISITED_PAGE", jspURL);
            request.getRequestDispatcher(jspURL).forward(request, response);
            return;
        }
    }
}

From source file:edu.umd.lib.servlets.permissions.PermissionsServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // explicitly set character encoding
    req.setCharacterEncoding("UTF-8");
    res.setCharacterEncoding("UTF-8");

    SimpleCredentials creds = BasicAuth.parseAuthorizationHeader(req);
    String credentialsId = creds.getUserID();
    log.debug("credentialsId={}", credentialsId);

    String jcrUserId = req.getParameter("jcrUserId");
    String jcrPath = req.getParameter("jcrPath");
    log.info("jcrUserId={}, jcrPath={}", jcrUserId, jcrPath);

    Session jcrSession = null;/*from   w  w w  .  ja  v a2s  .  co m*/
    Session impersonateSession = null;
    Map<String, Object> templateParams = new HashMap<String, Object>();

    try {
        if (creds.getUserID() == null || creds.getUserID().length() == 0) {
            jcrSession = repository.login();
        } else {
            jcrSession = repository.login(creds);
        }
        log.debug("jcrSession={}", jcrSession);
        User user = ((HippoSession) jcrSession).getUser();

        if (user.isSystemUser()) {
            final InetAddress address = InetAddress.getByName(req.getRemoteHost());
            if (!address.isAnyLocalAddress() && !address.isLoopbackAddress()) {
                throw new LoginException();
            }
        }

        templateParams.put("jcrSession", jcrSession);
        templateParams.put("jcrUserId", jcrUserId);
        templateParams.put("jcrPath", jcrPath);

        Credentials impersonateCredentials = new SimpleCredentials(jcrUserId, "".toCharArray());
        impersonateSession = jcrSession.impersonate(impersonateCredentials);
        Privilege[] privileges = getPrivileges(impersonateSession, jcrPath);
        log.info("========= " + ((SimpleCredentials) impersonateCredentials).getUserID() + " ==============");
        Map<String, String> privilegesMap = new HashMap<>();
        for (Privilege p : privileges) {
            privilegesMap.put(p.getName(), "true");
            log.info("p=" + p.getName());
        }
        templateParams.put("privilegesMap", privilegesMap);
        String[] allPermissions = { "jcr:read", "jcr:write", "hippo:author", "hippo:editor", "hippo:admin",
                "jcr:setProperties", "jcr:setAccessControlPolicy", "jcr:addChildNodes",
                "jcr:getAccessControlPolicy", "jcr:removeChildNodes" };

        templateParams.put("allPermissions", allPermissions);

    } catch (LoginException ex) {
        BasicAuth.setRequestAuthorizationHeaders(res, "Repository");
        log.error("Error logging in to repository", ex);
    } catch (Exception ex) {
        templateParams.put("exception", ex);
        log.error("Error retrieving permissions", ex);
    } finally {
        try {
            if (jcrSession != null) {
                renderTemplatePage(req, res, getRenderTemplate(req), templateParams);
            }
        } catch (Exception te) {
            log.warn("Failed to render freemarker template.", te);
        } finally {
            if (jcrSession != null) {
                jcrSession.logout();
            }

            if (impersonateSession != null) {
                impersonateSession.logout();
            }
        }
    }

}

From source file:org.jtwig.mvc.JtwigView.java

@Override
protected void renderMergedTemplateModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // Adding model information
    JtwigModelMap modelMap = new JtwigModelMap().add(model)
            .add("beans", new BeanResolver(getApplicationContext())).add("theme", getThemeName(request))
            .add("request", request);

    Object token = request.getAttribute(SPRING_CSRF);
    if (token != null) {
        modelMap.add("csrf", token);
    } else {//  w w w. jav a  2 s  .c  o  m
        modelMap.add("csrf", Undefined.UNDEFINED);
    }

    if (this.getEncoding() != null) {
        response.setCharacterEncoding(this.getEncoding());
    }

    getCompiledJtwigTemplate().render(RenderContext.create(getEnvironment(), modelMap,
            getViewResolver().functionResolver(), response.getOutputStream()));

    response.getOutputStream().flush();
    response.getOutputStream().close();
}

From source file:com.eviware.soapui.impl.wsdl.mock.WsdlMockRunner.java

public void printOkXmlResult(HttpServletResponse response, String content) throws IOException {
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("text/xml");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().print(content);
}

From source file:com.epam.wilma.test.server.PerformanceTestHandler.java

@Override
public void handle(final String path, final Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    if (PATH_TO_HANDLE.equals(path)) {
        double rnd = random.nextDouble();
        byte[] responseBodyAsBytes;
        if (rnd > 0.98) {
            responseBodyAsBytes = xmlMaxAsBytes;
        } else if (rnd > 0.3) {
            responseBodyAsBytes = xmlLargeAsBytes;
        } else if (rnd > 0.1) {
            responseBodyAsBytes = xmlSmallAsBytes;
        } else {//w  w  w.ja  v  a 2  s .co  m
            responseBodyAsBytes = xmlMinAsBytes;
        }
        response.setContentType("application/fastinfoset");
        response.setCharacterEncoding("UTF-8");
        response.getOutputStream().write(responseBodyAsBytes);
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);
        response.getOutputStream().close();
    }
}