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:de.unirostock.sems.cbarchive.web.servlet.IconServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException {
    // set charset
    response.setCharacterEncoding(Fields.CHARSET);
    request.setCharacterEncoding(Fields.CHARSET);

    // splitting request URL
    String requestUrl = request.getRequestURI();
    LOGGER.debug("IconServlet request: ", requestUrl);

    if (requestUrl != null && !requestUrl.isEmpty()) {

        String formatString = null;
        try {//from   w w  w . jav  a 2  s.  co m
            response.setContentType("image/png");

            formatString = requestUrl.substring(requestUrl.indexOf("res/icon/") + 9);
            LOGGER.debug("format: ", formatString);

            URI format = new URI(formatString);
            LOGGER.debug("format url: ", format);
            OutputStream output = response.getOutputStream();

            InputStream input = Iconizer.formatToIconStream(format);
            int size = IOUtils.copy(input, output);
            response.setContentLength(size);

            output.flush();
            output.close();
            input.close();

            response.flushBuffer();

        } catch (IOException e) {
            LOGGER.error(e, "IOException while loading icon");
        } catch (URISyntaxException e) {
            LOGGER.warn(e, "Not able to generate URL for Iconizer: ", formatString);
        }

    }

}

From source file:hd.controller.AddImageToProductServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww w  . ja v  a 2 s.  c  o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) { //to do

        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            try {
                items = upload.parseRequest(request);

            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator iter = items.iterator();
            Hashtable params = new Hashtable();

            String fileName = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString("UTF-8"));

                } else if (!item.isFormField()) {
                    try {
                        long time = System.currentTimeMillis();
                        String itemName = item.getName();
                        fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1);
                        String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName;
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
            String productID = (String) params.get("txtProductId");
            System.out.println(productID);
            String tilte = (String) params.get("newGalleryName");
            String description = (String) params.get("GalleryDescription");
            String url = "images/" + fileName;
            ProductDAO productDao = new ProductDAO();
            ProductPhoto productPhoto = productDao.insertProductPhoto(tilte, description, url, productID);

            response.sendRedirect("MyProductDetailServlet?action=showDetail&txtProductID=" + productID);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.close();
    }
}

From source file:per.mnn.controller.CheckoutController.java

@RequestMapping(value = "/confirm", method = RequestMethod.POST)
public ModelAndView confirm(HttpServletRequest request, HttpServletResponse respond)
        throws UnsupportedEncodingException {

    request.setCharacterEncoding("UTF-8");

    ModelAndView retval = new ModelAndView("confirmation");
    String name = request.getParameter("name");
    String email = request.getParameter("email");
    String phone = request.getParameter("phone");
    String address = request.getParameter("address");
    String cityRegion = request.getParameter("cityRegion");
    String creditcard = request.getParameter("creditcard");

    if (name == null || name.isEmpty()) {
        retval.addObject("nameError", "true");
        retval.addObject("validationErrorFlag", "true");
        retval.setViewName("checkout");
    }//from  ww w .  jav  a  2  s.c  o  m
    if (email == null || email.isEmpty()) {
        retval.addObject("emailError", "true");
        retval.addObject("validationErrorFlag", "true");
        retval.setViewName("checkout");
    }
    if (phone == null || phone.isEmpty()) {
        retval.addObject("phoneError", "true");
        retval.addObject("validationErrorFlag", "true");
        retval.setViewName("checkout");
    }
    if (address == null || address.isEmpty()) {
        retval.addObject("addressError", "true");
        retval.addObject("validationErrorFlag", "true");
        retval.setViewName("checkout");
    }
    if (cityRegion == null || cityRegion.isEmpty()) {
        retval.addObject("cityRegionError", "true");
        retval.addObject("validationErrorFlag", "true");
        retval.setViewName("checkout");
    }
    if (creditcard == null || creditcard.isEmpty()) {
        retval.addObject("creditcardError", "true");
        retval.addObject("validationErrorFlag", "true");
        retval.setViewName("checkout");
    }

    if (retval.getViewName() == "confirmation") {
        ShoppingCart cart = (ShoppingCart) request.getSession().getAttribute("cart");
        Session sess = HibernateUtil.getSessionFactory().openSession();
        Transaction tran = sess.beginTransaction();

        Customer customer = new Customer(name, email, phone, address, cityRegion, creditcard);
        sess.save(customer);

        CustomerOrder order = new CustomerOrder();
        order.setCustomer(customer);
        order.setAmount(BigDecimal.valueOf(cart.getTotal()));
        order.setDateCreated(new Date());
        order.setConfirmationNumber(new Random().nextInt(999999999));
        sess.save(order);

        for (ShoppingCartItem item : cart.getItems()) {
            OrderedProductId id = new OrderedProductId(order.getId(), item.getProduct().getId());
            OrderedProduct orderedProduct = new OrderedProduct();
            orderedProduct.setId(id);
            orderedProduct.setCustomerOrder(order);
            orderedProduct.setProduct(item.getProduct());
            orderedProduct.setQuantity((short) item.getQuantity());
            sess.save(orderedProduct);
            order.getOrderedProducts().add(orderedProduct);
        }

        tran.commit();
        sess.close();

        cart.clear();
        request.getSession().invalidate();
        retval.addObject("customer", customer);
        retval.addObject("orderRecord", order);
        retval.addObject("orderedProducts", order.getOrderedProducts());
    }

    return retval;
}

From source file:controllers.FrameworkController.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    this.request = request;
    this.response = response;

    if (request.getContentType().contains("multipart/form-data")) {
        adicionarOuEditarFramework();//from   ww w. ja va2 s.c o m
        return;
    }

    if (request.getParameter("btn_editar") != null) {
        editarFramework();
        return;
    }

    if (request.getParameter("btn_excluir") != null) {
        excluirFramework();
        return;
    }

}

From source file:com.flaptor.indextank.api.resources.Docs.java

/**
 * @see java.lang.Runnable#run()/*ww  w .  ja  va  2s  . co m*/
 */
public void run() {
    IndexEngineApi api = (IndexEngineApi) ctx().getAttribute("api");
    HttpServletResponse res = res();
    HttpServletRequest req = req();

    String characterEncoding = api.getCharacterEncoding();
    try {
        req.setCharacterEncoding(characterEncoding);
        res.setCharacterEncoding(characterEncoding);
        res.setContentType("application/json");
    } catch (UnsupportedEncodingException ignored) {
    }

    try {
        Object parse = JSONValue.parseWithException(req.getReader());
        if (parse instanceof JSONObject) { // 200, 400, 404, 409, 503
            JSONObject jo = (JSONObject) parse;
            try {
                putDocument(api, jo);
                res.setStatus(200);
                return;

            } catch (Exception e) {
                e.printStackTrace();
                if (LOG_ENABLED)
                    LOG.severe(e.getMessage());
                res.setStatus(400);
                print("Invalid or missing argument"); // TODO: descriptive error msg
                return;
            }
        } else if (parse instanceof JSONArray) {
            JSONArray statuses = new JSONArray();
            JSONArray ja = (JSONArray) parse;
            if (!validateDocuments(ja)) {
                res.setStatus(400);
                print("Invalid or missing argument"); // TODO: descriptive error msg
                return;
            }
            boolean hasError = false;
            for (Object o : ja) {
                JSONObject jo = (JSONObject) o;
                JSONObject status = new JSONObject();
                try {
                    putDocument(api, jo);
                    status.put("added", true);
                } catch (Exception e) {
                    status.put("added", false);
                    status.put("error", "Invalid or missing argument"); // TODO: descriptive error msg
                    hasError = true;
                }
                statuses.add(status);
            }
            print(statuses.toJSONString());
            return;
        }
    } catch (IOException e) {
        if (LOG_ENABLED)
            LOG.severe("PUT doc, parse input " + e.getMessage());
    } catch (ParseException e) {
        if (LOG_ENABLED)
            LOG.severe("PUT doc, parse input " + e.getMessage());
    } catch (Exception e) {
        if (LOG_ENABLED)
            LOG.severe("PUT doc " + e.getMessage());
    }
    res.setStatus(503);
    print("Service unavailable"); // TODO: descriptive error msg
}

From source file:com.concursive.connect.web.modules.welcome.servlets.WelcomeServlet.java

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {/*from w w  w  . ja va  2s.com*/
        request.setCharacterEncoding("UTF-8");
    } catch (Exception e) {
        LOG.warn("Unsupported encoding");
    }
    try {
        // Save the requestURI to be used downstream (it gets rewritten on forwards)
        String contextPath = request.getContextPath();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        String requestedURL = uri.substring(contextPath.length())
                + (queryString == null ? "" : "?" + queryString);
        if ("/index.shtml".equals(requestedURL)) {
            requestedURL = "";
        }
        request.setAttribute("requestedURL", requestedURL);
        // Configure the user's client
        ClientType clientType = (ClientType) request.getSession().getAttribute(Constants.SESSION_CLIENT_TYPE);
        if (clientType == null) {
            clientType = new ClientType();
            clientType.setParameters(request);
            request.getSession().setAttribute("clientType", clientType);
        }

        // Detect mobile
        if ("false".equals(request.getParameter("useMobile"))) {
            clientType.setMobile(false);
        }

        // Context startup initializes the prefs
        ApplicationPrefs applicationPrefs = (ApplicationPrefs) request.getSession().getServletContext()
                .getAttribute("applicationPrefs");
        if (!applicationPrefs.isConfigured()) {
            RequestDispatcher initialSetup = request.getRequestDispatcher("/Setup.do?command=Default");
            initialSetup.forward(request, response);
        } else if (ApplicationVersion.isOutOfDate(applicationPrefs)) {
            // If the site is setup, then check to see if this is an upgraded version of the app
            RequestDispatcher upgrade = getServletConfig().getServletContext()
                    .getRequestDispatcher("/Upgrade.do?command=Default&style=true");
            upgrade.forward(request, response);
        } else if ("true".equals(applicationPrefs.get("PORTAL"))) {
            // If the site supports a portal, go to the portal
            // @todo implement mobile pages then turn this back on
            //        if (clientType.getMobile()) {
            // If a mobile device is detected, offer a low-bandwidth option
            //          RequestDispatcher portal = request.getRequestDispatcher("/Login.do?command=DetectMobile");
            //          portal.forward(request, response);
            //        } else {
            String pathToUse = request.getRequestURI().substring(request.getContextPath().length());
            RequestDispatcher portal = request
                    .getRequestDispatcher(pathToUse + applicationPrefs.get("PORTAL.INDEX"));
            portal.forward(request, response);
            //        }
        } else {
            // Go to the user's home page if logged in
            User thisUser = (User) request.getSession().getAttribute(Constants.SESSION_USER);
            if (thisUser != null && thisUser.getId() > 0) {
                RequestDispatcher portal = request
                        .getRequestDispatcher("/ProjectManagement.do?command=Default");
                portal.forward(request, response);
            } else {
                RequestDispatcher portal = request.getRequestDispatcher("/Login.do?command=Default");
                portal.forward(request, response);
            }
        }
    } catch (Exception ex) {
        String msg = "Welcome failed";
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
    }
}

From source file:com.sbu.controller.Feed_Form_Startup_Edit_Contorller.java

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

    Startup User = new Startup();

    List<Member1> members = new ArrayList();

    request.setCharacterEncoding("UTF-8");
    int counter = 1;

    HttpSession session = request.getSession();

    int id = Integer.parseInt(request.getParameter("id"));
    User = startupService.getStartup(id);
    members = memberService.getAllMembers();
    Vector<Member1> filtered_members = new Vector<>();
    //filtered_members = memberService.getMemberByStartupId(id);

    for (int i = 0; i < members.size(); i++) {
        if (members.get(i).getStartupidStartup().getIdStartup() == id)
            filtered_members.add(members.get(i));
    }// w  ww . j  av  a 2  s. c o  m

    session.setAttribute("User", User);
    session.setAttribute("members", filtered_members);

    getServletContext().getRequestDispatcher("/accountsetting_Startup_Edit.jsp").forward(request, response);

}

From source file:feedme.controller.HomePageServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  w  w  w.  j a va  2  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 {
    processRequest(request, response);
    request.setCharacterEncoding("UTF-8");

}

From source file:com.sbu.controller.Update_Form_Employer_Controller.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    Employer employer;/*from   ww w .  j  ava  2s  . c o  m*/
    List<Project> projects = null;
    List<Skills> skills = null;
    HttpSession session = request.getSession();
    List<Employer> users;
    List<Feed> feed = feedService.getAllFeed();
    String username = request.getParameter("username");
    String pass = request.getParameter("password");

    //if we have this employer in Database
    int id = employerService.Redundant(username);
    if (id > 0) {
        employer = employerService.getEmployer(id);
        employer.setPassword(request.getParameter("password"));
        employer.setCompanyName(request.getParameter("workname"));
        employer.setIntroduction(request.getParameter("Intro"));
        employer.setYear(request.getParameter("year"));
        employer.setPhone(request.getParameter("phone"));
        employer.setAddress(request.getParameter("address"));
        employer.setCEOemail(request.getParameter("username"));
        employer.setCeoName(request.getParameter("name"));
        employer.setNews(request.getParameter("news"));
        employer.setCeoLastname(request.getParameter("lastname"));
        employer.setFacebook(request.getParameter("facebook"));
        employer.setInstagram(request.getParameter("instagram"));
        employer.setLinkedin(request.getParameter("linkedin"));
        employer.setGithub(request.getParameter("github"));
        //employer.setCompImage(request.getParts("CompImage"));
        employerService.editEmployer(employer);

        if (!((projectService.getProjectByEmployerId(employer.getIdEmployer())) == null)) {
            projects = projectService.getProjectByEmployerId(employer.getIdEmployer());
            for (int j = 0; j < projects.size(); j++) {
                projects.get(j).setName(request.getParameter("project_name" + j));
                projects.get(j).setDescription(request.getParameter("project_desc" + j));
                projects.get(j).setDeadline(request.getParameter("project_year" + j));
                projects.get(j).setEmployeridEmployer(employer);
                if (request.getParameter("project_name" + j) != null) {
                    projectService.editProject(projects.get(j));
                }

            }

        }

        if (!((skillsService.getSkillByEmployerId(employer.getIdEmployer())) == null)) {
            skills = skillsService.getSkillByEmployerId(employer.getIdEmployer());
            for (int j = 0; j < skills.size(); j++) {
                skills.get(j).setSkillName(request.getParameter("skill" + j));
                skills.get(j).setPercent(request.getParameter("skill_Percent" + j));
                skills.get(j).setEmployeridEmployer(employer);
                if (request.getParameter("skill" + j) != null) {
                    skillsService.editSkill(skills.get(j));
                }

            }

        }
        List<Employee> recomm = employerService.Recommendation();
        /**Recommendation**/
        session.setAttribute("recomm", recomm);
        session.setAttribute("feedcontent", feed);
        session.setAttribute("User", employer);
        getServletContext().getRequestDispatcher("/Feed_Employer.jsp").forward(request, response);

    }

}

From source file:feedme.controller.HomePageServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w  w w . j a  v a2s.co  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

}