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.marvelution.gadgets.sonar.servlet.SonarMakeRequestServlet.java

/**
 * {@inheritDoc}//ww  w. j a  v a 2s.co m
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String requestUrl = req.getParameter("url");
    String requestType = req.getParameter("type");
    if (StringUtils.isNotBlank(requestUrl)) {
        logger.debug("Got a makeRequest request for " + requestUrl);
        try {
            URI uri = new URI(requestUrl);
            Sonar sonar = new Sonar(new HttpClient4Connector(getHost(uri)));
            String json = sonar.getConnector().execute(new QueryWrapper(uri));
            resp.setCharacterEncoding("UTF-8");
            if (StringUtils.isBlank(requestType) || "json".equalsIgnoreCase(requestType)) {
                resp.setContentType(MediaType.APPLICATION_JSON);
            } else {
                resp.setContentType(MediaType.APPLICATION_XML);
            }
            resp.getWriter().write(json);
            resp.getWriter().flush();
        } catch (ConnectionException e) {
            throw new ServletException(
                    "Failed to execute query. Please verify the correctness of the query and "
                            + "that the Sonar server is up.",
                    e);
        } catch (URISyntaxException e) {
            throw new ServletException("Invalid query url specified", e);
        }
    }
}

From source file:eionet.webq.web.controller.FileDownloadController.java

/**
 * Sets content type header to response.
 *
 * @param response    http response//from  ww w .j  a v  a 2  s . c o  m
 * @param contentType content type
 */
private void setContentType(HttpServletResponse response, MediaType contentType) {
    if (contentType != null) {
        response.setContentType(contentType.toString());
        response.setCharacterEncoding("utf-8");
    }
}

From source file:dk.itst.oiosaml.sp.configuration.ConfigurationHandler.java

private void sendResponse(HttpServletResponse response, String res) throws IOException {
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(res);//w  w  w .  ja va2  s. co  m
}

From source file:com.wx.CustomerWXServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// w ww  .  ja  v a2  s  .  c  om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String sToken = "testToken";
    String sCorpID = "wxe706b25abb1216c0";
    String sEncodingAESKey = "AWdjbue1y51jzlAMwBCSm9GDt7zW6zuIbNqGEPcqsRR";
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    String msg_signature = request.getParameter("msg_signature");
    String timestamp = request.getParameter("timestamp");
    String nonce = request.getParameter("nonce");
    InputStream inputStream = request.getInputStream();
    String postData = IOUtils.toString(inputStream, "UTF-8");
    System.out.println(postData);
    String msg = "";
    WXBizMsgCrypt wxcpt = null;
    try {
        wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
        //?
        msg = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, postData);
    } catch (AesException e) {
        e.printStackTrace();
    }
    System.out.println("msg=" + msg);
    BaseMessage respMessage = CoreService.processRequest(msg, classService);
    String resMsg = null;
    /** if (request.getSession().getAttribute("accessToken") == null) {
    try {
        String accessToken = CoreService.getAccessToken(config.getInitParameter("corpid"), config.getInitParameter("corpsecret"));
        request.getSession().setAttribute("accessToken", accessToken);
        QyWxURLUtil.applyAccessToken(accessToken);
    } catch (Exception ex) {
        Logger.getLogger(TestWXServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
     }
     **/
    /**
     * UploadMediaReturnMessage uploadMediaReturnMsg; try {
     * uploadMediaReturnMsg = WXUtils.send("image",
     * "/root/WXMedia/anranhui520/1.jpg");
     * if("null".equals(uploadMediaReturnMsg.getErrcode())){
     * System.out.println("Media_id:"+uploadMediaReturnMsg.getMedia_id());
     * }else{ System.out.println("Upload error
     * message:"+uploadMediaReturnMsg.getErrmsg()+" error
     * code:"+uploadMediaReturnMsg.getErrcode());
     *
     * }
     * } catch (Exception ex) {
     * Logger.getLogger(TestWXServlet.class.getName()).log(Level.SEVERE,
     * null, ex); }
    *
     */
    if (respMessage instanceof TextMessage) {
        /*try {
        TextMessage txtMsg = (TextMessage) respMessage;
                
        String command = txtMsg.getContent();
                
        CheckCommandReturnMessage ccReturnMsg = CMDService.processCheckingCommand(command);
        Set<UserInfo> userInfoSet = ccReturnMsg.getUserInfos();
        UserInfo userif = null;
        for (UserInfo userInfo : userInfoSet) {
            userif = userInfo;
        }
                
        System.out.println("msgContent:" + ccReturnMsg.getContent());
        System.out.println("weixinid:" + userif.getWeixinid());
                
        try {
                
            UploadMediaReturnMessage uploadMediaReturnMsg = null;
            try {
                QRCodeGenerator.encode(ccReturnMsg.getContent(), "/root/WXMedia/"+userif.getWeixinid());
                        
                uploadMediaReturnMsg = WXUtils.send("image", "/root/WXMedia/"+userif.getWeixinid()+"/qrcode.jpg");
                if ("null".equals(uploadMediaReturnMsg.getErrcode())) {
                    System.out.println("Media_id:" + uploadMediaReturnMsg.getMedia_id());
                } else {
                    System.out.println("Upload error message:" + uploadMediaReturnMsg.getErrmsg() + " error code:" + uploadMediaReturnMsg.getErrcode());
                
                }
            } catch (Exception ex) {
                Logger.getLogger(CustomerWXServlet.class.getName()).log(Level.SEVERE, null, ex);
            }*/

        /**
         * TextSendMessage textMsg = new TextSendMessage(); String
         * msgtxt = ccReturnMsg.getContent();
         * textMsg.setTextContent(msgtxt);
         * textMsg.setMsgtype("text");
         * textMsg.setTouser(userif.getWeixinid());
         * textMsg.setAgentid(Long.parseLong(config.getInitParameter("checkingAgentId"))); *
         */
        /*  ImageSendMessage imgMsg = new ImageSendMessage();
          imgMsg.setImageMedia(uploadMediaReturnMsg.getMedia_id());
          imgMsg.setMsgtype("image");
          imgMsg.setTouser(userif.getWeixinid());
          imgMsg.setAgentid(Long.parseLong(config.getInitParameter("checkingAgentId")));
                
          AccessTokenReturnMessage returnMsg = CoreService.sendMessage(imgMsg);
        } catch (Exception ex) {
          Logger.getLogger(CustomerWXServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        } catch (Exception ex) {
        Logger.getLogger(CustomerWXServlet.class.getName()).log(Level.SEVERE, null, ex);
        }*/
    } else if (respMessage instanceof NewsMessage) {
        System.out.println("enter NewsMessage.");
        NewsMessage newsMsg = (NewsMessage) respMessage;
        resMsg = MessageUtil.newsMessageToXml(newsMsg);
        System.out.println("ResMsg:" + resMsg);
    }
    PrintWriter out = response.getWriter();
    out.print(resMsg);
    out.flush();
    out.close();

}

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

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

    if (!BasicAuth.hasAuthorizationHeader(req)) {
        BasicAuth.setRequestAuthorizationHeaders(res, "Repository");
        return;//from www. j av  a  2  s  .c  om
    }

    // Use user id from credentials as default userid.
    SimpleCredentials creds = BasicAuth.parseAuthorizationHeader(req);
    String userId = creds.getUserID();
    log.debug("userId={}", userId);

    Session jcrSession = null;
    Session impersonateSession = null;
    Map<String, Object> templateParams = new HashMap<String, Object>();

    String defaultJcrPath = "/";
    templateParams.put("jcrUserId", userId);
    templateParams.put("jcrPath", defaultJcrPath);

    try {
        renderTemplatePage(req, res, getRenderTemplate(req), templateParams);
    } catch (TemplateException te) {
        log.warn("Failed to render freemarker template.", te);
    }
}

From source file:com.haulmont.cuba.web.sys.CubaApplicationServlet.java

public void handleServerError(HttpServletRequest req, HttpServletResponse resp, Throwable exception)
        throws IOException {
    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    resp.setContentType("text/html");
    resp.setCharacterEncoding(StandardCharsets.UTF_8.name());

    PrintWriter out = resp.getWriter();

    try {//  www . j  a va2 s .c o m
        String errorHtml = prepareErrorHtml(req, exception);
        out.print(errorHtml);
    } catch (Throwable t) {
        log.error("Unable to show error page", t);
        out.print(INTERNAL_ERROR_TEXT);
    }
}

From source file:com.googlecode.psiprobe.controllers.sql.QueryHistoryItemController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    int sqlId = ServletRequestUtils.getIntParameter(request, "sqlId", -1);

    HttpSession sess = request.getSession(false);

    if (sess != null) {
        DataSourceTestInfo sessData = (DataSourceTestInfo) sess
                .getAttribute(DataSourceTestInfo.DS_TEST_SESS_ATTR);

        if (sessData != null) {
            List queryHistory = sessData.getQueryHistory();

            if (queryHistory != null) {
                try {
                    String sql = (String) queryHistory.get(sqlId);
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().print(sql);
                } catch (IndexOutOfBoundsException e) {
                    logger.error("Cannot find a query history entry for history item id = " + sqlId);
                }/*from w ww  .  j  a v  a  2  s  .  c  om*/
            }
        }
    }

    return null;
}

From source file:xx.tream.chengxin.ms.action.TrainReportAction.java

@RequestMapping({ "/exportIncomeCommonReport" })
public String exportIncomeCommonReport(ModelMap modelMap, HttpServletRequest request,
        HttpServletResponse response, FormMap formMap) throws IOException {
    Map<String, Object> queryMap = formMap.getFormMap();
    OutputStream os = response.getOutputStream();
    response.reset();// w  w w.j  a  v a  2 s .  c  om
    response.setCharacterEncoding("UTF-8");
    String title = "" + getDateFile() + ".xls";
    response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(title, "UTF-8"));
    response.setContentType("application/vnd.ms-excel");
    HSSFWorkbook workbook = new HSSFWorkbook();
    this.reportService.incomeCommonReport(workbook, queryMap);
    workbook.write(os);
    os.flush();
    os.close();
    return "train/exportIncomeCommonReport";
}

From source file:xx.tream.chengxin.ms.action.TrainReportAction.java

/**
 * //w ww . j  a  v  a2  s. c  o  m
 * @param modelMap
 * @param request
 * @param response
 * @param formMap
 * @return
 * @throws IOException
 */
@RequestMapping({ "/exportPayoutCommonReport" })
public String exportPayoutCommonReport(ModelMap modelMap, HttpServletRequest request,
        HttpServletResponse response, FormMap formMap) throws IOException {
    Map<String, Object> queryMap = formMap.getFormMap();
    OutputStream os = response.getOutputStream();
    response.reset();
    response.setCharacterEncoding("UTF-8");
    String title = "" + getDateFile() + ".xls";
    response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(title, "UTF-8"));
    response.setContentType("application/vnd.ms-excel");
    HSSFWorkbook workbook = new HSSFWorkbook();
    this.reportService.payoutCommonReport(workbook, queryMap);
    workbook.write(os);
    os.flush();
    os.close();
    return "train/exportPayoutCommonReport";
}

From source file:de.kp.ames.web.core.service.ServiceImpl.java

public void sendResponse(byte[] bytes, String mimetype, HttpServletResponse response) throws IOException {

    response.setStatus(HttpServletResponse.SC_OK);
    response.setCharacterEncoding("UTF-8");

    response.setContentType(mimetype);//from  w  w  w  .j  ava 2 s .  c  o m

    response.setContentLength(bytes.length);

    OutputStream os = response.getOutputStream();

    os.write(bytes);
    os.close();

}