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:com.sbu.controller.ServletPersonalEmployerController.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);/*ww w  .  j av a2  s .  c  o m*/
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    Employer employer = new Employer();
    List<Employer> user;
    List<Project> proj;
    List<Skills> skills = new Vector<>();
    ;
    List<Project> projects = new Vector<>();
    //List<Skills> skills = new Vector<>();
    user = employerService.getAllEmployers();
    //proj = projectService.getAllProjects();
    //allskills = skillsService.getAllSkills();
    int id = Integer.parseInt(request.getParameter("id"));
    employer = employerService.getEmployer(id);
    //for(int i = 0 ; i < user.size() ;i++)
    //{
    if (!((projectService.getProjectByEmployerId(id)) == null)) {
        projects = projectService.getProjectByEmployerId(id);

    }

    if (!((skillsService.getSkillByEmployerId(id)) == null)) {
        skills = skillsService.getSkillByEmployerId(id);

    }
    /*if(user.get(i).getIdEmployer()==Integer.parseInt(request.getParameter("id")))
    {
                
        for(int j = 0 ; j < proj.size() ; j++)
            {
                if(proj.get(j).getEmployeridEmployer().equals(user.get(i)))
                {
                    projects.add(proj.get(j));
                }
           }
                 
        for(int j = 0; j < allskills.size() ; j++)
            {
                if(skills.get(j).getEmployeridEmployer().equals(user.get(i)))
                {
                    skills.add(allskills.get(j));
                }
           }*/
    //employer = user.get(i);

    request.setAttribute("User", employer);
    request.setAttribute("projects", projects);
    request.setAttribute("skills", skills);
    getServletContext().getRequestDispatcher("/Personal_Employer.jsp").forward(request, response);
    //break;
    // }
    //}
    getServletContext().getRequestDispatcher("/Personal_Employer.jsp").forward(request, response);

}

From source file:msec.org.FileUploadServlet.java

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

    Map<String, String> fields = new HashMap<String, String>();
    List<String> fileNames = new ArrayList<String>();

    request.setCharacterEncoding("UTF-8");

    String result = FileUpload(fields, fileNames, request, response);

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

    if (result == null || !result.equals("success")) {
        out.printf("{\"status\":100, \"message\":\"%s\"}", result == null ? "" : result);
        return;//w w w  .ja  v  a 2 s  .  co m
    }
    String handleClass = fields.get("handleClass");
    if (handleClass != null && handleClass.equals("beans.service.LibraryFileUpload")) {
        //out.write(new LibraryFileUpload().run(fields, fileNames));
        return;
    }
    if (handleClass != null && handleClass.equals("beans.service.SharedobjectUpload")) {
        //  out.write(new SharedobjectUpload().run(fields, fileNames));
        return;

    }
    out.write("{\"status\":100, \"message\":\"unkown handle class\"}");
    return;

}

From source file:controller.productServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    String proimage = "";
    String nameProduct = "";
    double priceProduct = 0;
    String desProduct = "";
    String colorProduct = "";
    int years = 0;
    int catId = 0;
    int proid = 0;
    String command = "";

    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here
        PrintWriter writer = response.getWriter();
        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();/*from w w  w.  j av a 2s  .c  om*/
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // sets memory threshold - beyond which files are stored in disk 
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    // sets temporary location to store files
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);

    // sets maximum size of upload file
    upload.setFileSizeMax(MAX_FILE_SIZE);

    // sets maximum size of request (include file + form data)
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    // this path is relative to application's directory
    String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {
        // parses the request's content to extract file data
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {
            // iterates over form's fields
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    proimage = new File(item.getName()).getName();
                    String filePath = uploadPath + File.separator + proimage;
                    File storeFile = new File(filePath);
                    System.out.println(proimage);
                    item.write(storeFile);
                } else if (item.getFieldName().equals("name")) {
                    nameProduct = item.getString();
                } else if (item.getFieldName().equals("price")) {
                    priceProduct = Double.parseDouble(item.getString());
                } else if (item.getFieldName().equals("description")) {
                    desProduct = item.getString();
                    System.out.println(desProduct);
                } else if (item.getFieldName().equals("color")) {
                    colorProduct = item.getString();
                } else if (item.getFieldName().equals("years")) {
                    years = Integer.parseInt(item.getString());
                } else if (item.getFieldName().equals("catogory_name")) {
                    catId = Integer.parseInt(item.getString());
                } else if (item.getFieldName().equals("command")) {
                    command = item.getString();
                } else if (item.getFieldName().equals("proid")) {
                    proid = Integer.parseInt(item.getString());
                }
            }
        }
    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }

    String url = "", error = "";
    if (nameProduct.equals("")) {
        error = "Vui lng nhp tn danh mc!";
        request.setAttribute("error", error);
    }

    try {
        if (error.length() == 0) {
            ProductEntity p = new ProductEntity(catId, nameProduct, priceProduct, proimage, desProduct,
                    colorProduct, years);
            switch (command) {
            case "insert":
                prod.insertProduct(p);
                url = "/java/admin/ql-product.jsp";
                break;
            case "update":
                prod.updateProduct(catId, nameProduct, priceProduct, proimage, desProduct, colorProduct, years,
                        proid);
                url = "/java/admin/ql-product.jsp";
                break;
            }
        } else {
            url = "/java/admin/add-product.jsp";
        }
    } catch (Exception e) {

    }
    response.sendRedirect(url);
}

From source file:com.openkm.servlet.admin.PropertyGroupsServlet.java

@Override
public void doPost(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  . j  a v  a 2s  . c o  m*/

    try {
        if (action.equals("edit")) {
            edit(request, response);
        }

        list(request, response);
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:br.unicamp.cotuca.dpd.pd12.acinet.vagalmail.servlet.Configuracoes.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    String metodo = "", req = request.getRequestURI();

    if (req.contains("/nova")) {
        metodo = "nova";
    } else if (req.contains("/conta")) {
        metodo = "conta";
    } else if (req.contains("/senha")) {
        metodo = "senha";
    } else {/*from   w  w w .j a  va 2 s. c  om*/
        response.sendRedirect("/conf/conta");
    }

    if (!"".equals(metodo))
        request.getRequestDispatcher("/conf.jsp?metodo=" + metodo).include(request, response);
}

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

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    updateSessionManager(request);//  w ww.  j a  va  2  s  .  c  o  m
    InputStream is = null;

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            String docUuid = null;
            String repoPath = null;
            String text = null;
            String mimeType = null;
            String extractor = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("docUuid")) {
                        docUuid = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("repoPath")) {
                        repoPath = item.getString("UTF-8");
                    }
                } else {
                    is = item.getInputStream();
                    String name = FilenameUtils.getName(item.getName());
                    mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());

                    if (!name.isEmpty() && item.getSize() > 0) {
                        docUuid = null;
                        repoPath = null;
                    } else if (docUuid.isEmpty() && repoPath.isEmpty()) {
                        mimeType = null;
                    }
                }
            }

            if (docUuid != null && !docUuid.isEmpty()) {
                repoPath = OKMRepository.getInstance().getNodePath(null, docUuid);
            }

            if (repoPath != null && !repoPath.isEmpty()) {
                String name = PathUtils.getName(repoPath);
                mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase());
                is = OKMDocument.getInstance().getContent(null, repoPath, false);
            }

            long begin = System.currentTimeMillis();

            if (is != null) {
                if (!MimeTypeConfig.MIME_UNDEFINED.equals(mimeType)) {
                    TextExtractor extClass = RegisteredExtractors.getTextExtractor(mimeType);

                    if (extClass != null) {
                        extractor = extClass.getClass().getCanonicalName();
                        text = RegisteredExtractors.getText(mimeType, null, is);
                    } else {
                        extractor = "Undefined text extractor";
                    }
                }
            }

            ServletContext sc = getServletContext();
            sc.setAttribute("docUuid", docUuid);
            sc.setAttribute("repoPath", repoPath);
            sc.setAttribute("text", text);
            sc.setAttribute("time", System.currentTimeMillis() - begin);
            sc.setAttribute("mimeType", mimeType);
            sc.setAttribute("extractor", extractor);
            sc.getRequestDispatcher("/admin/check_text_extraction.jsp").forward(request, response);
        }
    } catch (DatabaseException e) {
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        sendErrorRedirect(request, response, e);
    } catch (PathNotFoundException e) {
        sendErrorRedirect(request, response, e);
    } catch (AccessDeniedException e) {
        sendErrorRedirect(request, response, e);
    } catch (RepositoryException e) {
        sendErrorRedirect(request, response, e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:ua.aits.sdolyna.controller.SystemController.java

@RequestMapping(value = { "/Sdolyna/system/logout.do", "/system/logout.do", "/Sdolyna/system/logout.do/",
        "/system/logout.do/" })
public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
    request.setCharacterEncoding("UTF-8");
    HttpSession session = request.getSession(false);
    if (session != null) {
        session.invalidate();/*from w  w w  . j  a v  a 2 s.c o  m*/
    }
    return new ModelAndView("redirect:" + "/system/login");
}

From source file:org.jcommon.com.wechat.servlet.MediaServlet.java

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

    String errormsg = null;/*from   w  w  w  .  j a va2  s  .  c om*/
    List<FileItem> list = new ArrayList<FileItem>();
    List<UrlObject> urls = new ArrayList<UrlObject>();
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItem item = null;
        try {
            ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> it = items.iterator();
            while (it.hasNext()) {
                item = it.next();
                if (!item.isFormField()) {
                    list.add(item);
                }
            }
        } catch (Throwable e) {
            logger.error("", e);
            errormsg = "transfer exception";
        }
    } else {
        errormsg = "not found multipart content";
    }
    if (errormsg != null) {
        error(response, errormsg);
        return;
    }
    for (FileItem item : list) {
        try {
            String file_name = item.getName();
            String file_id = org.jcommon.com.util.BufferUtils.generateRandom(20);
            String content_type = item.getContentType();

            Media media = new Media();
            media.setContent_type(content_type);
            media.setMedia_id(file_id);
            media.setMedia_name(file_name);

            FileOutputStream out_file = null;
            java.io.File file = MediaManager.getMedia_factory().createEmptyFile(media);
            media.setMedia(file);
            out_file = new FileOutputStream(file);
            InputStream is = item.getInputStream();
            logger.info("uploading...........");
            byte[] b = new byte[1024];
            int nRead;
            while ((nRead = is.read(b, 0, 1024)) > 0) {
                out_file.write(b, 0, nRead);
            }
            try {
                out_file.close();
                out_file.flush();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                file.delete();
                throw e1;
            }
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                throw e;
            }
            String url = MediaManager.getMedia_factory().createUrl(media).getUrl();
            logger.info(url);
            urls.add(new UrlObject(url));

        } catch (Throwable e) {
            logger.error("", e);
            errormsg = "transfer exception";
        }
    }
    if (errormsg != null) {
        error(response, errormsg);
        return;
    } else {
        String msg = "";
        if (urls.size() > 0) {
            if (urls.size() == 1)
                msg = urls.get(0).toJson();
            else
                msg = org.jcommon.com.util.JsonObject.list2Json(urls);
        }
        logger.info(msg);
        response.getWriter().println(msg);
    }
}

From source file:cn.com.cennavi.visualizer.service.ExecuteController.java

private void returnAjax(String json, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    try {/* w ww .j  av a 2  s . c o m*/
        String callback = request.getParameter("callback");
        String revalue = callback + "(" + json + ")";
        request.setCharacterEncoding("utf-8"); //???
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("Cache-Control", "no-cache");
        response.getOutputStream().write(revalue.getBytes());
        response.flushBuffer();
    } catch (Exception e) {
        // TODO: handle exception
    }
}

From source file:IdeaBroker.InserirIdeiaServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from w ww.j a va 2 s  .com
 * @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 {

    request.setCharacterEncoding("UTF-8");

    HttpSession session = request.getSession(true);

    RequestDispatcher dispatcher = null;

    String textData = null;
    String fileName = null;
    int investimento = -1, id_topico = -1;

    try { // Para apagar!!!!

        /*  isMultipart = ServletFileUpload.isMultipartContent(request);
          java.io.PrintWriter out = response.getWriter( );
          if( !isMultipart ){
            System.out.println("Multipart error ");
            return;
          }
                  
          DiskFileItemFactory factory = new DiskFileItemFactory();
          factory.setSizeThreshold(maxMemSize);
          factory.setRepository(new File("/home/joao/?rea\\ de\\ Trabalho/"));
                  
          ServletFileUpload upload = new ServletFileUpload(factory);
                  
          upload.setSizeMax(maxFileSize);
                  
          try{
                      
              List fileItems = upload.parseRequest(request);
                      
              Iterator i = fileItems.iterator();
                      
              while( i.hasNext())
              {
        FileItem fi = (FileItem)i.next();
                
        if( !fi.isFormField() )
        {
            fileName = fi.getName();
            if(!fileName.isEmpty())
            {
                 if( fileName.lastIndexOf("\\") >= 0 ){
                    file = new File( filePath + 
                    fileName.substring( fileName.lastIndexOf("\\"))) ;
                 }else{
                    file = new File( filePath + 
                    fileName.substring(fileName.lastIndexOf("\\")+1)) ;
                 }
                 fi.write(file);
            }
                
        }
        else
        {
            String inputName = (String) fi.getFieldName();
            if (inputName.equals("descricao"))
                textData = (String) fi.getString();
            else if(inputName.equals("investimento"))
                investimento = Integer.parseInt(fi.getString());
            else if(inputName.equals("id_topico"))
                id_topico = Integer.parseInt(fi.getString());
                
        }
              }*/

        /** Criar Ideia **/
        IdeaBrokerBean ideabrokerbean = (IdeaBrokerBean) session.getAttribute("ideabrokerbean");
        String username = (String) session.getAttribute("username");
        String password = (String) session.getAttribute("password");
        //System.out.println("[Servlet] Sou username =="+username+ "\n[Servlet] Token == "+ideabrokerbean.getOAuth());
        textData = request.getParameter("descricao");
        System.out.println("Descricao == " + textData);

        if ((request.getParameter("investimento") != null) && (!request.getParameter("investimento").isEmpty())
                && (ideabrokerbean.ContarLetras(request.getParameter("investimento")))) {
            System.out.println("Entra no if e investimento == " + request.getParameter("investimento"));
            investimento = Integer.parseInt(request.getParameter("investimento"));
        }

        filePath = null;
        if ((request.getParameter("id_topico") != null) && (!request.getParameter("id_topico").isEmpty()))
            id_topico = Integer.parseInt(request.getParameter("id_topico"));

        if ((textData != null && !textData.isEmpty())) {
            if (investimento != -1) {

                if ((fileName != null) && (!fileName.isEmpty())) {
                    //chama funcao que cria a ideia sem anexo
                    if (ideabrokerbean.criaIdeia(username, textData, null, id_topico, investimento))
                        dispatcher = request.getRequestDispatcher("ideia_aceite.html");
                    else
                        dispatcher = request.getRequestDispatcher("erro_ideia.html");

                    ideabrokerbean.print_service();
                } else {
                    //chama funcao que cria a ideia com anexo
                    if (ideabrokerbean.criaIdeia(username, textData, null, id_topico, investimento))
                        dispatcher = request.getRequestDispatcher("ideia_aceite.html");
                    else
                        dispatcher = request.getRequestDispatcher("erro_ideia.html");
                }
            }
        }

        //dispatcher = request.getRequestDispatcher("ideia_aceite.html");
        dispatcher.forward(request, response);

    } catch (Exception ex) {
        System.out.println(ex);
    }

}