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:ua.aits.crc.controller.SystemController.java

@RequestMapping(value = "/system/do/insertdata", method = RequestMethod.POST)
public ModelAndView addArticle(HttpServletRequest request) throws SQLException, ClassNotFoundException,
        InstantiationException, IllegalAccessException, UnsupportedEncodingException, IOException {
    request.setCharacterEncoding("UTF-8");
    String titleEN = request.getParameter("titleEN");
    String titleUA = request.getParameter("titleUA");
    String textEN = request.getParameter("textEN");
    String textUA = request.getParameter("textUA");
    String textAvaUA = request.getParameter("avatar_textUA");
    String textAvaEN = request.getParameter("avatar_textEN");
    String avatar = request.getParameter("avatar_path");
    String category = request.getParameter("category");
    Projects.insertProject(titleEN, titleUA, textEN, textUA, textAvaEN, textAvaUA, avatar, category);
    return new ModelAndView("redirect:" + "/system/index/" + category);
}

From source file:com.netcracker.tss.web.servlet.customer.CustomerOrderTaxiEditDeleteServlet.java

private void redirectToEdit(HttpServletRequest req, HttpServletResponse resp, String error)
        throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    resp.setCharacterEncoding("UTF-8");
    DateFormat format = new SimpleDateFormat("HH:mm, dd MM yyyy", Locale.ENGLISH);
    UserBeanLocal userBeanLocal = getUserBean(req);
    req.setAttribute("personal_addr", userBeanLocal.toPersonalAddress(UserUtils.findCurrentUser()));
    TaxiOrder taxiOrder = getTaxiOrderBean(req).getOrderById(taxiOrderId);
    TaxiOrderHistory toh = getTaxiOrderBean(req).getOrderForEdit(taxiOrder);
    req.setAttribute("orderTime", format.format(toh.getOrderTime()));
    req.setAttribute("toh", toh);
    req.setAttribute("errorMessage", error);
    req.setAttribute("pageContent", "content/editTaxiOrder.jsp");
    req.setAttribute("pageType", "editpage");
    req.getRequestDispatcher("/WEB-INF/views/customer/customer-template.jsp").forward(req, resp);
}

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

@RequestMapping(value = "/system/do/editdata", method = RequestMethod.POST)
public ModelAndView editArticle(HttpServletRequest request) throws SQLException, ClassNotFoundException,
        InstantiationException, IllegalAccessException, UnsupportedEncodingException, IOException {
    request.setCharacterEncoding("UTF-8");
    String id = request.getParameter("project_id");
    String titleEN = request.getParameter("titleEN");
    String titleUA = request.getParameter("titleUA");
    String textEN = request.getParameter("textEN");
    String textUA = request.getParameter("textUA");
    String textAvaUA = request.getParameter("avatar_textUA");
    String textAvaEN = request.getParameter("avatar_textEN");
    String avatar = request.getParameter("avatar_path");
    String category = request.getParameter("category");

    Projects.updateProject(id, titleEN, titleUA, textEN, textUA, textAvaEN, textAvaUA, avatar, category);
    return new ModelAndView("redirect:" + "/system/index/" + category);
}

From source file:com.dlshouwen.wzgl.servlet.UploadPic.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    String albumId = request.getParameter("albumId");
    //      String articleId = request.getParameter("articleId");
    String type = request.getParameter("albumFlag");
    //      String isFile = request.getParameter("isFile");
    //      String isVideo = request.getParameter("isVideo");
    PictureDao pictureDao = null;/*w  w w .ja va 2 s  .  co m*/
    try {
        pictureDao = (PictureDao) SpringUtils.getBean("pictureDao");
    } catch (Exception ex) {
        Logger.getLogger(UploadPic.class.getName()).log(Level.SEVERE, null, ex);
    }

    //    
    String tempPath = SysConfigLoader.getSystemConfig().getProperty("imageTemp", "C:\\files\\temp");
    //  
    File dirTempFile = new File(tempPath);
    if (!dirTempFile.exists()) {
        dirTempFile.mkdirs();
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(20 * 1024 * 1024); //5M     
    factory.setRepository(new File(tempPath)); //     
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    try {
        List items = upload.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            String fileName = item.getName();
            if (!item.isFormField()) {
                InputStream is = null;
                synchronized (this) {
                    try {
                        is = item.getInputStream();
                        JSONObject jobj = FileUploadClient.upFile(request, fileName, is);
                        String path = null;
                        if (null != jobj && jobj.getString("responseMessage").equals("OK")) {
                            if (StringUtils.isNotEmpty(jobj.getString("fpath"))) {
                                String sourceURL = AttributeUtils.getAttributeContent(
                                        request.getServletContext(), "source_webapp_file_postion");
                                path = sourceURL + jobj.getString("fpath");
                                //                                  filename = path.substring(path.lastIndexOf(File.separator) + 1);
                            }
                        }

                        if (albumId != null && albumId.trim().length() > 0) {
                            Picture pic = new Picture();
                            if (type != null) {
                                pic.setFlag(type);
                            }
                            pic.setPicture_name(fileName);
                            pic.setPath(path);
                            pic.setAlbum_id(albumId);
                            pic.setCreate_time(new Date());
                            SessionUser sessionUser = (SessionUser) request.getSession()
                                    .getAttribute(CONFIG.SESSION_USER);
                            String userName = sessionUser.getUser_name();
                            pic.setUser_name(userName);
                            pictureDao.insertPicture(pic);
                        }

                        String json = "{ \"state\": \"SUCCESS\",\"url\": \"" + path + "\",\"title\": \""
                                + fileName + "\",\"original\": \"" + fileName + "\"}";

                        response.setContentType("text/html;charset=utf-8");
                        response.setCharacterEncoding("UTF-8");
                        response.getWriter().print(json);
                    } catch (Exception ex) {
                        java.util.logging.Logger.getLogger(UploadPic.class.getName()).log(Level.SEVERE, null,
                                ex);
                    } finally {
                        if (is != null) {
                            is.close();
                        }
                    }
                }
            }
        }

    } catch (FileUploadException e) {
    }
}

From source file:org.bonitasoft.console.common.server.login.servlet.LoginServlet.java

@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException {

    // force post request body to UTF-8
    try {/*w w w . j  av  a2  s .co m*/
        request.setCharacterEncoding(CharEncoding.UTF_8);
    } catch (final UnsupportedEncodingException e) {
        // should never appear
        throw new ServletException(e);
    }

    final boolean redirectAfterLogin = hasRedirection(request);
    final String redirectURL = getRedirectUrl(request, redirectAfterLogin);
    try {
        doLogin(request);
        final APISession apiSession = (APISession) request.getSession()
                .getAttribute(SessionUtil.API_SESSION_PARAM_KEY);
        // if there a redirect=false attribute in the request do nothing (API login), otherwise, redirect (Portal login)
        if (redirectAfterLogin) {
            if (apiSession.isTechnicalUser() || TenantsManagementUtils.hasProfileForUser(apiSession)) {
                response.sendRedirect(createRedirectUrl(request, redirectURL));
            } else {
                request.setAttribute(LOGIN_FAIL_MESSAGE, "noProfileForUser");
                getServletContext().getRequestDispatcher(AuthenticationManager.LOGIN_PAGE).forward(request,
                        response);
            }
        }
    } catch (final AuthenticationManagerNotFoundException e) {
        final String message = "Can't get login manager";
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, message, e);
        }
        throw new ServletException(e);
    } catch (final LoginFailedException e) {
        handleLoginFailedException(request, response, redirectAfterLogin, e);
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, "Error while trying to log in", e);
        throw new ServletException(e);
    }
}

From source file:de.jaxenter.eesummit.caroline.gui.filter.LogFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    String remoteAddress = null;//from   w  ww  . j a va  2 s. c o  m
    String sessionId = null;
    String uid = "0";

    long start = 0;
    String url = "";
    String method = "";
    Throwable throwable = null;
    boolean dropped = false;
    String agent = null;
    try {
        Validate.isTrue(request instanceof HttpServletRequest, "filter oops?");
        HttpServletRequest req = (HttpServletRequest) request;

        if (req.getCharacterEncoding() == null || forceRequestEncoding) {
            req.setCharacterEncoding(requestEncoding);
        }

        url = req.getRequestURI();
        method = req.getMethod();
        String qs = req.getQueryString();
        agent = req.getHeader("User-Agent");
        if (qs != null) {
            url += "?" + qs;
        }

        for (String stopUrl : dropUrls) { // does any stopUrl match url
            if (url.indexOf(stopUrl) != -1) {
                dropped = true;
                break; // stop searching
            }
        }

        if (!dropped) {
            if (ndcEnabled) {
                if (ndcAddress) {
                    String forwarded = req.getHeader("X-Forwarded-For");
                    if (forwarded != null) {
                        remoteAddress = forwarded;
                    } else {
                        remoteAddress = request.getRemoteAddr();
                    }
                }
                if (ndcSession) {
                    HttpSession session = req.getSession(false); // do not create
                    if (session != null) {
                        sessionId = session.getId();
                        String sessOID = (String) session.getAttribute("USER_ID_LOG");
                        uid = sessOID == null ? "0" : sessOID;
                    }
                }
            }
            StringBuilder msg = simulateNDC(remoteAddress, sessionId, uid);
            msg.append("request start ").append(method).append(" ").append(url).append(" UA=").append(agent);
            logger.info(msg.toString());
            start = System.currentTimeMillis();
        }

        filterChain.doFilter(request, response);
    } catch (IOException e) {
        throwable = e;
        throw e;
    } catch (ServletException e) {
        if (e.getRootCause() != null) {
            throwable = e.getRootCause();
        } else {
            throwable = e;
        }
        throw e;
    } catch (Throwable e) { // be sure to get all errors
        throwable = e;
        throw new ServletException(e);
    } finally {
        if (!dropped) {
            long time = System.currentTimeMillis() - start;
            StringBuilder msg = simulateNDC(remoteAddress, sessionId, uid);
            msg.append("request done ").append(method).append(" ");
            msg.append(url).append(" time=").append(time).append("ms");

            if (throwable == null) {
                logger.info(msg.toString());
            } else {
                String name = throwable.getClass().getSimpleName();
                msg.append(" ex=").append(name);
                msg.append(" msg=").append(throwable.getMessage());
                if (name.equals("ViewExpiredException") || name.equals("ClientAbortException")) {
                    logger.warn(msg.toString());
                } else {
                    msg.append(" UA=").append(agent); // also log agent in error case
                    logger.error(msg.toString());
                }
            }
        }
    }
}

From source file:com.bluexml.side.Framework.alfresco.shareLanguagePicker.CustomWebScriptServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("Processing request (" + req.getMethod() + ") " + req.getRequestURL()
                + (req.getQueryString() != null ? "?" + req.getQueryString() : ""));
    }//from  w ww. java 2 s .  c o m

    if (req.getCharacterEncoding() == null) {
        req.setCharacterEncoding("UTF-8");
    }
    // initialize the request context
    RequestContext context = null;
    try {
        context = FrameworkHelper.initRequestContext(req);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
    LanguageSetter.setLanguageFromLayoutParam(req, context);

    WebScriptServletRuntime runtime = new WebScriptServletRuntime(container, authenticatorFactory, req, res,
            serverProperties);
    runtime.executeScript();
}

From source file:com.googlecode.jtiger.modules.ecside.filter.ECSideFilter.java

public void doAjaxFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    request.setCharacterEncoding("UTF-8");

    String findAjaxZoneAtClient = request.getParameter(TableConstants.AJAX_FINDZONE_CLIENT);
    if (findAjaxZoneAtClient != null
            && ("false".equalsIgnoreCase(findAjaxZoneAtClient) || "0".equals(findAjaxZoneAtClient))) {
        ECSideAjaxResponseWrapper bufferResponseWrapper = new ECSideAjaxResponseWrapper(response);
        try {//from  ww  w  .ja v  a  2s .c o  m

            String ectableId = request.getParameter(TableConstants.EXTREME_COMPONENTS_INSTANCE);

            chain.doFilter(request, bufferResponseWrapper);
            String zone = bufferResponseWrapper.findSubstring(ECSideUtils.getAjaxBegin(ectableId),
                    ECSideUtils.getAjaxEnd(ectableId));
            HttpServletResponse originalResponse = bufferResponseWrapper.getOriginalResponse();
            if (zone != null) {
                originalResponse.getOutputStream().write(zone.getBytes("UTF-8"));
            }
            // originalResponse.flushBuffer();
            originalResponse.getOutputStream().flush();
            originalResponse.getOutputStream().close();
        } catch (Exception e) {
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().println(
                    "Exception:<br />\n" + ExceptionUtils.formatStackTrace(e).replaceAll("\n", "<br/>\n"));
            response.getWriter().close();

        }
    } else {
        chain.doFilter(request, response);
    }
}

From source file:ilearn.orb.controller.AnnotationController.java

@RequestMapping(value = "/annotated/{userid}", method = RequestMethod.POST)
public ModelAndView annotatedText(Locale locale, ModelMap modelMap, HttpServletRequest request,
        HttpSession session, @PathVariable("userid") Integer userid) {
    try {// w  w w.  j ava 2s  .  c  o m
        request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    ActiveRule activeRules[] = null;
    String activatedRules = request.getParameter("activeRules");
    if (!activatedRules.trim().isEmpty()) {
        String p[] = activatedRules.trim().split(",");
        activeRules = new ActiveRule[p.length];
        for (int i = 0; i < p.length; i++) {
            activeRules[i] = new ActiveRule();
            String q[] = p[i].trim().split("_");
            activeRules[i].category = Integer.parseInt(q[0]);
            activeRules[i].index = Integer.parseInt(q[1]);
            activeRules[i].rule = Integer.parseInt(q[2]);
            activeRules[i].color = Integer.parseInt(q[3].substring(1), 16);
        }
    }
    ModelAndView model = new ModelAndView();
    model.setViewName("annotated");
    try {
        Gson gson = new GsonBuilder().registerTypeAdapter(java.util.Date.class, new UtilDateDeserializer())
                .setDateFormat(DateFormat.LONG).create();
        User[] students = null;
        try {
            String json = UserServices.getProfiles(Integer.parseInt(session.getAttribute("id").toString()),
                    session.getAttribute("auth").toString());
            students = gson.fromJson(json, User[].class);
        } catch (NullPointerException e) {
        }
        if (students == null || students.length == 0) {
            students = HardcodedUsers.defaultStudents();
        }
        modelMap.put("students", students);
        String text = request.getParameter("inputText");
        if (text != null) {
            text = new String(text.getBytes("8859_1"), "UTF-8");
        } else
            text = "";

        modelMap.put("profileId", userid);
        modelMap.put("text", text);
        UserProfile pr = retrieveProfile(session, userid);
        String annotatedJson;
        if (userid > 0)
            annotatedJson = TextServices.getAnnotatedText(userid,
                    pr.getLanguage() == LanguageCode.EN ? "EN" : "GR", session.getAttribute("auth").toString(),
                    text);
        else
            annotatedJson = TextServices.getAnnotatedText(HardcodedUsers.defaultProfileLanguage(userid), text);
        annotatedPack = (new Gson()).fromJson(annotatedJson, AnnotatedPack.class);
        txModule = new TextAnnotationModule();
        txModule.setProfile(pr);
        txModule.initializePresentationModule();
        txModule.setInputHTMLFile(annotatedPack.getHtml());
        txModule.setJSonObject(annotatedPack.getWordSet());
        if (activeRules != null && activeRules.length > 0) {
            for (ActiveRule ar : activeRules) {
                txModule.getPresentationRulesModule().setPresentationRule(ar.category, ar.index, ar.rule);
                txModule.getPresentationRulesModule().setTextColor(ar.category, ar.index, ar.color);
                txModule.getPresentationRulesModule().setHighlightingColor(ar.category, ar.index, ar.color);
                txModule.getPresentationRulesModule().setActivated(ar.category, ar.index, true);
            }
        }
        txModule.annotateText();
        String result = new String(txModule.getAnnotatedHTMLFile());
        modelMap.put("annotatedText", result);
    } catch (NumberFormatException e) {
        //e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return model;
}

From source file:controller.categoryServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    String catimage = "";
    String nameCategory = "";
    String command = "";
    int catogory_id = 0;
    String catogory_imagehidden = "";
    String catogory_image = "";

    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  www .j a v a 2 s  .c  o m*/
        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()) {
                    catimage = new File(item.getName()).getName();
                    String filePath = uploadPath + File.separator + catimage;
                    File storeFile = new File(filePath);

                    item.write(storeFile);
                } else if (item.getFieldName().equals("name")) {
                    nameCategory = item.getString();
                } else if (item.getFieldName().equals("command")) {
                    command = item.getString();
                } else if (item.getFieldName().equals("catid")) {
                    catogory_id = Integer.parseInt(item.getString());
                } else if (item.getFieldName().equals("catogery_imagehidden")) {
                    catogory_imagehidden = item.getString();
                }
            }
        }
    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }

    String url = "", error = "";
    if (nameCategory.equals("")) {
        error = "Vui lng nhp tn danh mc!";
        request.setAttribute("error", error);
    }
    HttpSession session = request.getSession();
    try {
        if (error.length() == 0) {
            CategoryEntity c = new CategoryEntity(nameCategory, catimage);
            switch (command) {
            case "insert":
                if (cate.getListCategoryByName(nameCategory).size() > 0) {
                    System.out.println("ten k ");
                    out.println("ten k dc trung nhau");
                    out.flush();
                    return;
                } else {
                    cate.insertCategory(c);
                    request.setAttribute("er", "thanh cong");
                    url = "/java/admin/ql-category.jsp";
                }
                break;
            case "update":
                if (cate.getListCategoryByName(nameCategory).size() > 0) {
                    System.out.println("ten k ");
                    out.println("ten k dc trung nhau");
                    out.flush();
                    return;
                } else {
                    cate.updateCategory(nameCategory, catimage, catogory_id);
                    url = "/java/admin/ql-category.jsp";
                }
                break;
            }
        } else {
            url = "/java/admin/add-category.jsp";
        }
    } catch (Exception e) {

    }
    response.sendRedirect(url);
}