Example usage for javax.servlet.http HttpServletRequest setCharacterEncoding

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

Introduction

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

Prototype

public void setCharacterEncoding(String env) throws UnsupportedEncodingException;

Source Link

Document

Overrides the name of the character encoding used in the body of this request.

Usage

From source file:kr.ac.cau.mecs.cass.servletcontextlistener.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    onServletInit(request, response);// ww  w  .  ja v  a 2 s .  c  o m

    response.setContentType("application/json; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();
    JSONObject jobj = new JSONObject();

    Transaction tx = null;
    Session hsession = HibernateSessionFactory.getSessionFactory().getCurrentSession();

    try {
        tx = hsession.beginTransaction();

        jobj = processGet(hsession, request, response);

        tx.commit();
    } catch (Exception e) {
        jobj.putOpt("error", 1);
        jobj.putOpt("reason", "server transaction error");
        jobj.putOpt("msg", e.getMessage());
        e.printStackTrace();
        if (tx != null && tx.isActive()) {
            try {
                tx.rollback();
            } catch (HibernateException e1) {
                e1.printStackTrace();
            }
        }
    }

    jobj.write(out);
    out.close();

}

From source file:kr.ac.cau.mecs.cass.servletcontextlistener.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    onServletInit(request, response);//  ww  w. j av a  2s. c om

    response.setContentType("application/json; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();
    JSONObject jobj = new JSONObject();

    Transaction tx = null;
    Session hsession = HibernateSessionFactory.getSessionFactory().getCurrentSession();

    try {
        tx = hsession.beginTransaction();

        jobj = processPost(hsession, request, response);

        tx.commit();
    } catch (Exception e) {
        jobj.putOpt("error", 1);
        jobj.putOpt("reason", "server transaction error");
        jobj.putOpt("msg", e.getMessage());

        e.printStackTrace();
        if (tx != null && tx.isActive()) {
            try {
                tx.rollback();
            } catch (HibernateException e1) {
                e1.printStackTrace();
            }
        }
    }

    jobj.write(out);
    out.close();
}

From source file:com.iwebirth.controller.AdminController.java

@RequestMapping(value = { "/delete/{obj_id}" }, method = RequestMethod.POST)
public @ResponseBody AjaxResult deleteRecord(@PathVariable int obj_id, HttpServletRequest request,
        HttpSession session) throws UnsupportedEncodingException {
    LoginStatus status = (LoginStatus) session.getAttribute("login_status");
    if (status == null || !status.getAlive())
        return null;
    request.setCharacterEncoding("utf-8");
    AjaxResult ajaxResult = new AjaxResult(false);
    try {//www .j  a  v  a 2s  .  c o m
        switch (obj_id) {
        case user_id:
            int id = Integer.parseInt(request.getParameter("id"));
            String res = CRUDEvent.getNameByValue(adminService.deleteUserById(id));
            ajaxResult.setResult(res);
            System.out.println(res);
            break;
        case department_id:
            break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ajaxResult;
}

From source file:com.salesmanager.core.security.AuthFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    String url = req.getRequestURI();
    log.debug("Requested URL " + url);

    req.setCharacterEncoding("UTF8");

    // check if user is logged in
    HttpSession session = req.getSession();

    if (bypassUrl(req, resp, chain)) {
        chain.doFilter(request, response);
        return;//ww w. j a  va2  s  .  co m
    }

    if (session == null) {

        String username = getUser(req);

        if (username == null) {// not logged in

            if (!StringUtils.isBlank(req.getParameter("username"))) {// submiting
                // login
                if (url.contains("/logon.action")) {
                    chain.doFilter(request, response);
                    return;
                } else {
                    // resp.sendRedirect(req.getContextPath()+"/index.jsp");
                    resp.sendRedirect(getLogonPage(req));
                    return;
                }
            } else {

                resp.sendRedirect(getLogonPage(req));
                return;
            }

        } else {// logged in, but need to retreive the profile
            if (url.contains("/logon.action")) {
                chain.doFilter(request, response);
                return;
            } else {

                resp.sendRedirect(getLogonPage(req));
                return;
            }
        }
    }

    // check if session is expired

    Object o = session.getAttribute(Constants.CONTEXT);
    if (o == null) {

        String username = getUser(req);

        if (username == null) {// not logged in
            if (!StringUtils.isBlank(req.getParameter("username"))) {// submiting
                // login
                if (url.contains("/logon.action")) {
                    chain.doFilter(request, response);
                    return;
                } else {

                    resp.sendRedirect(getLogonPage(req));
                    return;
                }
            } else {

                resp.sendRedirect(getLogonPage(req));
                return;
            }
        } else {// logged in, but need to retreive the profile
            if (url.contains("/logon.action")) {
                chain.doFilter(request, response);
                return;
            } else {

                resp.sendRedirect(getLogonPage(req));
                return;
            }
        }
    }

    chain.doFilter(request, response);
}

From source file:com.wibidata.shopping.servlet.HomePageServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    request.setCharacterEncoding("UTF-8");

    final Kiji kiji = (Kiji) getServletContext().getAttribute(KijiContextListener.KIJI_ATTRIBUTE);
    final KijiTable categoryTable = kiji.openTable("kiji_shopping_category");

    // Read the products by category.
    KijiTableReader reader = categoryTable.openTableReader();
    KijiRowScanner scanner = null;//from w  ww.j a  v a  2s  . c  o  m
    List<Category> categories = new ArrayList<Category>();
    try {
        KijiDataRequestBuilder drBuilder = KijiDataRequest.builder();
        drBuilder.newColumnsDef().add("related", "product");
        final KijiDataRequest dataRequest = drBuilder.build();

        final KijiScannerOptions scanOptions = new KijiScannerOptions()
                .setStartRow(categoryTable.getEntityId("category:"))
                .setStopRow(categoryTable.getEntityId("category;"));

        scanner = reader.getScanner(dataRequest, scanOptions);
        for (KijiRowData row : scanner) {
            if (row.containsColumn("related", "product")) {
                Category category = Category.fromProducts((Node) row.getMostRecentValue("related", "product"));
                categories.add(category);
            }
        }
    } catch (KijiDataRequestException e) {
        throw new IOException(e);
    } finally {
        ResourceUtils.closeOrLog(scanner);
        ResourceUtils.closeOrLog(reader);
        ResourceUtils.releaseOrLog(categoryTable);
    }
    request.setAttribute("categories", categories);

    // If the user is logged in, read their recent ratings, favorite
    // words, and recommendations.
    if (null != request.getSession().getAttribute("login")) {
        final String login = request.getSession().getAttribute("login").toString();
        final KijiTable userTable = kiji.openTable("kiji_shopping_user");
        final KijiTable productTable = kiji.openTable("kiji_shopping_product");
        try {
            List<ProductRating> ratings = getRecentRatings(userTable, login);
            if (null != ratings) {
                request.setAttribute("recentRatings", ratings);
            }
            List<FavoriteWord> favoriteWords = getFavoriteWords(userTable, login);
            if (null != favoriteWords) {
                request.setAttribute("favoriteWords", favoriteWords);
            }
            List<Product> productRecommendations = getProductRecommendations(userTable, productTable, login);
            if (null != productRecommendations) {
                request.setAttribute("productRecommendations", productRecommendations);
            }
        } finally {
            ResourceUtils.releaseOrLog(productTable);
            ResourceUtils.releaseOrLog(userTable);
        }
    }

    request.getRequestDispatcher("/WEB-INF/view/HomePage.jsp").forward(request, response);
}

From source file:de.tudarmstadt.lt.lm.web.servlet.LanguageModelProviderServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    resp.setContentType("text/html; charset=utf-8");
    PrintWriter w = new PrintWriter(resp.getWriter());
    String plaintext = req.getParameter("plaintext");
    String crawl_uri = req.getParameter("crawluri");
    String lm_key = req.getParameter("lm");
    String inputtype = req.getParameter("inputtype");
    boolean show_all_ngrams = req.getParameter("showall") != null;
    try {// w  ww.j a va2  s .com
        if (lm_key == null) // no parameter set
            show_available(w);
        else
            show(inputtype, lm_key, plaintext, crawl_uri, show_all_ngrams, w);
    } catch (Exception e) {
        w.format("Error %s: %s.", e.getClass().getSimpleName(), e.getMessage());
    }
    w.flush();
    w.close();
}

From source file:org.lareferencia.xoai.controller.LROAIDataProvider.java

@RequestMapping("/{context}")
public String contextAction(Model model, HttpServletRequest request, HttpServletResponse response,
        @PathVariable("context") String xoaiContext) throws IOException, ServletException {
    Context context = null;// w  ww .j a  va2s. c  om
    try {
        request.setCharacterEncoding("UTF-8");
        context = contextService.getContext();

        XOAIManager manager = xoaiManagerResolver.getManager();

        RepositoryConfiguration identify = identifyResolver.getIdentify();

        OAIDataProvider dataProvider = new OAIDataProvider(manager, xoaiContext, identify,
                setRepositoryResolver.getSetRepository(), itemRepositoryResolver.getItemRepository(),
                resumptionTokenFormat);

        OutputStream out = response.getOutputStream();
        OAIRequestParameters parameters = new OAIRequestParameters(buildParametersMap(request));

        response.setContentType("application/xml");
        response.setCharacterEncoding("UTF-8");

        String identification = xoaiContext + parameters.requestID();

        if (cacheService.isActive()) {
            if (!cacheService.hasCache(identification))
                cacheService.store(identification, dataProvider.handle(parameters));

            cacheService.handle(identification, out);
        } else
            dataProvider.handle(parameters, out);

        out.flush();
        out.close();

        closeContext(context);

    } catch (InvalidContextException e) {
        log.debug(e.getMessage(), e);
        return indexAction(response, model);
    } catch (ContextServiceException e) {
        log.error(e.getMessage(), e);
        closeContext(context);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Unexpected error while writing the output. For more information visit the log files.");
    } catch (XOAIManagerResolverException e) {
        throw new ServletException(
                "OAI 2.0 wasn't correctly initialized, please check the log for previous errors", e);
    } catch (OAIException e) {
        log.error(e.getMessage(), e);
        closeContext(context);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Unexpected error. For more information visit the log files.");
    } catch (WritingXmlException e) {
        log.error(e.getMessage(), e);
        closeContext(context);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Unexpected error while writing the output. For more information visit the log files.");
    } catch (XMLStreamException e) {
        log.error(e.getMessage(), e);
        closeContext(context);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Unexpected error while writing the output. For more information visit the log files.");
    } finally {
        closeContext(context);
    }

    return null; // response without content
}

From source file:kotys.monika.MenuCreatorJSP.LoadData.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w ww. j  a v a 2s  .  c  o m*/
 * @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 {
    // Check that we have a file upload request
    request.setCharacterEncoding("UTF-8");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    ArrayList<String> files = new ArrayList<String>();

    if (!isMultipart) {
        return;
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // constructs the folder where uploaded file will be stored
    String uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Set overall request size constraint
    upload.setSizeMax(MAX_REQUEST_SIZE);

    try {
        // Parse the request
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String filePath = uploadFolder + File.separator + fileName;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                // saves the file to upload directory
                item.write(uploadedFile);
                files.add(filePath);
            }
        }

        // displays done.jsp page after upload finished
        request.getSession().setAttribute("uploadedFiles", files);
        processRequest(request, response);

    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        Logger.getLogger(LoadData.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.ikon.servlet.admin.CronTabServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doGet({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    updateSessionManager(request);/*  ww w .java 2 s . c  o  m*/

    try {
        Map<String, String> types = new LinkedHashMap<String, String>();
        types.put(CronTab.BSH, "BSH");
        types.put(CronTab.JAR, "JAR");

        if (action.equals("create")) {
            ServletContext sc = getServletContext();
            CronTab ct = new CronTab();
            sc.setAttribute("action", action);
            sc.setAttribute("types", types);
            sc.setAttribute("ct", ct);
            sc.getRequestDispatcher("/admin/crontab_edit.jsp").forward(request, response);
        } else if (action.equals("edit")) {
            ServletContext sc = getServletContext();
            int ctId = WebUtils.getInt(request, "ct_id");
            CronTab ct = CronTabDAO.findByPk(ctId);
            sc.setAttribute("action", action);
            sc.setAttribute("types", types);
            sc.setAttribute("ct", ct);
            sc.getRequestDispatcher("/admin/crontab_edit.jsp").forward(request, response);
        } else if (action.equals("delete")) {
            ServletContext sc = getServletContext();
            int ctId = WebUtils.getInt(request, "ct_id");
            CronTab ct = CronTabDAO.findByPk(ctId);
            sc.setAttribute("action", action);
            sc.setAttribute("types", types);
            sc.setAttribute("ct", ct);
            sc.getRequestDispatcher("/admin/crontab_edit.jsp").forward(request, response);
        } else if (action.equals("execute")) {
            execute(request, response);
            list(request, response);
        } else {
            list(request, response);
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (EvalError e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:org.projectforge.web.meb.SMSReceiverServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    log.debug("Start doPost");
    // https://projectforge.micromata.de/secure/SMSReceiver?key=<key>&date=20101105171233&sender=01701891142&msg=Hallo...
    req.setCharacterEncoding("UTF-8");
    final String key = req.getParameter("key");
    final String expectedKey = ConfigXml.getInstance().getReceiveSmsKey();
    if (StringUtils.isBlank(expectedKey) == true) {
        log.warn(//  w ww . j  a v  a2s  .  co m
                "Servlet call for receiving sms ignored because receiveSmsKey is not given in config.xml file.");
        response(resp, "NOT YET CONFIGURED");
        return;
    }
    if (expectedKey.equals(key) == false) {
        log.warn("Servlet call for receiving sms ignored because receiveSmsKey does not match given key: "
                + key);
        response(resp, "DENIED");
        return;
    }
    final String dateString = req.getParameter("date");
    if (StringUtils.isBlank(dateString) == true) {
        log.warn("Servlet call for receiving sms ignored because parameter 'date' is not given.");
        response(resp, "Missing parameter 'date'.");
        return;
    }
    final String sender = req.getParameter("sender");
    if (StringUtils.isBlank(sender) == true) {
        log.warn("Servlet call for receiving sms ignored because parameter 'sender' is not given.");
        response(resp, "Missing parameter 'sender'.");
        return;
    }
    final String msg = req.getParameter("msg");
    if (StringUtils.isBlank(msg) == true) {
        log.warn("Servlet call for receiving sms ignored because parameter 'msg' is not given.");
        response(resp, "Missing parameter 'msg'.");
        return;
    }
    final Date date = MebDao.parseDate(dateString);
    if (date == null) {
        log.warn("Servlet call for receiving sms ignored because couln't parse parameter 'date'.");
        response(resp, "Unsupported date format.");
        return;
    }
    final ConfigurableListableBeanFactory beanFactory = Configuration.getInstance().getBeanFactory();
    beanFactory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
    MebEntryDO entry = new MebEntryDO();
    entry.setDate(date);
    entry.setSender(sender);
    entry.setMessage(msg);
    log.info("Servlet-call: date=[" + date + "], sender=[" + sender + "]");
    mebDao.checkAndAddEntry(entry, "SERVLET");
    response(resp, "OK");
}