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:com.ankang.report.main.Report.java

@RequestMapping(value = "showReport")
public void showReport(String modulName, String methodName, HttpServletResponse response) throws IOException {

    MonitorView monitorView = matchMonitorView(modulName, methodName);
    monitorView.setModul(modulName);/*from  w  w  w  .j av  a 2  s.c o  m*/
    monitorView.setMethod(methodName);

    JSONArray json = new JSONArray();

    json.add(monitorView);

    response.setCharacterEncoding("utf-8");
    response.getWriter().print(json);
}

From source file:cn.vlabs.umt.ui.servlet.AddClientServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String act = req.getParameter("act");
    resp.setCharacterEncoding("utf-8");
    if ("add".equals(act)) {
        addClient(req, resp);//from www  . j  a  v a  2s.c o m
        return;
    } else if ("clientIdUsed".equals(act)) {
        clientIdUsed(req, resp);
        return;
    } else if ("update".equals(act)) {
        updateClient(req, resp);
        return;
    } else if ("getClientInfo".equals(act)) {
        getClientInfo(req, resp);
        return;
    } else if ("delete".equals(act)) {
        deleteClient(req, resp);
    } else if ("refresh".equals(act)) {
        refreshClient(req);
    }
    req.setAttribute("clients", getAllClient());
    req.getRequestDispatcher("/admin/oauthaddcliend.jsp").forward(req, resp);
}

From source file:com.mirth.connect.server.servlets.WebStartServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // MIRTH-1745
    response.setCharacterEncoding("UTF-8");

    try {/*from   ww w.  java 2  s  .  c om*/
        response.setContentType("application/x-java-jnlp-file");
        response.setHeader("Pragma", "no-cache");
        PrintWriter out = response.getWriter();
        Document jnlpDocument = null;

        if (request.getServletPath().equals("/webstart.jnlp") || request.getServletPath().equals("/webstart")) {
            jnlpDocument = getAdministratorJnlp(request);
        } else if (request.getServletPath().equals("/webstart/extensions")) {
            String extensionPath = StringUtils.removeEnd(StringUtils.removeStart(request.getPathInfo(), "/"),
                    ".jnlp");
            jnlpDocument = getExtensionJnlp(extensionPath);
        }

        DocumentSerializer docSerializer = new DocumentSerializer(true);
        docSerializer.toXML(jnlpDocument, out);
    } catch (RuntimeIOException rio) {
        logger.debug(rio);
    } catch (Throwable t) {
        logger.error(ExceptionUtils.getStackTrace(t));
        throw new ServletException(t);
    }
}

From source file:it.unimi.di.big.mg4j.query.GenericItem.java

public Template handleRequest(final HttpServletRequest request, final HttpServletResponse response,
        final Context context) throws Exception {
    if (request.getParameter("doc") != null) {
        DocumentCollection collection = (DocumentCollection) getServletContext().getAttribute("collection");
        response.setContentType(request.getParameter("m"));
        response.setCharacterEncoding("UTF-8");
        final Document document = collection.document(Long.parseLong(request.getParameter("doc")));
        final DocumentFactory factory = collection.factory();
        final ObjectArrayList<String> fields = new ObjectArrayList<String>();
        final int numberOfFields = factory.numberOfFields();

        LOGGER.debug("ParsingFactory declares " + numberOfFields + " fields");

        for (int field = 0; field < numberOfFields; field++) {
            if (factory.fieldType(field) != FieldType.TEXT)
                fields.add(StringEscapeUtils.escapeHtml(document.content(field).toString()));
            else//from ww  w  .  java  2  s  .  com
                fields.add(StringEscapeUtils.escapeHtml(IOUtils.toString((Reader) document.content(field)))
                        .replaceAll("\n", "<br>\n"));
        }
        context.put("title", document.title());
        context.put("fields", fields);
        context.put("factory", factory);
        return getTemplate("it/unimi/dsi/mg4j/query/generic.velocity");
    }

    return null;
}

From source file:com.laxser.blitz.web.instruction.TextInstruction.java

@Override
public void doRender(Invocation inv) throws Exception {
    if (StringUtils.isEmpty(text)) {
        return;/*from   ww  w .  j  a  va 2  s. co m*/
    }

    if (logger.isDebugEnabled()) {
        logger.debug("trying to render text:" + text);
    }

    HttpServletResponse response = inv.getResponse();
    String oldEncoding = response.getCharacterEncoding();
    if (StringUtils.isBlank(oldEncoding) || oldEncoding.startsWith("ISO-")) {
        String encoding = inv.getRequest().getCharacterEncoding();
        Assert.isTrue(encoding != null);
        response.setCharacterEncoding(encoding);
        if (logger.isDebugEnabled()) {
            logger.debug("set response.characterEncoding by default:" + response.getCharacterEncoding());
        }
    }

    if (response.getContentType() == null) {
        response.setContentType("text/html");
        if (logger.isDebugEnabled()) {
            logger.debug("set response content-type by default: " + response.getContentType());
        }
    }
    sendResponse(response, text);
}

From source file:com.primeleaf.krystal.web.view.WebView.java

public void init(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws Exception {
    httpRequest.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING);
    httpResponse.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING);
    request = httpRequest;/*from   w  ww.j a va2  s  .  c  om*/
    response = httpResponse;
    request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING);
    response.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING);

    response.setContentType("text/html; charset=utf-8");
    response.setHeader("Cache-Control", "no-cache");
    out = httpResponse.getWriter();
    session = (HttpSession) httpRequest.getSession();
    out = httpResponse.getWriter();

    loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);

}

From source file:com.xdtech.report.controller.ReadReportController.java

@RequestMapping(params = "exportReport")
public void exportReport(HttpServletRequest request, HttpServletResponse response, Long configId,
        String exportType) {//w w w.  j a  va 2 s .c o  m
    try {
        ConfigItem configItem = configService.loadConfigItem(configId);
        if (StringUtils.isNotBlank(configItem.getXml())) {
            response.setCharacterEncoding("UTF-8");
            if (IReportLoader.PDF_TYPE.equals(exportType)) {
                response.setContentType("application/pdf");
                String filename = System.currentTimeMillis() + ".pdf";
                response.setHeader("Content-disposition", "attachment;filename=" + filename);
            } else if (IReportLoader.EXCEL_TYPE.equals(exportType)) {
                response.setContentType("application/vnd.ms-excel");
                String filename = System.currentTimeMillis() + ".xls";
                response.setHeader("Content-disposition", "attachment;filename=" + filename);
            } else if (IReportLoader.CVS_TYPE.equals(exportType)) {
                response.setContentType("application/vnd.ms-csv");
                String filename = System.currentTimeMillis() + ".csv";
                response.setHeader("Content-disposition", "attachment;filename=" + filename);
            } else if (IReportLoader.TXT_TYPE.equals(exportType)) {
                response.setContentType("text/plain");
                String filename = System.currentTimeMillis() + ".txt";
                response.setHeader("Content-disposition", "attachment;filename=" + filename);
            } else if (IReportLoader.HTML_TYPE.equals(exportType)) {
                response.setContentType("text/html");
                String filename = System.currentTimeMillis() + ".html";
                response.setHeader("Content-disposition", "attachment;filename=" + filename);
            } else {
                response.setContentType("application/pdf");
                String filename = System.currentTimeMillis() + ".pdf";
                response.setHeader("Content-disposition", "attachment;filename=" + filename);
            }

            ServletOutputStream ouputStream = response.getOutputStream();
            ReportTemplateLoader.configIReportXml(configItem.getXml(), exportType, ouputStream);
        } else {
            response.getWriter().write(
                    "??http://localhost:81/xdtech-web/readReport.do?exportReport&configId=2&exportType=excel");
        }
    } catch (Exception e) {
        System.out.println("daochu ");
    }

}

From source file:com.linuxbox.enkive.web.search.AdvancedSearch.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    JSONObject jsonData = new JSONObject();
    JSONObject jsonResult = new JSONObject();

    res.setCharacterEncoding("UTF-8");
    try {/*from  w w  w.  ja v a  2 s.  c  om*/
        // because of the JavaScript SpringSurf bridge we need to look out
        // for parameters that contain the string "null" rather than the
        // null value, so we call cleanGetParameter
        String sender = WebScriptUtils.cleanGetParameter(req, SENDER_PARAMETER);
        String recipient = WebScriptUtils.cleanGetParameter(req, RECIPIENT_PARAMETER);
        String dateEarliestString = WebScriptUtils.cleanGetParameter(req, DATE_EARLIEST_PARAMETER);
        String dateLatestString = WebScriptUtils.cleanGetParameter(req, DATE_LATEST_PARAMETER);
        String subject = WebScriptUtils.cleanGetParameter(req, SUBJECT_PARAMETER);
        String messageId = WebScriptUtils.cleanGetParameter(req, MESSAGE_ID_PARAMETER);
        String contentCriteriaString = WebScriptUtils.cleanGetParameter(req, CONTENT_PARAMETER);

        HashMap<String, String> searchFields = new HashMap<String, String>();
        searchFields.put(SENDER_PARAMETER, sender);
        searchFields.put(RECIPIENT_PARAMETER, recipient);
        searchFields.put(DATE_EARLIEST_PARAMETER, dateEarliestString);
        searchFields.put(DATE_LATEST_PARAMETER, dateLatestString);
        searchFields.put(SUBJECT_PARAMETER, subject);
        searchFields.put(MESSAGE_ID_PARAMETER, messageId);
        searchFields.put(CONTENT_PARAMETER, contentCriteriaString);

        SearchQuery query = null;

        try {
            Workspace workspace = workspaceService.getActiveWorkspace(authenticationService.getUserName());
            String queryUUID = workspace.getLastQueryUUID();
            if (queryUUID != null) {
                query = searchQueryBuilder.getSearchQuery(queryUUID);
            }
            if (query != null && query.matches(searchFields)) {
                Future<SearchQuery> resultFuture = searchService.updateSearchAsync(query);
                query = resultFuture.get(searchTimeoutSeconds, TimeUnit.SECONDS);
            } else {
                // Didn't match; make sure we run query below
                query = null;
            }
        } catch (Exception e) {
            // Fall through and make a new result
        }

        if (query == null) {
            try {
                Future<SearchQuery> resultFuture = searchService.searchAsync(searchFields);
                query = resultFuture.get(searchTimeoutSeconds, TimeUnit.SECONDS);
                // catch various kinds of exceptions, including cancellations
            } catch (MessageSearchException e) {
                query = null;
            } catch (InterruptedException e) {
                query = null;
            } catch (ExecutionException e) {
                query = null;
            } catch (TimeoutException e) {
                query = null;
            }
        }

        if (query != null) {
            jsonData.put(QUERY_TAG, query.toJson());
            WebPageInfo pageInfo = new WebPageInfo();
            if (LOGGER.isInfoEnabled())
                LOGGER.info("search results are complete");

            final List<MessageSummary> messageSummaries = archiveService
                    .retrieveSummary(query.getResult().getMessageIds().values());

            pageInfo.setItemTotal(messageSummaries.size());
            @SuppressWarnings("unchecked")
            final JSONArray jsonMessageSummary = SearchResultsBuilder
                    .getMessageListJSON((List<MessageSummary>) pageInfo.getSubList(messageSummaries));
            jsonData.put(RESULTS_TAG, jsonMessageSummary);

            jsonData.put(STATUS_ID_TAG, COMPLETE_STATUS_VALUE);
            jsonData.put(WebConstants.ITEM_TOTAL_TAG, pageInfo.getItemTotal());

            jsonResult.put(PAGING_LABEL, pageInfo.getPageJSON());
        } else {
            if (LOGGER.isInfoEnabled())
                LOGGER.info("search results are not ready yet");
            // note that the content portion of the query will have been cleaned
            // up by the parsing of the contentCriteriaString
            JSONObject jsonQuery = searchQueryToJson(null, false, false);
            jsonQuery.put(SEARCH_PARAMETER_TAG, searchParametersToJson(sender, recipient, dateEarliestString,
                    dateLatestString, subject, messageId, contentCriteriaString));
            jsonData.put(QUERY_TAG, jsonQuery);
            jsonData.put(STATUS_ID_TAG, RUNNING_STATUS_VALUE);
        }
        jsonResult.put(DATA_TAG, jsonData);
    } catch (JSONException e) {
        LOGGER.error("JSONException", e);
        respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, res);
        throw new EnkiveServletException("Unable to serialize JSON");
    } catch (CannotRetrieveException e) {
        LOGGER.fatal("could not retrieve message summaries from archive", e);
        respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, res);
        throw new EnkiveServletException("Unable to access repository");
    } finally {
        setResponse(res, jsonResult);
    }
}

From source file:com.sshdemo.common.report.manage.web.TextReportAction.java

public void download() {
    PrintWriter pw = null;//from   w ww  . j  a  va 2 s  .c  o m
    InputStream in = null;
    try {
        if (getTextId() != null) {
            TextReport report = reportFac.findTextReportById(getTextId());
            if (report.getTextEntity() != null && report.getTextEntity().length != 0) {
                String fileName = String.valueOf(report.getName());
                fileName = URLEncoder.encode(fileName, "UTF-8");
                //fileName = new String(fileName.getBytes("GBK"), "ISO8859-1");

                HttpServletResponse response = ServletActionContext.getResponse();
                response.setContentType("application/jrxml");
                response.setCharacterEncoding("UTF-8");
                response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".jrxml");

                byte[] bytes = new byte[report.getTextEntity().length];
                bytes = report.getTextEntity();

                pw = response.getWriter();

                response.setContentLength(bytes.length);
                in = new ByteArrayInputStream(bytes);
                int len = 0;
                while ((len = in.read()) > -1) {
                    pw.write(len);
                }
                pw.flush();
            } else {
                this.addActionError("?");
            }
        } else {
            this.addActionError("?");
        }
    } catch (IOException e) {
    } finally {
        if (pw != null) {
            try {
                pw.close();
                pw = null;
            } catch (Exception e) {
            }
        }
        if (in != null) {
            try {
                in.close();
                in = null;
            } catch (Exception e) {
            }
        }
    }
}

From source file:jp.mathes.databaseWiki.web.DbwServlet.java

private void handleHttp(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    resp.setCharacterEncoding("UTF-8");
    String user = null;//from  w  w  w. j  a  v  a2s .  c o  m
    String password = null;
    if (req.getHeader("Authorization") != null) {
        String[] split = req.getHeader("Authorization").split(" ");
        String userpw = "";
        if (split.length > 1) {
            userpw = new String(Base64.decodeBase64(split[1]));
        }
        user = StringUtils.substringBefore(userpw, ":");
        password = StringUtils.substringAfter(userpw, ":");
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType("application/xhtml+xml; charset=UTF-8");
        try {
            this.handleAction(req, resp, user, password);
        } catch (InstantiationException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Could not instantiate database backend: " + e.getMessage());
        } catch (IllegalAccessException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Illegal Access: " + e.getMessage());
        } catch (ClassNotFoundException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Could not find database backend: " + e.getMessage());
        } catch (TemplateException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Template error: " + e.getMessage());
        } catch (BackendException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database error: " + e.getMessage());
        } catch (PluginException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Rendering error: " + e.getMessage());
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        resp.setHeader("WWW-Authenticate", "Basic realm=\"databaseWiki\"");
    }
}