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.betterform.agent.web.servlet.XFormsServlet.java

/**
 * Starts a new form-editing session.<br>
 * <p/>/*from  w w w  .  ja  v  a  2 s. co m*/
 * The default value of a number of settings can be overridden as follows:
 * <p/>
 * 1. The uru of the xform to be displayed can be specified by using a param name of 'form' and a param value
 * of the location of the xform file as follows, which will attempt to load the current xforms file.
 * <p/>
 * http://localhost:8080/betterform/XFormsServlet?form=/forms/hello.xhtml
 * <p/>
 * 2. The uri of the XSLT file used to generate the form can be specified using a param name of 'xslt' as follows:
 * <p/>
 * http://localhost:8080/betterform/XFormsServlet?form=/forms/hello.xhtml&xslt=/betterform/my.xslt
 * <p/>
 * 3. Besides these special params arbitrary other params can be passed via the GET-string and will be available
 * in the context map of XFormsProcessorImpl. This means they can be used as instance data (with the help of ContextResolver)
 * or to set params for URI resolution.
 *
 * @param request  servlet request
 * @param response servlet response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 * @see de.betterform.connector.ConnectorFactory
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

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

    HttpSession session = request.getSession(true);

    request.setAttribute(WebFactory.USER_AGENT, useragent);

    WebProcessor webProcessor = null;
    try {
        //            webProcessor = WebFactory.createWebProcessor(request);
        webProcessor = new FluxProcessor();
        webProcessor.setRequest(request);
        webProcessor.setResponse(response);
        webProcessor.setHttpSession(session);
        webProcessor.setBaseURI(request.getRequestURL().toString());
        webProcessor.configure();
        webProcessor.setXForms();
        webProcessor.init();
        webProcessor.handleRequest();

    } catch (Exception e) {
        e.printStackTrace();
        if (webProcessor != null) {
            webProcessor.close(e);
        }
    }
}

From source file:com.sishistorico.sv.SvCadastraEleitor.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w w w .ja v a  2 s  . 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 doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF8");
    response.setContentType("text/html;charset=UTF-8");

    List<FileItem> items = null;
    byte[] foto = null;
    try {
        items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                InputStream imageInput = item.getInputStream();
                Image image = ImageIO.read(imageInput);
                BufferedImage thumb = Imagem.redimensionar(image, 400, 500);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(thumb, "JPG", baos);
                baos.flush();
                foto = baos.toByteArray();
                baos.close();
            }
        }
        //dados do formulrio e metodos para salvar 
        DateFormat formatter;
        Date date;
        formatter = new SimpleDateFormat("dd/MM/yyyy");
        date = (Date) formatter.parse(items.get(1).getString());
        // fim do tratamento        
        Eleitor el = new Eleitor();
        Endereco end = new Endereco();
        el.setNome(items.get(0).getString("UTF-8").trim());
        el.setData_nascimento(date);
        el.setCpf(items.get(2).getString("UTF-8").replaceAll("\\.|\\-|\\ ", "").trim());
        el.setRg(items.get(3).getString("UTF-8").replaceAll("\\.|\\-|\\ ", "").trim());
        el.setSus(items.get(4).getString("UTF-8").replaceAll("\\.|\\-|\\ ", "").trim());
        el.setEmail(items.get(5).getString("UTF-8"));
        el.setTelefone(items.get(6).getString("UTF-8").replaceAll("\\(|\\)|\\-|\\ ", "").trim());
        el.setWhats(items.get(7).getString("UTF-8").replaceAll("\\(|\\)|\\-|\\ ", "").trim());
        el.setObs(items.get(8).getString("UTF-8").trim());
        el.setReferencia_pessoal(items.get(9).getString("UTF-8").trim());

        end.setRua(items.get(11).getString("UTF-8").trim());
        end.setBairro(items.get(12).getString("UTF-8").trim());
        end.setN(items.get(13).getString("UTF-8").trim());
        end.setCidade(items.get(14).getString("UTF-8").trim());
        end.setCep(items.get(15).getString("UTF-8").trim());
        end.setLocalidade(Integer.parseInt(items.get(16).getString("UTF-8").trim()));
        el.setTipo(Integer.parseInt(items.get(17).getString("UTF-8").trim()));
        el.setPertence(Integer.parseInt(items.get(18).getString("UTF-8").trim()));

        el.setEnd(end);
        DaoEleitor daoEleitor = new DaoEleitor();
        DaoFoto daoFoto = new DaoFoto();
        int idretorno = daoEleitor.Eleitor_Salvar(el);
        daoFoto.inserirImagem(foto, idretorno);
        response.sendRedirect("cadastro_eleitor.jsp?msgok");

    } catch (FileUploadException ex) {
        Logger.getLogger(SvCadastraEleitor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(SvCadastraEleitor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(SvCadastraEleitor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(SvCadastraEleitor.class.getName()).log(Level.SEVERE, null, ex);
    }

}

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

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    request.setCharacterEncoding(StandardCharsets.UTF_8.name());

    String requestURI = request.getRequestURI();

    boolean filtered = false;

    if (authProvider != null) {
        // Active Directory integration
        if (!requestURI.endsWith("/")) {
            requestURI = requestURI + "/";
        }/*from w w  w  . j  a v  a  2s  . c  om*/

        boolean bypass = false;
        for (String bypassUrl : bypassUrls) {
            if (requestURI.contains(bypassUrl)) {
                log.debug("Skip AD auth for by pass url: " + bypassUrl);
                bypass = true;
                break;
            }
        }

        filtered = filterByAuthProvider(request, response, chain, bypass);
    }

    if (!filtered) {
        handleNotFiltered(request, response, chain);
    }
}

From source file:com.ikon.servlet.frontend.StaplingDownloadServlet.java

/**
 * //  w w w.  ja  v  a  2  s.c  o m
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    request.setCharacterEncoding("UTF-8");
    String sgName = WebUtils.getString(request, "sgName");
    String groupName = sgName.substring(0, sgName.indexOf("?")) + "_" + sgName.charAt(sgName.length() - 1);
    String id = "" + groupName.charAt(groupName.length() - 1);
    int groupId = Integer.parseInt(id);
    File tmpZip = File.createTempFile("okm", ".zip");

    try {
        System.out.println("before zip");
        String archive = groupName + ".zip";
        response.setHeader("Content-disposition", "attachment; filename=\"" + archive + "\"");
        response.setContentType("application/zip");
        OutputStream out = response.getOutputStream();
        exportZip(groupId, out);
        out.flush();
        out.close();
    } catch (RepositoryException e) {
        log.warn(e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "RepositoryException: " + e.getMessage());
    } catch (Exception e) {
        log.warn(e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
        FileUtils.deleteQuietly(tmpZip);
    }
}

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

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

    request.setCharacterEncoding("UTF-8");
    HttpSession session = request.getSession();

    int id = Integer.parseInt(request.getParameter("id"));
    String username = request.getParameter("email");
    Employer user = employerService.getEmployer(id);
    Feed feed = new Feed();
    List<Feed> feeds = new ArrayList();
    Jobpositions jobposition = new Jobpositions();

    jobposition.setCategory(request.getParameter("category"));
    jobposition.setDegree(request.getParameter("certificate"));
    jobposition.setLanguages(request.getParameter("familiar"));
    jobposition.setMajor(request.getParameter("major"));
    jobposition.setPosTitle(request.getParameter("posname"));
    jobposition.setSalary(request.getParameter("minsalary"));
    jobposition.setSex(request.getParameter("sex"));
    jobposition.setSkills(request.getParameter("Skills"));
    jobposition.setDate(request.getParameter("Date"));
    jobposition.setWorkTime(request.getParameter("workhours"));
    jobposition.setUniversity(request.getParameter("uni"));
    jobposition.setDescription(request.getParameter("description"));
    jobposition.setEmployeridEmployer(user);
    jobPositionService.addJobpositions(jobposition);
    //feed//from w w w . ja  v  a2 s .c  o  m
    feed.setEmployeridEmployer(user);
    feed.setDescription(request.getParameter("description"));
    feed.setTitle(request.getParameter("posname"));
    feed.setDegree(request.getParameter("certificate"));
    feed.setMajor(request.getParameter("major"));
    feed.setSkills(request.getParameter("Skills"));
    feed.setSalary(request.getParameter("minsalary"));
    feed.setWorkTime(request.getParameter("workhours"));
    feed.setDate(request.getParameter("Date"));
    feedService.addFeed(feed);

    feeds = feedService.getAllFeed();

    /**Recommendation**/

    List<Employee> emps = employeeService.getAllEmployees();
    Vector<Employee> recomm = new Vector<>();

    for (int j = 0; j < emps.size(); j++) {

        if (user.getAddress().contains(emps.get(j).getCity())) {
            recomm.add(emps.get(j));
        }

    }

    /**Recommendation**/
    session.setAttribute("recomm", recomm);
    session.setAttribute("id", id);
    session.setAttribute("email", username);
    session.setAttribute("feedcontent", feeds);
    session.setAttribute("User", user);
    getServletContext().getRequestDispatcher("/Feed_Employer.jsp").forward(request, response);

}

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

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    updateSessionManager(request);/*from ww  w  . jav  a 2 s. c  om*/

    if (action.equals("view")) {
        view(request, response);
    } else if (action.equals("purge")) {
        purge(request, response);
    } else if (action.equals("download")) {
        download(request, response);
    } else if (action.equals("list") || action.equals("")) {
        list(request, response);
    } else {
        ServletContext sc = getServletContext();
        sc.getRequestDispatcher("/admin/logcat.jsp").forward(request, response);
    }
}

From source file:net.hillsdon.reviki.web.dispatching.impl.DispatcherImpl.java

public void handle(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {
    request.setCharacterEncoding("UTF-8");
    request.setAttribute(ApplicationUrls.KEY, _applicationUrls);

    // We should be able to use request.getPathInfo() as it's documented as
    // having been correctly decoded by the container,
    // however Tomcat at least fails with UTF-8.
    final String requestPath = getStrippedPath(URI.create(request.getRequestURI()));
    final String contextPath = request.getContextPath();
    ConsumedPath path = new ConsumedPath(requestPath, contextPath);

    try {// w ww.  ja  v a 2s.c  om
        _requestLifecycleAwareManager.requestStarted(request);
        View view = handle(path, request, response);
        if (view != null) {
            view.render(request, response);
        }
    } catch (NotFoundException ex) {
        handleException(request, response, ex, false, "Could not find the file you were looking for.", 404);
    } catch (Exception ex) {
        handleException(request, response, ex, true, null, 500);
    } finally {
        _requestCompletedHandler.requestComplete();
    }
}

From source file:controllers.LinguagemController.java

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

    if (request.getParameter("btn_editar") != null) {
        getEditarLinguagemView();/*w w  w . ja va2s  . c  o  m*/
        return;
    }

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

    if (request.getContentType().contains("multipart/form-data")) {
        adicionarOuEditarLinguagem();
    }
}

From source file:com.sishistorico.sv.SvEditarEleitor.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w w  w .  j  a va2s.  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 doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF8");
    response.setContentType("text/html;charset=UTF-8");

    List<FileItem> items = null;
    byte[] foto = null;
    long vazio = 0;
    try {
        items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                vazio = item.getSize();
                System.out.println("tamanho/:::::::::::::::::::: " + vazio);
                InputStream imageInput = item.getInputStream();
                Image image = ImageIO.read(imageInput);
                BufferedImage thumb = Imagem.redimensionar(image, 400, 500);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(thumb, "JPG", baos);
                baos.flush();
                foto = baos.toByteArray();
                baos.close();
            }
        }
        //dados do formulrio e metodos para salvar 
        DateFormat formatter;
        Date date;
        formatter = new SimpleDateFormat("dd/MM/yyyy");
        date = (Date) formatter.parse(items.get(1).getString());
        // fim do tratamento        
        Eleitor el = new Eleitor();
        Endereco end = new Endereco();
        el.setId(Integer.parseInt(items.get(19).getString("UTF-8").trim()));
        el.setNome(items.get(0).getString("UTF-8").trim());
        el.setData_nascimento(date);
        el.setCpf(items.get(2).getString("UTF-8").replaceAll("\\.|\\-|\\ ", "").trim());
        el.setRg(items.get(3).getString("UTF-8").replaceAll("\\.|\\-|\\ ", "").trim());
        el.setSus(items.get(4).getString("UTF-8").replaceAll("\\.|\\-|\\ ", "").trim());
        el.setEmail(items.get(5).getString("UTF-8"));
        el.setTelefone(items.get(6).getString("UTF-8").replaceAll("\\(|\\)|\\-|\\ ", "").trim());
        el.setWhats(items.get(7).getString("UTF-8").replaceAll("\\(|\\)|\\-|\\ ", "").trim());
        el.setObs(items.get(8).getString("UTF-8").trim());
        el.setReferencia_pessoal(items.get(9).getString("UTF-8").trim());

        end.setRua(items.get(11).getString("UTF-8").trim());
        end.setBairro(items.get(12).getString("UTF-8").trim());
        end.setN(items.get(13).getString("UTF-8").trim());
        end.setCidade(items.get(14).getString("UTF-8").trim());
        end.setCep(items.get(15).getString("UTF-8").trim());
        end.setLocalidade(Integer.parseInt(items.get(16).getString("UTF-8").trim()));
        el.setTipo(Integer.parseInt(items.get(17).getString("UTF-8").trim()));
        el.setPertence(Integer.parseInt(items.get(18).getString("UTF-8").trim()));

        el.setEnd(end);
        DaoEleitor daoEleitor = new DaoEleitor();
        DaoFoto daoFoto = new DaoFoto();
        int idretorno = daoEleitor.Eleitor_Editar(el);
        if (vazio > 1) {
            daoFoto.atualizarImagem(foto, idretorno);
        }
        response.sendRedirect("editar_eleitor.jsp?id=" + el.getId() + "&msgok=Editado com sucesso!");

    } catch (FileUploadException ex) {
        Logger.getLogger(SvEditarEleitor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(SvEditarEleitor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(SvEditarEleitor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(SvEditarEleitor.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:de.betterform.agent.web.servlet.XFormsRequestServlet.java

/**
 * This ia jus a little demo servlet to show operation with XFormsFilter. It parses the XForms
 * document form the file system and writes it out to the ServletStream. Additionally it sets the request property
 * XFORMS_FILTER to allow the Filter to work efficiently.
 *
 * @param request  servlet request/*from  w ww.  j  a  v a 2  s.c o m*/
 * @param response servlet response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LOGGER.debug("hit XFormsRequestServlet");

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

    Document doc;

    //locate it
    //        String formURI = request.getParameter(WebFactory.FORM_PARAM_NAME);
    String formURI = WebUtil.getFormUrlAsString(request);
    if (formURI.startsWith("http://")) {
        InputStream inputStream = new URL(formURI).openStream();
        try {
            doc = DOMUtil.parseInputStream(inputStream, true, false);
        } catch (ParserConfigurationException e) {
            throw new ServletException(e);
        } catch (SAXException e) {
            throw new ServletException(e);
        }
    } else {
        String realPath = null;
        try {
            realPath = WebFactory.getRealPath(formURI, getServletContext());
        } catch (XFormsConfigException e) {
            throw new ServletException(e);
        }
        File xfDoc = new File(realPath);
        try {
            doc = DOMUtil.parseXmlFile(xfDoc, true, false);
        } catch (ParserConfigurationException e) {
            throw new ServletException(e);
        } catch (SAXException e) {
            throw new ServletException(e);
        }
    }

    //parse it

    request.setAttribute(WebFactory.XFORMS_NODE, doc);
    //        try {
    //            DOMUtil.prettyPrintDOM(doc,response.getOutputStream());
    //        } catch (TransformerException e) {
    //            throw new ServletException(e);
    //        }

    //do the Filter twist
    response.getOutputStream().close();
}