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.vlabs.umt.ui.actions.ManageUserAction.java

public ActionForward loadUser(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    BeanFactory factory = (BeanFactory) getServlet().getServletContext()
            .getAttribute(Attributes.APPLICATION_CONTEXT_KEY);
    UserService us = (UserService) factory.getBean("UserService");
    String username = request.getParameter("q");
    User u = us.getUserByUid(Integer.valueOf(username));

    //JSON/*  w  ww .j  a  va2  s. c  o  m*/
    StringBuffer buffer = new StringBuffer();
    buffer.append("[{");
    buffer.append("username:'" + u.getCstnetId() + "'");
    buffer.append(",truename:'" + u.getTrueName() + "'");
    buffer.append(",email:'" + u.getCstnetId() + "'");
    buffer.append("}]");

    //
    response.setCharacterEncoding("UTF-8");
    PrintWriter writer = response.getWriter();
    writer.write(buffer.toString());
    writer.flush();
    writer.close();
    return null;
}

From source file:ch.ralscha.extdirectspring.controller.RouterController.java

@SuppressWarnings("resource")
public void writeJsonResponse(HttpServletResponse response, Object responseObject, Class<?> jsonView,
        boolean streamResponse, boolean isMultipart) throws IOException {

    ObjectMapper objectMapper = this.configurationService.getJsonHandler().getMapper();

    if (isMultipart) {
        response.setContentType(RouterController.TEXT_HTML.toString());
        response.setCharacterEncoding(RouterController.TEXT_HTML.getCharset().name());

        ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
        bos.write("<html><body><textarea>".getBytes(ExtDirectSpringUtil.UTF8_CHARSET));

        String responseJson;//from w  w  w.  j a  va  2 s  .com
        if (jsonView == null) {
            responseJson = objectMapper.writeValueAsString(responseObject);
        } else {
            responseJson = objectMapper.writerWithView(jsonView).writeValueAsString(responseObject);
        }

        responseJson = responseJson.replace("&quot;", "\\&quot;");
        bos.write(responseJson.getBytes(ExtDirectSpringUtil.UTF8_CHARSET));

        String frameDomain = this.configurationService.getConfiguration().getFrameDomain();
        String frameDomainScript = "";
        if (frameDomain != null) {
            frameDomainScript = String
                    .format(this.configurationService.getConfiguration().getFrameDomainScript(), frameDomain);
        }
        bos.write(("</textarea>" + frameDomainScript + "</body></html>")
                .getBytes(ExtDirectSpringUtil.UTF8_CHARSET));

        response.setContentLength(bos.size());
        FileCopyUtils.copy(bos.toByteArray(), response.getOutputStream());
    } else {

        response.setContentType(APPLICATION_JSON.toString());
        response.setCharacterEncoding(APPLICATION_JSON.getCharset().name());

        ServletOutputStream outputStream = response.getOutputStream();

        if (!streamResponse) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(bos, JsonEncoding.UTF8);

            if (jsonView == null) {
                objectMapper.writeValue(jsonGenerator, responseObject);
            } else {
                objectMapper.writerWithView(jsonView).writeValue(jsonGenerator, responseObject);
            }

            response.setContentLength(bos.size());
            outputStream.write(bos.toByteArray());
            jsonGenerator.close();
        } else {
            JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(outputStream,
                    JsonEncoding.UTF8);
            if (jsonView == null) {
                objectMapper.writeValue(jsonGenerator, responseObject);
            } else {
                objectMapper.writerWithView(jsonView).writeValue(jsonGenerator, responseObject);
            }
            jsonGenerator.close();
        }

        outputStream.flush();
    }
}

From source file:com.exilant.exility.core.HttpRequestHandler.java

/***
 * We accept only POST requests.//from  ww  w.j a  va  2  s. c  o  m
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // set the character encoding...
    request.setCharacterEncoding(CommonFieldNames.CHAR_ENCODING);
    response.setCharacterEncoding(CommonFieldNames.CHAR_ENCODING);
    response.setHeader(CACHE_CONTROL, NO_CACHE);
    try {
        MyAssistant assistant = new MyAssistant(request, response);
        String log = assistant.processRequest();
        System.out.println("Log \n" + log);
    } catch (Exception e) {

        /**
         * TODO : we have to use error reporting infrastructure and probably
         * create a ticket...
         */
        System.out.println("Server exception " + e.getMessage());
        e.printStackTrace();
        response.getWriter().write(
                "Sorry, we are unable to service your request due to an internal error on the server. Some one is looking at the issue right away. Please retry your request after some time.");
    }
}

From source file:it.jugpadova.controllers.EventController.java

@RequestMapping
public ModelAndView rss(HttpServletRequest req, HttpServletResponse res) throws Exception {
    try {/*from w  ww.ja va  2 s . c om*/
        EventSearch eventSearch = buildEventSearch(req);
        List<Event> events = eventBo.search(eventSearch);
        Channel channel = feedsBo.buildChannel(events, Utilities.getBaseUrl(req), buildChannelLink(req));
        // flush it in the res
        WireFeedOutput wfo = new WireFeedOutput();
        res.setHeader("Cache-Control", "no-store");
        res.setHeader("Pragma", "no-cache");
        res.setDateHeader("Expires", 0);
        res.setContentType("text/xml");
        res.setCharacterEncoding("UTF-8");
        ServletOutputStream resOutputStream = res.getOutputStream();
        wfo.output(channel, new OutputStreamWriter(resOutputStream, "UTF-8"));
        resOutputStream.flush();
        resOutputStream.close();
    } catch (Exception exception) {
        logger.error("Error producing RSS", exception);
        throw exception;
    }
    return null;
}

From source file:com.suntek.gztpb.controller.DriverLicenseController.java

@RequestMapping(value = "upload.htm", method = RequestMethod.POST) //
public String handleFormUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    String inputName = request.getParameter("name");
    CommonsMultipartFile mFile = (CommonsMultipartFile) multipartRequest.getFile(inputName);

    if (!mFile.isEmpty()) {
        String path = this.servletContext.getRealPath("/picUpload/");
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = format.format(new Date()) + "_" + mFile.getOriginalFilename();
        File fold = new File(path);
        if (!fold.exists()) {
            fold.mkdir();/*from   ww  w .j a va  2 s. c  om*/
        }
        path = path + "\\" + fileName; // ?

        File file = new File(path); // 

        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();

        try {
            mFile.getFileItem().write(file); // 
            out.write("<script>parent.callback(1,'" + fileName + "','" + inputName + "')</script>");
        } catch (Exception e) {
            logger.error(e.getMessage());
            out.write("<script>parent.callback(0)</script>");
        }
    }
    return null;
}

From source file:com.ewcms.content.vote.web.ResultServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletOutputStream out = null;/*from ww  w. ja  v a  2 s. c  om*/
    StringBuffer output = new StringBuffer();
    try {
        String id = req.getParameter("id");

        if (!id.equals("") && StringUtils.isNumeric(id)) {
            Long questionnaireId = new Long(id);

            ServletContext application = getServletContext();
            WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application);
            QuestionnaireService questionnaireService = (QuestionnaireService) wac
                    .getBean("questionnaireService");

            String ipAddr = req.getRemoteAddr();

            output = questionnaireService.getQuestionnaireResultClientToHtml(questionnaireId,
                    getServletContext().getContextPath(), ipAddr);
        }
        out = resp.getOutputStream();
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");
        out.write(output.toString().getBytes("UTF-8"));
        out.flush();
    } finally {
        if (out != null) {
            out.close();
            out = null;
        }
    }
}

From source file:mml.handler.get.MMLCorformHandler.java

/**
* Handle the request/*w  w  w .java 2  s .  c  o  m*/
* @param request the request
* @param response the response
* @param urn the remaining urn of the request
* @throws MMLException 
*/
public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException {
    try {
        String jBody = null;
        docid = request.getParameter(JSONKeys.DOCID);
        if (docid != null) {
            Connection conn = Connector.getConnection();
            String jStr = conn.getFromDb(Database.CORTEX, docid);
            JSONObject jObj = (JSONObject) JSONValue.parse(jStr);
            String style = (String) jObj.get(JSONKeys.STYLE);
            jStr = conn.getFromDb(Database.CORFORM, style);
            if (jStr == null)
                jBody = getDefaultResource(docid);
            else {
                jObj = (JSONObject) JSONValue.parse(jStr);
                jBody = (String) jObj.get(JSONKeys.BODY);
            }
        } else
            jBody = getDefaultResource("default");
        setEncoding(request);
        response.setContentType("text/plain");
        response.setCharacterEncoding(encoding);
        response.getWriter().println(jBody);
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

From source file:jp.terasoluna.fw.web.struts.actions.FileDownloadUtil.java

/**
 * uEU_E??[h?B/* w w  w  .  j  a v a  2s  .com*/
 * @param downloadObject _E??[h??B
 * @param request NGXg?B
 * @param response X|X?B
 *
 * @throws IOException _E??[h?oO????B
 */
public static void download(AbstractDownloadObject downloadObject, HttpServletRequest request,
        HttpServletResponse response, boolean forceDownload) throws IOException {

    // downloadObjectnull???A??
    if (downloadObject == null) {
        if (log.isWarnEnabled()) {
            log.warn("No download object.");
        }
        return;
    }

    // wb_??B
    Map<String, List<String>> additionalHeaders = downloadObject.getAdditionalHeaders();

    // wb_?null???A??
    if (additionalHeaders == null) {
        if (log.isWarnEnabled()) {
            log.warn("Header must not be null.");
        }
        return;
    }

    // wb_??B
    Set<Entry<String, List<String>>> entrySet = additionalHeaders.entrySet();
    for (Entry<String, List<String>> entry : entrySet) {
        String headerName = entry.getKey();
        List<String> headerValues = entry.getValue();

        // wb_?L?[lXgnull???A??
        if (headerValues == null || headerName == null) {
            if (log.isWarnEnabled()) {
                log.warn("Header name and value must not be null.");
            }
            return;
        }
        for (String headerValue : headerValues) {
            // wb_?lnull
            if (headerValue == null) {
                headerValue = "";
            }
            response.addHeader(headerName, headerValue);
        }
    }

    // GR?[fBO?
    String charSet = downloadObject.getCharset();
    if (StringUtils.isNotEmpty(charSet)) {
        response.setCharacterEncoding(downloadObject.getCharset());
    }

    // Reg^Cv?
    String contentType = downloadObject.getContentType();
    if (StringUtils.isNotEmpty(contentType)) {
        response.setContentType(downloadObject.getContentType());
    }

    // f?[^TCY?
    int contentLength = downloadObject.getLengthOfData();
    if (contentLength > 0) {
        response.setContentLength(downloadObject.getLengthOfData());
    }

    // t@C????A??B
    // ?????B
    String name = downloadObject.getName();
    if (name != null) {
        name = encoder.encode(name, request, response);
    } else {
        name = encoder.encode("", request, response);
    }
    setFileName(response, name, forceDownload);

    InputStream inputStream = downloadObject.getStream();
    OutputStream outputStream = null;

    try {
        // _E??[h???s
        outputStream = response.getOutputStream();
        Streams.copy(inputStream, outputStream, false);
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (outputStream != null) {
            outputStream.flush();
            outputStream.close();
        }
    }

}

From source file:mml.handler.get.MMLGetDialectHandler.java

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException {
    try {//from w w  w  .  j a  v a 2s .c o  m
        docid = request.getParameter(Params.DOCID);
        version1 = request.getParameter(Params.VERSION1);
        if (version1 != null && version1.length() > 0 && !docid.endsWith(version1))
            docid += version1;
        // look for a dialect file with the full path then
        // if not found progressively pop off segments from the end
        String res = null;
        Connection conn = Connector.getConnection();
        while (res == null && docid.length() > 0) {
            res = conn.getFromDb(Database.DIALECTS, docid);
            if (res == null)
                docid = Utils.chomp(docid);
        }
        if (res == null)
            res = DEFAULT_DIALECT;
        JSONObject jObj = (JSONObject) JSONValue.parse(res);
        String dialect = (String) jObj.get(JSONKeys.BODY);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().write(dialect);
    } catch (Exception e) {
        throw new MMLException(e);
    }
}