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:eu.earthobservatory.org.StrabonEndpoint.BrowseBean.java

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

    // check connection details
    if (strabonWrapper.getStrabon() == null) {
        RequestDispatcher dispatcher = request.getRequestDispatcher("/connection.jsp");

        // pass the current details of the connection
        request.setAttribute("username", strabonWrapper.getUsername());
        request.setAttribute("password", strabonWrapper.getPassword());
        request.setAttribute("dbname", strabonWrapper.getDatabaseName());
        request.setAttribute("hostname", strabonWrapper.getHostName());
        request.setAttribute("port", strabonWrapper.getPort());
        request.setAttribute("dbengine", strabonWrapper.getDBEngine());

        // pass the other parameters as well
        request.setAttribute("query", request.getParameter("query"));
        request.setAttribute("format", request.getParameter("format"));
        request.setAttribute("handle", request.getParameter("handle"));

        // forward the request
        dispatcher.forward(request, response);

    } else {/*from  w  w w.  j  a v  a2s  .c o m*/

        if (Common.VIEW_TYPE.equals(request.getParameter(Common.VIEW))) {
            // HTML visual interface
            processVIEWRequest(request, response);

        } else {// invoked as a service
            processRequest(request, response);
        }
    }
}

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

@RequestMapping(value = { "/system/do/deleteproject/{id}", "/system/do/deleteproject/{id}/" })
public ModelAndView deleteArticle(@PathVariable("id") String id, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    request.setCharacterEncoding("UTF-8");
    return new ModelAndView("redirect:" + "/system/index/" + Projects.deleteProject(id));
}

From source file:es.uma.inftel.blog.servlet.PostServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w ww  .  j  a va2 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");
    String tituloP = request.getParameter("tituloPost");
    String textoP = request.getParameter("textoPost");

    RequestDispatcher rd = request.getRequestDispatcher("/crearPost.jsp");
    if (tituloP == null && textoP == null) {
        BaseView crearPostView = new BaseView();
        BaseViewFacade<BaseView> crearPostViewFacade = new BaseViewFacade<>(postFacade);
        crearPostViewFacade.initView(crearPostView);
        request.setAttribute("crearPostView", crearPostView);
        rd.forward(request, response);
        return;
    }
    Usuario usuario = (Usuario) request.getSession().getAttribute("usuario");
    Post post = crearPost(tituloP, textoP, usuario);
    postFacade.create(post);

    String etiquetas = request.getParameter("etiqueta");
    insertarEtiquetas(etiquetas, post);
    if (!request.getParameter("lat").isEmpty()) {
        crearMapa(request, post);
    }
    //Crea Fotos
    insertarImagen(request, post);

    response.sendRedirect("post?id=" + post.getId());
}

From source file:org.guiceside.web.dispatcher.GuiceSideFilter.java

/**
 * servletContext<br/>/*from w ww . ja  v  a2  s.c om*/
 * ?Filter?characterEncoding<br/>
 * @param servletRequest
 * @param servletResponse
 * @param filterChain
 */
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    ServletContext servletContext = filterConfig.getServletContext();
    Context previous = localContext.get();
    try {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        if (StringUtils.isNotBlank(encoding)) {
            httpServletRequest.setCharacterEncoding(encoding);
            httpServletResponse.setCharacterEncoding(encoding);
        }
        httpServletResponse.setHeader("P3P",
                "CP='IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT'");
        localContext.set(new Context(servletContext));
        filterChain.doFilter(servletRequest, servletResponse);
    } finally {
        localContext.set(previous);

    }
}

From source file:cz.muni.fi.webmias.ProcessServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  ww  w . j  a  va  2  s  .  co m*/
 * @param response servlet response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");

    HttpSession session = request.getSession(true);

    int page = Integer.parseInt(request.getParameter("n"));
    String query = request.getParameter(QUERY_PARAMETER);
    boolean debug = request.getParameter("debug") != null;
    boolean extractSubformulae = request.getParameter("extractSubformulae") != null;
    boolean reduceWeighting = request.getParameter("reduceWeighting") != null;
    String indexNo = request.getParameter("index");
    int indexNumber = 0;
    if (indexNo != null) {
        indexNumber = Integer.parseInt(indexNo);
    }
    String qc = request.getParameter("qc");
    String variant = request.getParameter("variant");
    MathMLType mmlType = getType(variant);

    IndexDef currentIndexDef = Indexes.getIndexDef(indexNumber);
    IndexSearcher searcher = currentIndexDef.getIndexSearcher();
    request.setAttribute("index", indexNumber);
    request.setAttribute(QUERY_PARAMETER, query);
    request.setAttribute("debug", debug);
    request.setAttribute("extractSubformulae", extractSubformulae);
    request.setAttribute("reduceWeighting", reduceWeighting);
    request.setAttribute("qc", qc);
    request.setAttribute("variant", variant);
    request.setAttribute("forbidden", forbidden);

    request.setAttribute("indexes", Indexes.getIndexNames());

    if (query != null && !query.isEmpty()) {
        logQuery(request, query);
        String[] sep = MathSeparator.separate(query, "");
        query = sep[1];
        if (sep[0] != null && !sep[0].isEmpty()) {
            query += " " + TeXConverter.convertTexLatexML(sep[0]);
        }

        s = new Searching(searcher, currentIndexDef.getStorage());
        page = page == 0 ? page : page - 1;
        SearchResult searchResult = s.search(query, false, page * resPerPage, resPerPage, debug, mmlType,
                extractSubformulae, reduceWeighting);
        int totalResults = searchResult.getTotalResults();
        request.setAttribute("processedQuery", searchResult.getProcessedQuery());
        request.setAttribute("luceneQuery", searchResult.getLuceneQuery());
        request.setAttribute("total", searchResult.getTotalResults());
        request.setAttribute("coreTime", searchResult.getCoreSearchTime());
        request.setAttribute("totalTime", searchResult.getTotalSearchTime());
        request.setAttribute("resPerPage", resPerPage);
        totalResults = Math.min(totalResults, Settings.getMaxResults());
        if (totalResults > 0 && page >= 0) {
            List<Integer> pages = new ArrayList<>();
            for (int i = 0; i < (totalResults / resPerPage) + 1; i++) {
                pages.add(i + 1);
            }
            request.setAttribute("pages", pages);
            request.setAttribute("n", page);
            for (Result r : searchResult.getResults()) {
                r.setInfo(r.getInfo().replaceAll("\n", "<br/>"));
            }
            request.setAttribute("results", searchResult.getResults());
        } else if (page == -1) {
            session.invalidate();
        } else {
            request.setAttribute("nores", "No results.");
        }
    }
    request.getRequestDispatcher("/index.jsp").forward(request, response);
}

From source file:fr.aliasource.webmail.server.LoginFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fc)
        throws IOException, ServletException {
    HttpServletRequest hreq = (HttpServletRequest) req;
    HttpSession session = hreq.getSession();
    hreq.setCharacterEncoding("UTF-8");

    IAccount account = (IAccount) session.getAttribute("account");
    String uri = hreq.getRequestURI();
    uri = uri.replace("/minig", "");

    if (account != null) {
        fc.doFilter(req, resp);/*  w w  w.j a  va  2s . c om*/
        return;
    } else {

        // pass through ajax calls
        if (ajaxCall.contains(uri)) {
            fc.doFilter(req, resp);
            return;
        }

        if (logger.isDebugEnabled()) {
            logger.debug("loginFilter on uri: " + hreq.getRequestURI());
        }

        /* Not logged in */
        try {
            performLoginProcedure(session, fc, hreq, (HttpServletResponse) resp);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
}

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

@RequestMapping(value = { "/system/do/login", "/system/do/login/" }, method = RequestMethod.POST)
public ModelAndView login(@RequestParam("user_name") String user_name,
        @RequestParam("user_password") String user_password, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    request.setCharacterEncoding("UTF-8");
    HttpSession session = request.getSession(true);
    session.setAttribute("user", "admin");
    return new ModelAndView("redirect:" + "/system/index");
}

From source file:com.happyuno.controller.JoinGameTable.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=utf-8");
    request.setCharacterEncoding("utf-8");

    //?//from  ww w  . j  a va2s .  co  m
    String tableId = (String) request.getParameter("tableId");
    //      int tableId =Integer.parseInt(request.getSession().getAttribute("tableId").toString());

    //      String setNum = request.getParameter("setNum").trim();

    //      
    ServletContext application = request.getSession().getServletContext();
    HashMap<Integer, GameTable> gameTableMap = (HashMap<Integer, GameTable>) application
            .getAttribute("gameTableMap");

    //?ID user
    String userId = (String) request.getSession().getAttribute("userId");
    maindeal md = new maindeal();
    List dbUserList = md.query("from User as u where u.id='" + userId + "'");
    User curUser = (User) dbUserList.get(0);

    //
    String resultMessage = "?";
    int index = Integer.parseInt(tableId);
    System.out.println(index);
    //
    GameTable gametable = gameTableMap.get(index);
    if (gametable == null) {
        System.out.println("true");
    }

    int defiNum = gametable.getDefiNum();

    //
    if (gametable.isStateStart() == false) { //?
        if (gametable.getUserList().size() < defiNum) { //??
            if (!gametable.getUserList().contains(curUser)) {
                gametable.getUserList().add(curUser);
            }
            resultMessage = "??";
        } else {
            resultMessage = "???";
        }
    } else {
        resultMessage = "????";
    }

    //
    application.setAttribute("gameTableMap", gameTableMap);

    //??
    HttpSession session = request.getSession();
    session.setAttribute("tableId", index);
    session.setAttribute("userList", gameTableMap.get(index).getUserList());

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/waiting.jsp");
    dispatcher.forward(request, response);

    //      PrintWriter out = response.getWriter();
    //      out.print("ID");
    //      out.println(userId);
    //      out.print("?:");
    //      out.println(resultMessage);
    //      out.print("?");
    //      out.println(gametable.getUserList().size());

}

From source file:com.ibm.watson.ta.retail.DemoServlet.java

/**
 * Create and POST a request to the Watson service
 *
 * @param req//from w  w  w. j  a v  a2s  .co m
 *            the Http Servlet request
 * @param resp
 *            the Http Servlet response
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    req.setCharacterEncoding("UTF-8");
    try {
        String queryStr = req.getQueryString();
        String url = baseURL + "/v1/dilemmas";
        if (queryStr != null) {
            url += "?" + queryStr;
        }
        URI uri = new URI(url).normalize();
        logger.info("posting to " + url);

        Request newReq = Request.Post(uri);
        newReq.addHeader("Accept", "application/json");
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream());
        newReq.bodyString(EntityUtils.toString(entity, "UTF-8"), ContentType.APPLICATION_JSON);

        Executor executor = this.buildExecutor(uri);
        Response response = executor.execute(newReq);
        HttpResponse httpResponse = response.returnResponse();
        resp.setStatus(httpResponse.getStatusLine().getStatusCode());

        ServletOutputStream servletOutputStream = resp.getOutputStream();
        httpResponse.getEntity().writeTo(servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();

        logger.info("post done");
    } catch (Exception e) {
        // Log something and return an error message
        logger.log(Level.SEVERE, "got error: " + e.getMessage(), e);
        resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
    }
}

From source file:controller.ProductProcess.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    String fileName = processImage(request, response);

    String todo = request.getParameter("todo");
    String page = "";

    String name = (String) request.getAttribute("name");
    int quantity = Integer.parseInt((String) request.getAttribute("quantity"));
    double price = Double.parseDouble((String) request.getAttribute("price"));
    int categoryID = Integer.parseInt((String) request.getAttribute("category"));
    String description = (String) request.getAttribute("description");
    System.out.println(description);

    Category c = categoryDAO.getCategoryById(categoryID);

    switch (todo) {
    case "add":

        Watch w = new Watch(c, name, price);
        w.setDescription(description);/*from w  ww . j  a v  a2 s  . c  o m*/
        w.setQuantity(quantity);
        w.setImage(fileName);
        watchDAO.addOrUpdateWatch(w);
        page = "admin-addProduct.jsp";
        break;
    case "edit":
        String image = request.getParameter("imageLink");
        int id = Integer.parseInt(request.getParameter("idWatch"));
        Watch w1 = new Watch(c, name, price);
        w1.setDescription(description);
        w1.setQuantity(quantity);
        w1.setImage(image);
        w1.setWatchId(id);
        watchDAO.addOrUpdateWatch(w1);
        page = "admin-product.jsp";
        break;
    }

    request.getRequestDispatcher(page).forward(request, response);
}