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.senseidb.servlet.AbstractSenseiClientServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (req.getCharacterEncoding() == null)
        req.setCharacterEncoding("UTF-8");
    resp.setContentType("application/json; charset=utf-8");
    resp.setCharacterEncoding("UTF-8");

    resp.setHeader("Access-Control-Allow-Origin", "*");
    resp.setHeader("Access-Control-Allow-Methods", "GET, POST");
    resp.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, X-Requested-With, Accept");

    if (null == req.getPathInfo() || "/".equalsIgnoreCase(req.getPathInfo())) {
        handleSenseiRequest(req, resp, _senseiBroker);
    } else if ("/get".equalsIgnoreCase(req.getPathInfo())) {
        handleStoreGetRequest(req, resp);
    } else if ("/sysinfo".equalsIgnoreCase(req.getPathInfo())) {
        handleSystemInfoRequest(req, resp);
    } else if (req.getPathInfo().startsWith("/admin/jmx/")) {
        handleJMXRequest(req, resp);/* w  ww  . jav  a2  s. c  o  m*/
    } else if (req.getPathInfo().startsWith("/federatedBroker/")) {
        if (federatedBroker == null) {
            try {
                writeEmptyResponse(req, resp, new SenseiError("The federated broker wasn't initialized",
                        ErrorType.FederatedBrokerUnavailable));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        handleSenseiRequest(req, resp, federatedBroker);
    } else {
        handleSenseiRequest(req, resp, _senseiBroker);
    }
}

From source file:org.frontcache.FrontCacheEngine.java

private void writeResponse(WebResponse webResponse, RequestContext context) throws Exception {

    // there is no body to send
    if (null == webResponse.getContent()) {
        return;//ww  w .j  av  a  2s. c om
    }

    HttpServletResponse servletResponse = context.getResponse();
    servletResponse.setCharacterEncoding("UTF-8");
    OutputStream outStream = servletResponse.getOutputStream();
    try {
        byte[] body = webResponse.getContent();
        FCUtils.writeResponse(new ByteArrayInputStream(body), outStream);
    } finally {
        try {
            outStream.flush();
            outStream.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    return;
}

From source file:com.hp.action.CalendarAction.java

public String edit() throws IOException {
    HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
            .get(ServletActionContext.HTTP_REQUEST);
    HttpServletResponse response = (HttpServletResponse) ActionContext.getContext()
            .get(ServletActionContext.HTTP_RESPONSE);

    HttpSession session = request.getSession();

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

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    String id = StringUtils.trimToEmpty(request.getParameter("id"));
    String contributor = StringUtils.trimToEmpty(request.getParameter("contributor"));
    String support = StringUtils.trimToEmpty(request.getParameter("support"));
    String mission = StringUtils.trimToEmpty(request.getParameter("mission"));
    String report = StringUtils.trimToEmpty(request.getParameter("report"));
    String statusParam = StringUtils.trimToEmpty(request.getParameter("status"));

    int stt = 0;// w w  w.ja v  a2  s  .  com
    int status = -1;
    try {
        stt = Integer.parseInt(id);
        status = Integer.parseInt(statusParam);

    } catch (Exception e) {
        e.printStackTrace();
        response.getOutputStream().write("Li khng xc nh, hy th li sau!".getBytes("UTF-8"));
        return null;
    }

    Calendar calendar = null;
    if (stt > 0)
        calendar = calendarDAO.getCalendar(stt);

    if (calendar != null && calendar.getStatus() != 2) {
        calendar.setContributor(contributor);
        calendar.setMission(mission);
        calendar.setReport(report);
        calendar.setSupport(support);

        calendar.setUpdatedTime(Timestamp.valueOf(df.format(new Date())));

        if (status != -1)
            calendar.setStatus(status);

        if (calendarDAO.update(calendar)) {
            response.getOutputStream().write("Cp nht lch cng tc thnh cng".getBytes("UTF-8"));
            return null;
        }
    }

    response.getOutputStream()
            .write("Cp nht lch cng tc tht bi, hy th li sau!".getBytes("UTF-8"));

    return null;
}

From source file:edu.monash.merc.struts2.dispatcher.RssResult.java

public void execute(ActionInvocation actionInvocation) throws Exception {
    if (StringUtils.isBlank(feedName)) {
        String msg = ("Required parameter with the name [" + feedName + "] not found. "
                + "Make sure you have the param tag set.");
        logger.error(msg);//from   w ww  . j  av a 2 s . co m
        throw new IllegalArgumentException(msg);
    }

    //set the content type for response
    HttpServletResponse response = (HttpServletResponse) actionInvocation.getInvocationContext()
            .get(StrutsStatics.HTTP_RESPONSE);
    if (StringUtils.isBlank(mimeType)) {
        mimeType = DEFAULT_MIME_TYPE;
    }
    response.setContentType(mimeType);

    SyndFeed feed = (SyndFeed) actionInvocation.getStack().findValue(feedName);
    if (feed != null) {
        if (StringUtils.isBlank(encoding)) {
            encoding = feed.getEncoding();
        }
        //set the response encoding
        if (StringUtils.isNotBlank(encoding)) {
            response.setCharacterEncoding(encoding);
        }
        //set the feed type
        if (StringUtils.isNotBlank(feedType)) {
            feed.setFeedType(feedType);
        }
        SyndFeedOutput feedOutput = new SyndFeedOutput();
        //we will writer to write out to the outpustream
        Writer out = null;
        try {
            out = response.getWriter();
            feedOutput.output(feed, out);
        } catch (Exception ex) {
            logger.error("Could not write the feed: " + ex.getMessage());
            throw new RuntimeException(ex);
            // throw new RuntimeException("Could not write the feed: " + ex.getMessage());
        } finally {
            if (out != null) {
                out.close();
            }
        }
    } else {
        String errormsg = "Did not find the object on the stack with name '" + feedName + "'";
        logger.error(errormsg);
        throw new RuntimeException(errormsg);
    }
}

From source file:cn.vlabs.umt.ui.actions.ManageApplicationAction.java

public ActionForward loadApp(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    String idStr = request.getParameter("q");
    AppService service = getAppService();
    int appid = Integer.parseInt(idStr);
    Application app = service.getApplication(appid);
    String json = "";
    if (app != null) {
        json = "[{" + "appname:'" + escape(app.getName()) + "'" + ",url:'" + escape(app.getUrl()) + "'"
                + ",description:'" + escape(app.getDescription()) + "'" + ",serverType:'"
                + escape(app.getServerType()) + "'" + ",allowOperate:" + app.isAllowOperate() + "}]";
    }//from  w  ww .  jav a  2 s .  c o m
    response.setCharacterEncoding("UTF-8");
    PrintWriter writer = response.getWriter();
    writer.write(json);
    writer.close();
    writer.flush();
    return null;
}

From source file:io.resthelper.RestHelperController.java

@RequestMapping(value = "/rest-helper/apis", method = RequestMethod.GET)
public void apis(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("package") String packageName) throws IOException {
    String requestURI = request.getRequestURI();
    String contextName = requestURI.substring(0, requestURI.indexOf("/rest-helper"));

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

    if (packageName == null || packageName.length() == 0) {
        out.flush();/*from  w w w  .j  a v  a  2s .  c  o m*/
        return;
    }

    if (!restHelperService.isValidIp(request)) {
        throw new NotAllowIpException();
    }

    List<RestApi> apiList = restHelperService.getApiList(packageName);

    out.println("<!DOCTYPE html>");
    out.println("<html>");
    out.println("<head>");
    out.println("<meta charset=\"UTF-8\">");
    out.println("<title>API LIST</title>");
    out.println("<style type='text/css'>");
    out.println("body {");
    out.println("font-family: monospace;");
    out.println("}");
    out.println("</style>");
    out.println("<script type=\"text/javascript\">");
    out.println("function bodyonload() {");
    out.println("   top.apiFrame.location = \"" + contextName + "/rest-helper/detail?package=" + packageName
            + "\";");
    out.println("}");
    out.println("</script>");
    out.println("</head>");
    out.println("<body onload=\"bodyonload()\">");
    out.println("<h3>API List</h3>");
    out.println("<ul>");

    for (RestApi api : apiList) {
        out.println("<li><a href=\"" + contextName + "/rest-helper/detail?package=" + packageName + "#"
                + api.getApiKey() + "\" target=\"apiFrame\">" + api.getUriPattern() + " (" + api.getHttpMethod()
                + ")</a></li>");
    }

    out.println("</ul>");
    out.println("</body></html>");

    out.flush();
}

From source file:tw.com.sbi.product.controller.Product.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

    ProductService productService = null;

    String groupId = request.getSession().getAttribute("group_id").toString();
    String action = request.getParameter("action");

    logger.debug("Action:" + action);

    if ("selectAll".equals(action)) {
        try {//from  ww  w  .j av  a2 s . com
            productService = new ProductService();
            List<ProductVO> list = productService.selectByGroupId(groupId);

            Gson gson = new Gson();
            String jsonStrList = gson.toJson(list);
            response.getWriter().write(jsonStrList);

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if ("search".equals(action)) {
        try {
            String productSpec = request.getParameter("product_spec");
            logger.debug("productSpec:" + productSpec);
            productService = new ProductService();
            List<ProductVO> list = productService.getProductBySpec(groupId, productSpec);

            Gson gson = new Gson();
            String jsonStrList = gson.toJson(list);
            response.getWriter().write(jsonStrList);

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if ("insert".equals(action)) {
        try {
            String productSpec = request.getParameter("product_spec");
            String photo = request.getParameter("photo");
            String seed = request.getParameter("seed");

            logger.debug("productSpec:" + productSpec);
            logger.debug("photo:" + photo);
            logger.debug("seed:" + seed);

            productService = new ProductService();
            List<ProductVO> list = productService.addProduct(groupId, productSpec, photo, seed);

            Gson gson = new Gson();
            String jsonStrList = gson.toJson(list);
            response.getWriter().write(jsonStrList);

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if ("update".equals(action)) {
        logger.debug("enter product update method");
        try {
            String productId = request.getParameter("product_id");
            String productSpec = request.getParameter("product_spec");
            String photo = request.getParameter("photo");
            String seed = request.getParameter("seed");

            logger.debug("productId:" + productId);
            logger.debug("productSpec:" + productSpec);
            logger.debug("photo:" + photo);
            logger.debug("seed:" + seed);

            productService = new ProductService();

            List<ProductVO> list = productService.updateProduct(groupId, productId, productSpec, photo, seed);

            Gson gson = new Gson();
            String jsonStrList = gson.toJson(list);
            response.getWriter().write(jsonStrList);
            logger.debug("jsonStrList: " + jsonStrList);

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if ("delete".equals(action)) {
        try {
            String productId = request.getParameter("product_id");

            logger.debug("productId:" + productId);

            productService = new ProductService();

            List<ProductVO> list = productService.deleteProduct(groupId, productId);

            Gson gson = new Gson();
            String jsonStrList = gson.toJson(list);
            response.getWriter().write(jsonStrList);

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if ("gen_identity".equals(action)) {
        try {
            String productId = request.getParameter("product_id");

            logger.debug("productId:" + productId);

            productService = new ProductService();

            List<ProductVO> list = productService.genIdentityID(groupId, productId);

            Gson gson = new Gson();
            String jsonStrList = gson.toJson(list);
            response.getWriter().write(jsonStrList);

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if ("autocomplete_spec".equals(action)) {
        try {
            String term = request.getParameter("term");

            logger.debug("term:" + term);

            productService = new ProductService();
            List<ProductVO> list = productService.getProductBySpec(groupId, term);
            Gson gson = new Gson();
            String jsonStrList = gson.toJson(list);
            response.getWriter().write(jsonStrList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:io.resthelper.RestHelperController.java

@RequestMapping(value = "/rest-helper/packages", method = RequestMethod.GET)
public void packages(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String requestURI = request.getRequestURI();
    String contextName = requestURI.substring(0, requestURI.indexOf("/rest-helper"));

    String[] packages = restHelperService.getBasePackages();

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

    if (packages == null || packages.length == 0) {
        out.flush();/*from w  w w. j ava  2 s  . c om*/
        return;
    }

    if (!restHelperService.isValidIp(request)) {
        throw new NotAllowIpException();
    }

    out.println("<!DOCTYPE html>");
    out.println("<html>");
    out.println("<head>");
    out.println("<meta charset=\"UTF-8\">");
    out.println("<title>Packages</title>");
    out.println("<style type='text/css'>");
    out.println("body {");
    out.println("font-family: monospace;");
    out.println("}");
    out.println("</style>");
    out.println("<script type=\"text/javascript\">");
    out.println("function bodyonload() {");
    out.println("   top.packageFrame.location = \"" + contextName + "/rest-helper/apis?package=" + packages[0]
            + "\";");
    out.println("}");
    out.println("</script>");
    out.println("</head>");
    out.println("<body onload=\"bodyonload()\">");
    out.println("<h3>Packages</h3>");
    out.println("<ul>");

    for (String basePackage : packages) {
        out.println("<li><a href=\"" + contextName + "/rest-helper/apis?package=" + basePackage
                + "\" target=\"packageFrame\">" + basePackage + "</a></li>");
    }

    out.println("</ul>");
    out.println("</body></html>");

    out.flush();
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.mtprofile.MTDetailHandler.java

/**
 * Invokes this PageHandler/*from   www  . j  av a2s.c  o m*/
 * 
 * @param p_pageDescriptor
 *            the page desciptor
 * @param p_request
 *            the original request sent from the browser
 * @param p_response
 *            the original response object
 * @param p_context
 *            context the Servlet context
 */
public void invokePageHandler(WebPageDescriptor p_pageDescriptor, HttpServletRequest p_request,
        HttpServletResponse p_response, ServletContext p_context)
        throws ServletException, IOException, EnvoyServletException {
    MachineTranslateAdapter mta = new MachineTranslateAdapter();
    HttpSession sess = p_request.getSession(false);
    ResourceBundle bundle = PageHandler.getBundle(sess);
    SessionManager sessionMgr = (SessionManager) sess.getAttribute(SESSION_MANAGER);
    // when edit submit
    MachineTranslationProfile mtProfile = (MachineTranslationProfile) sessionMgr
            .getAttribute(MTProfileConstants.MT_PROFILE);
    p_response.setContentType("text/json; charset=utf-8");
    p_response.setCharacterEncoding("utf-8");
    PrintWriter writer = p_response.getWriter();
    String mtId = p_request.getParameter(MTProfileConstants.MT_PROFILE_ID);

    if (StringUtils.isNotEmpty(mtId)) {
        // edit
        mtProfile = MTProfileHandlerHelper.getMTProfileById(mtId);
        p_request.setAttribute("title", bundle.getString("lb_mt_options_edit"));
    } else if (mtProfile == null) {
        // new
        mtProfile = new MachineTranslationProfile();
        mtProfile.setActive(true);
        p_request.setAttribute("title", bundle.getString("lb_mt_options_new"));

    }

    String action = (String) p_request.getParameter(MTProfileConstants.ACTION);
    if (StringUtils.isNotBlank(action)) {
        String engine = p_request.getParameter(MTProfileConstants.MT_ENGINE);

        if (engine != null) {
            mta.setMTCommonOptions(p_request, mtProfile, engine);
        }
        if (MTProfileConstants.CANCEL_ACTION.equals(action)) {
            clearSessionExceptTableInfo(sess, MTProfileConstants.MTP_KEY);
        } else if (MTProfileConstants.CANCEL_MT_OPTIONS_ACTION.equals(action)) {
            clearSessionExceptTableInfo(sess, MTProfileConstants.MTP_KEY);
        } else if (MTProfileConstants.SAVE_MT_OPTIONS_ACTION.equals(action)) {
            // for the ui has a force save flag
            MTProfileHandlerHelper.savemtProfile(mtProfile);
            p_response.sendRedirect("/globalsight/ControlServlet?activityName=mtProfiles");
            return;
        } else if (MTProfileConstants.TEST_MT_OPTIONS_ACTION.equals(action)) {
            try {
                if (MTProfileHandlerHelper.isMtProfileExisted(mtProfile)
                        || StringUtils.isEmpty(mtProfile.getMtProfileName())) {
                    JSONObject jso = new JSONObject();
                    jso.put("ExceptionInfo", "Well:The Name has been in used!");
                    writer.write(jso.toString());
                }
                // if promt and ao will test return false in case not save
                // just for session
                else if (mta.testMTCommonOptions(mtProfile, writer)) {
                    MTProfileHandlerHelper.savemtProfile(mtProfile);
                    JSONObject jso = new JSONObject();
                    jso.put("Info", "saved");
                    writer.write(jso.toString());
                    writer.close();
                }
                sessionMgr.setAttribute(MTProfileConstants.MT_PROFILE, mtProfile);
                writer.close();

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }
            return;
        }
    }
    sessionMgr.setAttribute(MTProfileConstants.MT_PROFILE, mtProfile);
    // Call parent invokePageHandler() to set link beans and invoke JSP
    super.invokePageHandler(p_pageDescriptor, p_request, p_response, p_context);
}

From source file:com.mmj.app.web.controller.user.UserController.java

@RequestMapping(value = "/gozapIdentifyCode")
public ModelAndView gozapIdentifyCode(String t, HttpServletRequest request, HttpServletResponse response) {

    response.setContentType("image/png; charset=utf-8");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control",
            "private, must-revalidate,no-store, no-cache, must-revalidate,post-check=0, pre-check=0");
    response.addHeader("Content-Disposition", "attachment; filename=\"" + "gozapIdentifyCode" + "\"");
    response.setCharacterEncoding("UTF-8");

    final byte[] bytes = WebsiteCheckCodeManager.INSTANCE.create(CookieManagerLocator.get(request, response),
            response);/*www  . j  a  v  a 2  s  .  com*/

    OutputStream os;
    try {
        os = response.getOutputStream();
        IOUtils.write(bytes, os);
        response.flushBuffer();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}