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.devpia.service.DEXTUploadJController.java

/**
 * ?  ? ? userdata.up  ?  ?  ?? // w  ww  .  j  av  a2 s  .com
 * ??? ? ??(?) ?? .
 * @param req HttpServletRequest ?
 * @param res HttpServletResponse ?
 * @throws Exception
 */
@RequestMapping(value = "/userdata.up", method = RequestMethod.POST)
public void uploadUserData(HttpServletRequest req, HttpServletResponse res) throws Exception {
    req.setCharacterEncoding("utf-8");
    res.setContentType("text/plain");
    res.setCharacterEncoding("utf-8");

    FileUpload dextj = new FileUpload(req, res);

    String appRootPath = null;
    //  ?? ??  ?  ?? ? .
    // ? OS   ?  ?  . (,   ?/  .)
    File temp = new File(getUploadDirectory());
    File repository = new File(getUploadDirectory());

    try {
        //    ?/ ?    ??  .
        if (!temp.exists() || !temp.canRead() || !temp.canWrite()) {
            throw new Exception(
                    "    ?? ?/  ? .");
        }

        //  ?   ?/ ?    ??  .
        if (!repository.exists() || !repository.canRead() || !repository.canWrite()) {
            throw new Exception(
                    "?    ?? ?/  ? .");
        }

        // DEXTUploadJ ?? ?(dextuploadj.config)?  ?? ?  ? .
        // ?     ? .
        appRootPath = req.getSession().getServletContext().getRealPath("/") + "/";
        dextj.setLicenseFilePath(appRootPath.concat("dextuploadj.config"));

        // ?    .
        //     ??    .
        dextj.UploadStart(temp.getAbsolutePath());

        // "DEXTUploadNX_UserData"? DEXTUploadNX? ? ? ? ? ?? ?  .
        String[] userData = dextj.getParameterValues("DEXTUploadNX_UserData");
        if (userData == null)
            userData = new String[0];

        // "DEXTUploadNX"? DEXTUploadNX? ?  ? ??  .
        FileItem[] fileItems = dextj.getFileItemValues("DEXTUploadNX");
        if (fileItems == null)
            fileItems = new FileItem[0];

        // "DEXTUploadNX_UserData", "DEXTUploadNX" ? ? ??   ?? ? ?.

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < fileItems.length; i++) {
            if (fileItems[i].IsUploaded()) {
                fileItems[i].Save(repository.getAbsolutePath(), true);
                sb.append("file: ".concat(fileItems[i].getLastSavedFileName()).concat(", user-data: ")
                        .concat(userData[i]));

            } else {
                sb.append("file: ".concat(fileItems[i].getFileName()).concat(", user-data: ")
                        .concat(userData[i]));
            }
        }

        res.getWriter().write(sb.toString());

    } catch (DEXTUploadException ex) {
        throw new Exception(" ? .", ex);
    } catch (Exception ex) {
        throw new Exception(" ? .", ex);
    } finally {
        //  ?  ???  .
        //    ?? ?  ?  .
        dextj.dispose();
    }
}

From source file:com.devpia.service.DEXTUploadJController.java

/**
 * ?  ? ? formdata.up  ?  ?  ?? //from  w  w w . jav  a 2  s. c  o  m
 * ??? ? ??(?) ?? .
 * @param req HttpServletRequest ?
 * @param res HttpServletResponse ?
 * @throws Exception
 */
@RequestMapping(value = "/formdata.up", method = RequestMethod.POST)
public void uploadFormData(HttpServletRequest req, HttpServletResponse res) throws Exception {
    req.setCharacterEncoding("utf-8");
    res.setContentType("text/plain");
    res.setCharacterEncoding("utf-8");

    FileUpload dextj = new FileUpload(req, res);

    String appRootPath = null;
    //  ?? ??  ?  ?? ? .
    // ? OS   ?  ?  . (,   ?/  .)
    File temp = new File(getUploadDirectory());
    File repository = new File(getUploadDirectory());

    try {
        //    ?/ ?    ??  .
        if (!temp.exists() || !temp.canRead() || !temp.canWrite()) {
            throw new Exception(
                    "    ?? ?/  ? .");
        }

        //  ?   ?/ ?    ??  .
        if (!repository.exists() || !repository.canRead() || !repository.canWrite()) {
            throw new Exception(
                    "?    ?? ?/  ? .");
        }

        // DEXTUploadJ ?? ?(dextuploadj.config)?  ?? ?  ? .
        // ?     ? .
        appRootPath = req.getSession().getServletContext().getRealPath("/") + "/";
        dextj.setLicenseFilePath(appRootPath.concat("dextuploadj.config"));

        // ?    .
        //     ??    .
        dextj.UploadStart(temp.getAbsolutePath());

        // "DEXTUploadNX"? DEXTUploadNX? ?  ? ??  .
        FileItem[] fileItems = dextj.getFileItemValues("DEXTUploadNX");
        if (fileItems == null)
            fileItems = new FileItem[0];
        // ? ?? .
        for (FileItem item : fileItems) {
            if (item.IsUploaded()) {
                item.Save(repository.getAbsolutePath(), true);
            }
        }

        String autoForm1Value = dextj.getParameter("auto_include_form1");
        String autoForm2Value = dextj.getParameter("auto_include_form2");
        String userForm1Value = dextj.getParameter("UserForm1");
        String userForm2Value = dextj.getParameter("UserForm2");

        if (autoForm1Value == null)
            autoForm1Value = "";
        if (autoForm2Value == null)
            autoForm2Value = "";
        if (userForm1Value == null)
            userForm1Value = "";
        if (userForm2Value == null)
            userForm2Value = "";

        res.getWriter()
                .write("[Webformname : auto_include_form1, formvalue: ".concat(autoForm1Value).concat("]"));
        res.getWriter()
                .write("[Webformname : auto_include_form2, formvalue: ".concat(autoForm2Value).concat("]"));
        res.getWriter().write("[forname : UserForm1, formvalue: ".concat(userForm1Value).concat("]"));
        res.getWriter().write("[forname : UserForm2, formvalue: ".concat(userForm2Value).concat("]"));

    } catch (DEXTUploadException ex) {
        throw new Exception(" ? .", ex);
    } catch (Exception ex) {
        throw new Exception(" ? .", ex);
    } finally {
        //  ?  ???  .
        //    ?? ?  ?  .
        dextj.dispose();
    }
}

From source file:com.swiftcorp.portal.question.web.QuestionDispatchAction.java

public ActionForward addQuestion(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SystemException, BusinessRuleViolationException, Exception {
    request.setCharacterEncoding("UTF-8");

    log.info("addQuestion() : Enter");
    List mcqoptions = new ArrayList();
    MCQOptionDTO mcqOptionDTO = null;/*from  w ww . j  a v a2 s.  com*/
    String mcqOptionNumber = request.getParameter("mcqOptionNumber");
    int mcqNo = 0;
    if (mcqOptionNumber != null && !mcqOptionNumber.equals("null") && mcqOptionNumber.length() > 0) {
        mcqNo = Integer.parseInt(mcqOptionNumber);
    }
    HttpSession session = request.getSession();
    DynaValidatorActionForm questionForm = (DynaValidatorActionForm) form;
    QuestionDTO questionDTO = (QuestionDTO) questionForm.get("question");
    long categoryId = (Long) questionForm.get("category");

    // now get the role dto from the database
    CategoryTypeDTO categoryTypeDTO = (CategoryTypeDTO) questionService.getCategory(categoryId);

    if (categoryTypeDTO == null) {
        throw new SystemException("Category is found null");
    }
    questionDTO.setCategoryType(categoryTypeDTO);

    long answerTypeId = (Long) questionForm.get("answerType");

    AnswerTypeDTO answerTypeDTO = (AnswerTypeDTO) questionService.getAnswerType(answerTypeId);

    if (answerTypeDTO == null) {
        throw new SystemException("Answer is found null");
    }

    // encode the question name
    String questionName = questionDTO.getQuestionName();
    String utfQuestionName = new String(questionName.getBytes("UTF-8"), "UTF-8");
    System.out.println("Converted:" + questionName + " to:" + utfQuestionName);
    List<ValidationDTO> validationDTOList = this.populateValidationDTOFromReq(questionDTO, request,
            answerTypeDTO);
    questionDTO.setValidationDTOList(validationDTOList);
    questionDTO.setQuestionName(utfQuestionName);
    // get questionId
    String questionId = request.getParameter("question.questionId");
    questionDTO.setQuestionId("" + questionId);
    questionDTO.setAnswerType(answerTypeDTO);
    for (int i = 0; i < mcqNo; i++) {
        mcqOptionDTO = new MCQOptionDTO();
        mcqOptionDTO.setName(request.getParameter("mcq" + i));
        mcqOptionDTO.setValue(request.getParameter("value" + i));
        mcqOptionDTO.setQuestionDTO(questionDTO);
        mcqoptions.add(mcqOptionDTO);
    }
    if (mcqoptions != null && mcqoptions.size() > 0) {
        questionDTO.setMcqOptionList(mcqoptions);
    }
    String[][] messageArgValues = { { questionDTO.getQuestionName() } };

    try {
        questionService.add(questionDTO);
    } catch (Exception e) {
        log.info("questionAdd() : ", e);
        throw e;
    }

    WebUtils.setSuccessMessages(request, MessageKeys.ADD_SUCCESS_MESSAGE_KEYS, messageArgValues);
    log.info("addQuestion() : Exit");
    return promptQuestionSearchSystemLevel(mapping, form, request, response);
}

From source file:net.lightbody.bmp.proxy.jetty.servlet.Dump.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute("Dump", this);
    request.setCharacterEncoding("ISO_8859_1");
    getServletContext().setAttribute("Dump", this);

    String info = request.getPathInfo();
    if (info != null && info.endsWith("Exception")) {
        try {//ww  w . j  av a  2 s .c o  m
            throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance());
        } catch (Throwable th) {
            throw new ServletException(th);
        }
    }

    String redirect = request.getParameter("redirect");
    if (redirect != null && redirect.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendRedirect(redirect);
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String error = request.getParameter("error");
    if (error != null && error.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendError(Integer.parseInt(error));
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String length = request.getParameter("length");
    if (length != null && length.length() > 0) {
        response.setContentLength(Integer.parseInt(length));
    }

    String buffer = request.getParameter("buffer");
    if (buffer != null && buffer.length() > 0)
        response.setBufferSize(Integer.parseInt(buffer));

    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");

    if (info != null && info.indexOf("Locale/") >= 0) {
        try {
            String locale_name = info.substring(info.indexOf("Locale/") + 7);
            Field f = java.util.Locale.class.getField(locale_name);
            response.setLocale((Locale) f.get(null));
        } catch (Exception e) {
            LogSupport.ignore(log, e);
            response.setLocale(Locale.getDefault());
        }
    }

    String cn = request.getParameter("cookie");
    String cv = request.getParameter("value");
    String v = request.getParameter("version");
    if (cn != null && cv != null) {
        Cookie cookie = new Cookie(cn, cv);
        cookie.setComment("Cookie from dump servlet");
        if (v != null) {
            cookie.setMaxAge(300);
            cookie.setPath("/");
            cookie.setVersion(Integer.parseInt(v));
        }
        response.addCookie(cookie);
    }

    String pi = request.getPathInfo();
    if (pi != null && pi.startsWith("/ex")) {
        OutputStream out = response.getOutputStream();
        out.write("</H1>This text should be reset</H1>".getBytes());
        if ("/ex0".equals(pi))
            throw new ServletException("test ex0", new Throwable());
        if ("/ex1".equals(pi))
            throw new IOException("test ex1");
        if ("/ex2".equals(pi))
            throw new UnavailableException("test ex2");
        if ("/ex3".equals(pi))
            throw new HttpException(501);
    }

    PrintWriter pout = response.getWriter();
    Page page = null;

    try {
        page = new Page();
        page.title("Dump Servlet");

        page.add(new Heading(1, "Dump Servlet"));
        Table table = new Table(0).cellPadding(0).cellSpacing(0);
        page.add(table);
        table.newRow();
        table.addHeading("getMethod:&nbsp;").cell().right();
        table.addCell("" + request.getMethod());
        table.newRow();
        table.addHeading("getContentLength:&nbsp;").cell().right();
        table.addCell(Integer.toString(request.getContentLength()));
        table.newRow();
        table.addHeading("getContentType:&nbsp;").cell().right();
        table.addCell("" + request.getContentType());
        table.newRow();
        table.addHeading("getCharacterEncoding:&nbsp;").cell().right();
        table.addCell("" + request.getCharacterEncoding());
        table.newRow();
        table.addHeading("getRequestURI:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURI());
        table.newRow();
        table.addHeading("getRequestURL:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURL());
        table.newRow();
        table.addHeading("getContextPath:&nbsp;").cell().right();
        table.addCell("" + request.getContextPath());
        table.newRow();
        table.addHeading("getServletPath:&nbsp;").cell().right();
        table.addCell("" + request.getServletPath());
        table.newRow();
        table.addHeading("getPathInfo:&nbsp;").cell().right();
        table.addCell("" + request.getPathInfo());
        table.newRow();
        table.addHeading("getPathTranslated:&nbsp;").cell().right();
        table.addCell("" + request.getPathTranslated());
        table.newRow();
        table.addHeading("getQueryString:&nbsp;").cell().right();
        table.addCell("" + request.getQueryString());

        table.newRow();
        table.addHeading("getProtocol:&nbsp;").cell().right();
        table.addCell("" + request.getProtocol());
        table.newRow();
        table.addHeading("getScheme:&nbsp;").cell().right();
        table.addCell("" + request.getScheme());
        table.newRow();
        table.addHeading("getServerName:&nbsp;").cell().right();
        table.addCell("" + request.getServerName());
        table.newRow();
        table.addHeading("getServerPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getServerPort()));
        table.newRow();
        table.addHeading("getLocalName:&nbsp;").cell().right();
        table.addCell("" + request.getLocalName());
        table.newRow();
        table.addHeading("getLocalAddr:&nbsp;").cell().right();
        table.addCell("" + request.getLocalAddr());
        table.newRow();
        table.addHeading("getLocalPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getLocalPort()));
        table.newRow();
        table.addHeading("getRemoteUser:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteUser());
        table.newRow();
        table.addHeading("getRemoteAddr:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteAddr());
        table.newRow();
        table.addHeading("getRemoteHost:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteHost());
        table.newRow();
        table.addHeading("getRemotePort:&nbsp;").cell().right();
        table.addCell("" + request.getRemotePort());
        table.newRow();
        table.addHeading("getRequestedSessionId:&nbsp;").cell().right();
        table.addCell("" + request.getRequestedSessionId());
        table.newRow();
        table.addHeading("isSecure():&nbsp;").cell().right();
        table.addCell("" + request.isSecure());

        table.newRow();
        table.addHeading("isUserInRole(admin):&nbsp;").cell().right();
        table.addCell("" + request.isUserInRole("admin"));

        table.newRow();
        table.addHeading("getLocale:&nbsp;").cell().right();
        table.addCell("" + request.getLocale());

        Enumeration locales = request.getLocales();
        while (locales.hasMoreElements()) {
            table.newRow();
            table.addHeading("getLocales:&nbsp;").cell().right();
            table.addCell(locales.nextElement());
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers")
                .attribute("COLSPAN", "2").left();
        Enumeration h = request.getHeaderNames();
        String name;
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();

            Enumeration h2 = request.getHeaders(name);
            while (h2.hasMoreElements()) {
                String hv = (String) h2.nextElement();
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().right();
                table.addCell(hv);
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters")
                .attribute("COLSPAN", "2").left();
        h = request.getParameterNames();
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().right();
            table.addCell(request.getParameter(name));
            String[] values = request.getParameterValues(name);
            if (values == null) {
                table.newRow();
                table.addHeading(name + " Values:&nbsp;").cell().right();
                table.addCell("NULL!!!!!!!!!");
            } else if (values.length > 1) {
                for (int i = 0; i < values.length; i++) {
                    table.newRow();
                    table.addHeading(name + "[" + i + "]:&nbsp;").cell().right();
                    table.addCell(values[i]);
                }
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left();
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            table.newRow();
            table.addHeading(cookie.getName() + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell(cookie.getValue());
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes")
                .attribute("COLSPAN", "2").left();
        Enumeration a = request.getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>");
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>");
        }

        if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")
                && request.getContentLength() < 1000000) {
            MultiPartRequest multi = new MultiPartRequest(request);
            String[] parts = multi.getPartNames();

            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content")
                    .attribute("COLSPAN", "2").left();
            for (int p = 0; p < parts.length; p++) {
                name = parts[p];
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
                table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>");
            }
        }

        String res = request.getParameter("resource");
        if (res != null && res.length() > 0) {
            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res)
                    .attribute("COLSPAN", "2").left();

            table.newRow();
            table.addHeading("this.getClass():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getResource(res));

            table.newRow();
            table.addHeading("this.getClass().getClassLoader():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getClassLoader().getResource(res));

            table.newRow();
            table.addHeading("Thread.currentThread().getContextClassLoader():&nbsp;").cell().right();
            table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res));

            table.newRow();
            table.addHeading("getServletContext():&nbsp;").cell().right();
            try {
                table.addCell("" + getServletContext().getResource(res));
            } catch (Exception e) {
                table.addCell("" + e);
            }
        }

        /* ------------------------------------------------------------ */
        page.add(Break.para);
        page.add(new Heading(1, "Request Wrappers"));
        ServletRequest rw = request;
        int w = 0;
        while (rw != null) {
            page.add((w++) + ": " + rw.getClass().getName() + "<br/>");
            if (rw instanceof HttpServletRequestWrapper)
                rw = ((HttpServletRequestWrapper) rw).getRequest();
            else if (rw instanceof ServletRequestWrapper)
                rw = ((ServletRequestWrapper) rw).getRequest();
            else
                rw = null;
        }

        page.add(Break.para);
        page.add(new Heading(1, "International Characters"));
        page.add("Directly encoced:  Drst<br/>");
        page.add("HTML reference: D&uuml;rst<br/>");
        page.add("Decimal (252) 8859-1: D&#252;rst<br/>");
        page.add("Hex (xFC) 8859-1: D&#xFC;rst<br/>");
        page.add(
                "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>");
        page.add(Break.para);
        page.add(new Heading(1, "Form to generate GET content"));
        TableForm tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("GET");
        tf.addTextField("TextField", "TextField", 20, "value");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(Break.para);
        page.add(new Heading(1, "Form to generate POST content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("TextField", "TextField", 20, "value");
        Select select = tf.addSelect("Select", "Select", true, 3);
        select.add("ValueA");
        select.add("ValueB1,ValueB2");
        select.add("ValueC");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(new Heading(1, "Form to upload content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.attribute("enctype", "multipart/form-data");
        tf.addFileField("file", "file");
        tf.addButton("Upload", "Upload");
        page.add(tf);

        page.add(new Heading(1, "Form to get Resource"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("resource", "resource", 20, "");
        tf.addButton("Action", "getResource");
        page.add(tf);

    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }

    page.write(pout);

    String data = request.getParameter("data");
    if (data != null && data.length() > 0) {
        int d = Integer.parseInt(data);
        while (d > 0) {
            pout.println("1234567890123456789012345678901234567890123456789\n");
            d = d - 50;

        }
    }

    pout.close();

    if (pi != null) {
        if ("/ex4".equals(pi))
            throw new ServletException("test ex4", new Throwable());
        if ("/ex5".equals(pi))
            throw new IOException("test ex5");
        if ("/ex6".equals(pi))
            throw new UnavailableException("test ex6");
        if ("/ex7".equals(pi))
            throw new HttpException(501);
    }

    request.getInputStream().close();

}

From source file:com.hp.action.ProductsAction.java

public String searchProducts() throws UnsupportedEncodingException {
    HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
            .get(ServletActionContext.HTTP_REQUEST);
    HttpSession session = request.getSession();
    request.setCharacterEncoding("UTF8");

    //Authorize/*from w ww . ja v a  2 s. co  m*/
    if (!userDAO.authorize((String) session.getAttribute("user_name"),
            (String) session.getAttribute("user_password"))) {
        return LOGIN;
    }

    String para = request.getParameter("search_text");
    System.out.println("__" + para);
    productsList = productDAO.getSearchProductList(para);

    return SUCCESS;
}

From source file:com.devpia.service.DEXTUploadJController.java

/**
 * ?  ? ? response.up  ?  ?  ?? /*from   w  ww  . j  a va 2s .co m*/
 * ??? ? ??(?) ?? .
 * @param req HttpServletRequest ?
 * @param res HttpServletResponse ?
 * @throws Exception
 */
@RequestMapping(value = "/response.up", method = RequestMethod.POST)
public void uploadResponse(HttpServletRequest req, HttpServletResponse res) throws Exception {
    req.setCharacterEncoding("utf-8");
    res.setContentType("text/plain");
    res.setCharacterEncoding("utf-8");

    FileUpload dextj = new FileUpload(req, res);

    String appRootPath = null;
    //  ?? ??  ?  ?? ? .
    // ? OS   ?  ?  . (,   ?/  .)
    File temp = new File(getUploadDirectory());
    File repository = new File(getUploadDirectory());

    try {
        //    ?/ ?    ??  .
        if (!temp.exists() || !temp.canRead() || !temp.canWrite()) {
            throw new Exception(
                    "    ?? ?/  ? .");
        }

        //  ?   ?/ ?    ??  .
        if (!repository.exists() || !repository.canRead() || !repository.canWrite()) {
            throw new Exception(
                    "?    ?? ?/  ? .");
        }

        // DEXTUploadJ ?? ?(dextuploadj.config)?  ?? ?  ? .
        // ?     ? .
        appRootPath = req.getSession().getServletContext().getRealPath("/") + "/";
        dextj.setLicenseFilePath(appRootPath.concat("dextuploadj.config"));

        // ?    .
        //     ??    .
        dextj.UploadStart(temp.getAbsolutePath());

        File targetFolder = null;
        StringBuilder responseData = new StringBuilder();

        // "DEXTUploadNX_EmptyFolderPath"? DEXTUploadNX? ?  ??()  ?  .
        String[] emptyFolderNames = dextj.getParameterValues("DEXTUploadNX_EmptyFolderPath");
        if (emptyFolderNames == null)
            emptyFolderNames = new String[0];
        for (String nextName : emptyFolderNames) {
            targetFolder = new File(repository, nextName);
            if (!targetFolder.exists()) {
                targetFolder.mkdir();
                responseData.append("Create Folder : ".concat(targetFolder.getName()));
                responseData.append("[SPLIT]");
            } else {
                responseData.append("Existing Folder : ".concat(targetFolder.getName()));
                responseData.append("[SPLIT]");
            }
        }

        // "DEXTUploadNX_FolderPath"? DEXTUploadNX? ? ??()  ?  .
        String[] folderNames = dextj.getParameterValues("DEXTUploadNX_FolderPath");
        if (folderNames == null)
            folderNames = new String[0];

        // "DEXTUploadNX"? DEXTUploadNX? ?  ? ??  .
        FileItem[] fileItems = dextj.getFileItemValues("DEXTUploadNX");
        if (fileItems == null)
            fileItems = new FileItem[0];

        // "DEXTUploadNX_FolderPath", "DEXTUploadNX" ? ? ?? ??   ?? ? ?.

        for (int i = 0; i < folderNames.length; i++) {
            targetFolder = new File(repository, folderNames[i]);
            if (!targetFolder.exists()) {
                targetFolder.mkdir();
                responseData.append("Create Folder : ".concat(targetFolder.getName()));
                responseData.append("[SPLIT]");
            } else {
                responseData.append("Existing Folder : ".concat(targetFolder.getName()));
                responseData.append("[SPLIT]");
            }

            if (fileItems[i].IsUploaded()) {
                fileItems[i].Save(targetFolder.getAbsolutePath(), true);
                responseData.append("Save file : ".concat(fileItems[i].getLastSavedFileName()));
                responseData.append("[SPLIT]");
            }
        }

        res.getWriter().write(responseData.toString());

    } catch (DEXTUploadException ex) {
        throw new Exception(" ? .", ex);
    } catch (Exception ex) {
        throw new Exception(" ? .", ex);
    } finally {
        //  ?  ???  .
        //    ?? ?  ?  .
        dextj.dispose();
    }
}

From source file:org.openqa.jetty.servlet.Dump.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute("Dump", this);
    request.setCharacterEncoding("ISO_8859_1");
    getServletContext().setAttribute("Dump", this);

    String info = request.getPathInfo();
    if (info != null && info.endsWith("Exception")) {
        try {/*from w ww .ja v  a2 s.c  om*/
            throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance());
        } catch (Throwable th) {
            throw new ServletException(th);
        }
    }

    String redirect = request.getParameter("redirect");
    if (redirect != null && redirect.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendRedirect(redirect);
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String error = request.getParameter("error");
    if (error != null && error.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendError(Integer.parseInt(error));
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String length = request.getParameter("length");
    if (length != null && length.length() > 0) {
        response.setContentLength(Integer.parseInt(length));
    }

    String buffer = request.getParameter("buffer");
    if (buffer != null && buffer.length() > 0)
        response.setBufferSize(Integer.parseInt(buffer));

    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");

    if (info != null && info.indexOf("Locale/") >= 0) {
        try {
            String locale_name = info.substring(info.indexOf("Locale/") + 7);
            Field f = java.util.Locale.class.getField(locale_name);
            response.setLocale((Locale) f.get(null));
        } catch (Exception e) {
            LogSupport.ignore(log, e);
            response.setLocale(Locale.getDefault());
        }
    }

    String cn = request.getParameter("cookie");
    String cv = request.getParameter("value");
    String v = request.getParameter("version");
    if (cn != null && cv != null) {
        Cookie cookie = new Cookie(cn, cv);
        cookie.setComment("Cookie from dump servlet");
        if (v != null) {
            cookie.setMaxAge(300);
            cookie.setPath("/");
            cookie.setVersion(Integer.parseInt(v));
        }
        response.addCookie(cookie);
    }

    String pi = request.getPathInfo();
    if (pi != null && pi.startsWith("/ex")) {
        OutputStream out = response.getOutputStream();
        out.write("</H1>This text should be reset</H1>".getBytes());
        if ("/ex0".equals(pi))
            throw new ServletException("test ex0", new Throwable());
        if ("/ex1".equals(pi))
            throw new IOException("test ex1");
        if ("/ex2".equals(pi))
            throw new UnavailableException("test ex2");
        if ("/ex3".equals(pi))
            throw new HttpException(501);
    }

    PrintWriter pout = response.getWriter();
    Page page = null;

    try {
        page = new Page();
        page.title("Dump Servlet");

        page.add(new Heading(1, "Dump Servlet"));
        Table table = new Table(0).cellPadding(0).cellSpacing(0);
        page.add(table);
        table.newRow();
        table.addHeading("getMethod:&nbsp;").cell().right();
        table.addCell("" + request.getMethod());
        table.newRow();
        table.addHeading("getContentLength:&nbsp;").cell().right();
        table.addCell(Integer.toString(request.getContentLength()));
        table.newRow();
        table.addHeading("getContentType:&nbsp;").cell().right();
        table.addCell("" + request.getContentType());
        table.newRow();
        table.addHeading("getCharacterEncoding:&nbsp;").cell().right();
        table.addCell("" + request.getCharacterEncoding());
        table.newRow();
        table.addHeading("getRequestURI:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURI());
        table.newRow();
        table.addHeading("getRequestURL:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURL());
        table.newRow();
        table.addHeading("getContextPath:&nbsp;").cell().right();
        table.addCell("" + request.getContextPath());
        table.newRow();
        table.addHeading("getServletPath:&nbsp;").cell().right();
        table.addCell("" + request.getServletPath());
        table.newRow();
        table.addHeading("getPathInfo:&nbsp;").cell().right();
        table.addCell("" + request.getPathInfo());
        table.newRow();
        table.addHeading("getPathTranslated:&nbsp;").cell().right();
        table.addCell("" + request.getPathTranslated());
        table.newRow();
        table.addHeading("getQueryString:&nbsp;").cell().right();
        table.addCell("" + request.getQueryString());

        table.newRow();
        table.addHeading("getProtocol:&nbsp;").cell().right();
        table.addCell("" + request.getProtocol());
        table.newRow();
        table.addHeading("getScheme:&nbsp;").cell().right();
        table.addCell("" + request.getScheme());
        table.newRow();
        table.addHeading("getServerName:&nbsp;").cell().right();
        table.addCell("" + request.getServerName());
        table.newRow();
        table.addHeading("getServerPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getServerPort()));
        table.newRow();
        table.addHeading("getLocalName:&nbsp;").cell().right();
        table.addCell("" + request.getLocalName());
        table.newRow();
        table.addHeading("getLocalAddr:&nbsp;").cell().right();
        table.addCell("" + request.getLocalAddr());
        table.newRow();
        table.addHeading("getLocalPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getLocalPort()));
        table.newRow();
        table.addHeading("getRemoteUser:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteUser());
        table.newRow();
        table.addHeading("getRemoteAddr:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteAddr());
        table.newRow();
        table.addHeading("getRemoteHost:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteHost());
        table.newRow();
        table.addHeading("getRemotePort:&nbsp;").cell().right();
        table.addCell("" + request.getRemotePort());
        table.newRow();
        table.addHeading("getRequestedSessionId:&nbsp;").cell().right();
        table.addCell("" + request.getRequestedSessionId());
        table.newRow();
        table.addHeading("isSecure():&nbsp;").cell().right();
        table.addCell("" + request.isSecure());

        table.newRow();
        table.addHeading("isUserInRole(admin):&nbsp;").cell().right();
        table.addCell("" + request.isUserInRole("admin"));

        table.newRow();
        table.addHeading("getLocale:&nbsp;").cell().right();
        table.addCell("" + request.getLocale());

        Enumeration locales = request.getLocales();
        while (locales.hasMoreElements()) {
            table.newRow();
            table.addHeading("getLocales:&nbsp;").cell().right();
            table.addCell(locales.nextElement());
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers")
                .attribute("COLSPAN", "2").left();
        Enumeration h = request.getHeaderNames();
        String name;
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();

            Enumeration h2 = request.getHeaders(name);
            while (h2.hasMoreElements()) {
                String hv = (String) h2.nextElement();
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().right();
                table.addCell(hv);
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters")
                .attribute("COLSPAN", "2").left();
        h = request.getParameterNames();
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().right();
            table.addCell(request.getParameter(name));
            String[] values = request.getParameterValues(name);
            if (values == null) {
                table.newRow();
                table.addHeading(name + " Values:&nbsp;").cell().right();
                table.addCell("NULL!!!!!!!!!");
            } else if (values.length > 1) {
                for (int i = 0; i < values.length; i++) {
                    table.newRow();
                    table.addHeading(name + "[" + i + "]:&nbsp;").cell().right();
                    table.addCell(values[i]);
                }
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left();
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            table.newRow();
            table.addHeading(cookie.getName() + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell(cookie.getValue());
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes")
                .attribute("COLSPAN", "2").left();
        Enumeration a = request.getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>");
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>");
        }

        if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")
                && request.getContentLength() < 1000000) {
            MultiPartRequest multi = new MultiPartRequest(request);
            String[] parts = multi.getPartNames();

            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content")
                    .attribute("COLSPAN", "2").left();
            for (int p = 0; p < parts.length; p++) {
                name = parts[p];
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
                table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>");
            }
        }

        String res = request.getParameter("resource");
        if (res != null && res.length() > 0) {
            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res)
                    .attribute("COLSPAN", "2").left();

            table.newRow();
            table.addHeading("this.getClass():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getResource(res));

            table.newRow();
            table.addHeading("this.getClass().getClassLoader():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getClassLoader().getResource(res));

            table.newRow();
            table.addHeading("Thread.currentThread().getContextClassLoader():&nbsp;").cell().right();
            table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res));

            table.newRow();
            table.addHeading("getServletContext():&nbsp;").cell().right();
            try {
                table.addCell("" + getServletContext().getResource(res));
            } catch (Exception e) {
                table.addCell("" + e);
            }
        }

        /* ------------------------------------------------------------ */
        page.add(Break.para);
        page.add(new Heading(1, "Request Wrappers"));
        ServletRequest rw = request;
        int w = 0;
        while (rw != null) {
            page.add((w++) + ": " + rw.getClass().getName() + "<br/>");
            if (rw instanceof HttpServletRequestWrapper)
                rw = ((HttpServletRequestWrapper) rw).getRequest();
            else if (rw instanceof ServletRequestWrapper)
                rw = ((ServletRequestWrapper) rw).getRequest();
            else
                rw = null;
        }

        page.add(Break.para);
        page.add(new Heading(1, "International Characters"));
        page.add("Directly encoced:  Drst<br/>");
        page.add("HTML reference: D&uuml;rst<br/>");
        page.add("Decimal (252) 8859-1: D&#252;rst<br/>");
        page.add("Hex (xFC) 8859-1: D&#xFC;rst<br/>");
        page.add(
                "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>");
        page.add(Break.para);
        page.add(new Heading(1, "Form to generate GET content"));
        TableForm tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("GET");
        tf.addTextField("TextField", "TextField", 20, "value");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(Break.para);
        page.add(new Heading(1, "Form to generate POST content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("TextField", "TextField", 20, "value");
        Select select = tf.addSelect("Select", "Select", true, 3);
        select.add("ValueA");
        select.add("ValueB1,ValueB2");
        select.add("ValueC");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(new Heading(1, "Form to upload content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.attribute("enctype", "multipart/form-data");
        tf.addFileField("file", "file");
        tf.addButton("Upload", "Upload");
        page.add(tf);

        page.add(new Heading(1, "Form to get Resource"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("resource", "resource", 20, "");
        tf.addButton("Action", "getResource");
        page.add(tf);

    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }

    page.write(pout);

    String data = request.getParameter("data");
    if (data != null && data.length() > 0) {
        int d = Integer.parseInt(data);
        while (d > 0) {
            pout.println("1234567890123456789012345678901234567890123456789\n");
            d = d - 50;

        }
    }

    pout.close();

    if (pi != null) {
        if ("/ex4".equals(pi))
            throw new ServletException("test ex4", new Throwable());
        if ("/ex5".equals(pi))
            throw new IOException("test ex5");
        if ("/ex6".equals(pi))
            throw new UnavailableException("test ex6");
        if ("/ex7".equals(pi))
            throw new HttpException(501);
    }

    request.getInputStream().close();

}

From source file:com.icb123.Controller.ManageController.java

@RequestMapping(value = "/forJsp")
public String forJsp(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {/*from  w w w. j a v  a 2s . c o  m*/
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Constants.root = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();
        String sysRootPath = request.getSession().getServletContext().getRealPath("\\");
        SystemStaticArgsSet.setSysRootPath(sysRootPath);
        String requestType = request.getParameter("requestType") == null ? ""
                : request.getParameter("requestType");
        int pageSize = 10;
        Employee emp = (Employee) request.getSession().getAttribute("Employee");
        if ("1".equals(requestType)) {//session
            //System.out.println("requestType");
            request.getSession().removeAttribute("Employee");
            request.getSession().removeAttribute("code");
            return "/pcManager/index.html";
        } else if ("2".equals(requestType)) {//?
            String nam1 = request.getParameter("num1") == null ? "" : request.getParameter("num1");
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            int rowCount = employeeManager.countEmployee();
            int num = Integer.parseInt(nam1);
            Page page = new Page(pageSize, num, rowCount);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("startRow", page.getStartRow());
            map.put("pageSize", pageSize);
            map.put("code", code);
            List<LinkedHashMap<String, String>> list = employeeManager.selectAllEmployee(map);
            request.setAttribute("list", list);
            request.setAttribute("page", page);
            request.setAttribute("code", code);
            return "/pcManager/jsp/Employee/listUser.jsp";
        } else if ("3".equals(requestType)) {// ?id
            String code = request.getParameter("id") == null ? "" : request.getParameter("id");
            int num1 = employeeManager.deleteEmployeeByCode(code);
            if (num1 > 0) {
                System.out.println(num1);
                request.setAttribute("ok", "?!!!");
            }
            return "manage/forJsp.do?pageSize1=4&num1=1&requestType=2";
        } else if ("4".equals(requestType)) {//?
            String id = request.getParameter("id") == null ? "" : request.getParameter("id");
            String name = request.getParameter("name1") == null ? "" : request.getParameter("name1");
            String weixinCode = request.getParameter("weixinCode") == null ? ""
                    : request.getParameter("weixinCode");
            String mobile = request.getParameter("mobile") == null ? "" : request.getParameter("mobile");
            String loginName = request.getParameter("loginName") == null ? ""
                    : request.getParameter("loginName");
            String positionCode = request.getParameter("positionCode") == null ? ""
                    : request.getParameter("positionCode");
            String departmentCode = request.getParameter("departmentCode") == null ? ""
                    : request.getParameter("departmentCode");
            String password = request.getParameter("password") == null ? "" : request.getParameter("password");
            String roleCode = request.getParameter("roleCode") == null ? "" : request.getParameter("roleCode");
            int id1 = Integer.parseInt(id);
            if (id1 != 0) {
                String modifiedCode = (String) request.getSession().getAttribute("code");
                Employee e = employeeManager.findEmployeeById(id1);
                String employeeCodeString = e.getCode();
                List<EmployeeRole> list = employeeManager.findRoleByCode(employeeCodeString);
                if (list.size() != 0) {
                    for (int i = 0; i < list.size(); i++) {
                        String RoleCode1 = list.get(i).getRoleCode();
                        if (!RoleCode1.equals(roleCode)) {
                            employeeManager.updateEmployeeRole(e.getCode(), roleCode);
                            int num = employeeManager.updateIcbEmployeeById(name, departmentCode, positionCode,
                                    loginName, password, id1, mobile, weixinCode, modifiedCode);
                            if (num != 0) {
                                request.setAttribute("ok", "?");
                            }
                        } else {
                            int num = employeeManager.updateIcbEmployeeById(name, departmentCode, positionCode,
                                    loginName, password, id1, mobile, weixinCode, modifiedCode);
                            if (num != 0) {
                                request.setAttribute("ok", "?");
                            }
                        }
                    }
                } else {
                    employeeManager.saveEmployeeRole(e.getCode(), roleCode);
                    int num = employeeManager.updateIcbEmployeeById(name, departmentCode, positionCode,
                            loginName, password, id1, mobile, weixinCode, modifiedCode);
                    if (num != 0) {
                        request.setAttribute("ok", "?");
                    }
                }
            } else {
                String code = systemParamManager.employeeCode();
                employeeManager.saveEmployee(name, mobile, loginName, password, positionCode, departmentCode,
                        code, emp.getCode(), weixinCode);
                employeeManager.saveEmployeeRole(code, roleCode);
                request.setAttribute("ok", "?");
            }
            return "manage/forJsp.do?requestType=2&num1=1";
        } else if ("5".equals(requestType)) {//?
            String nam1 = request.getParameter("num1") == null ? "" : request.getParameter("num1");
            String name = request.getParameter("name1") == null ? "" : request.getParameter("name1");
            String mobile = request.getParameter("mobile1") == null ? "" : request.getParameter("mobile1");
            List<Map<String, String>> list1 = new ArrayList<Map<String, String>>();
            if (name == "" && mobile == "") {
                int rowCount = customerManager.countCustomer();
                int num = Integer.parseInt(nam1);
                Page page = new Page(pageSize, num, rowCount);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("startRow", page.getStartRow());
                map.put("pageSize", pageSize);
                list1 = customerManager.selectAllCustomer(map);
                request.setAttribute("list1", list1);
                request.setAttribute("page", page);
                return "/pcManager/jsp/customer/listCustomer.jsp";
            } else {
                Map<String, Object> map1 = new HashMap<String, Object>();
                map1.put("name", name);
                map1.put("mobile", mobile);
                int rowCount = customerManager.countByNameOrmobile(map1);
                int num = Integer.parseInt(nam1);
                Page page = new Page(pageSize, num, rowCount);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("name", name);
                map.put("mobile", mobile);
                map.put("startRow", page.getStartRow());
                map.put("pageSize", pageSize);
                list1 = customerManager.findByNameOrmobile(map);
                request.setAttribute("list1", list1);
                request.setAttribute("page", page);
                request.setAttribute("mobile", mobile);
                request.setAttribute("name", name);
                return "/pcManager/jsp/customer/listCustomer.jsp";
            }
        } else if ("6".equals(requestType)) {//? 2015/11/11 ?
            return "/pcManager/jsp/car/listCar.jsp";
        } else if ("7".equals(requestType)) {//??? 2015/11/11 ?
            String typeCode = "";
            String nam1 = request.getParameter("num1") == null ? "" : request.getParameter("num1");
            typeCode = request.getParameter("code") == null ? "" : request.getParameter("code");
            List<AccessoriesType> typeList = accessoriesTypeManager.selectAll();
            int num = Integer.parseInt(nam1);
            if (typeCode == "") {
                Map<String, Object> map = new HashMap<String, Object>();
                int rowCount = accessoriesInfoManager.countAccessoriesStorage();
                Page page = new Page(pageSize, num, rowCount);
                map.put("startRow", page.getStartRow());
                map.put("pageSize", pageSize);
                List<AccessoriesStorage> list = accessoriesInfoManager.searchAccessoriesStorage(map);
                request.setAttribute("list", list);
                request.setAttribute("page", page);
                request.setAttribute("typeCode", typeCode);
                request.setAttribute("typeList", typeList);
                return "/pcManager/jsp/accessories/listAccessories.jsp";
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                int rowCount = accessoriesInfoManager.countByTypeCode(typeCode);
                Page page = new Page(pageSize, num, rowCount);
                map.put("startRow", page.getStartRow());
                map.put("pageSize", pageSize);
                map.put("typeCode", typeCode);
                List<AccessoriesStorage> list = accessoriesInfoManager.searchByTypeCode(map);
                request.setAttribute("list", list);
                request.setAttribute("typeList", typeList);
                request.setAttribute("page", page);
                request.setAttribute("typeCode", typeCode);
                return "/pcManager/jsp/accessories/listAccessories.jsp";
            }
        } else if ("8".equals(requestType)) {//? 2015/11/11 ?
            List<FalseAccount> list = falseAccountManager.selectAllFalseAccount();
            request.setAttribute("list", list);
            return "/pcManager/jsp/customer/addAccount.jsp";
        } else if ("9".equals(requestType)) {//? 2015/11/11 ?
            List<Role> list = employeeManager.findAllRole();
            request.setAttribute("list", list);
            return "/pcManager/jsp/Role/listRole.jsp";
        } else if ("10".equals(requestType)) {// 2015/11/12 ?
            String nam1 = request.getParameter("num1") == null ? "" : request.getParameter("num1");
            String name = request.getParameter("name1") == null ? "" : request.getParameter("name1");
            String licensePlate = request.getParameter("licensePlate1") == null ? ""
                    : request.getParameter("licensePlate1");
            if (name == "" && licensePlate == "") {
                int num = Integer.parseInt(nam1);
                int rowCount = customerManager.countCustomerCar();
                Page page = new Page(pageSize, num, rowCount);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("startRow", page.getStartRow());
                map.put("pageSize", pageSize);
                List<Map<String, Object>> list = customerManager.selectCustomerCar(map);
                request.setAttribute("list", list);
                request.setAttribute("page", page);
                return "/pcManager/jsp/customer/customerCar.jsp";
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("name", name);
                map.put("licensePlate", licensePlate);
                int rowCount = customerManager.countByNameOrlicensePlate(map);
                int num = Integer.parseInt(nam1);
                System.out.println(rowCount);
                Page page = new Page(pageSize, num, rowCount);
                Map<String, Object> map1 = new HashMap<String, Object>();
                map1.put("name", name);
                map1.put("licensePlate", licensePlate);
                map1.put("startRow", page.getStartRow());
                map1.put("pageSize", pageSize);
                List<Map<String, Object>> list = customerManager.selectByNameOrlicensePlate(map1);
                request.setAttribute("list", list);
                request.setAttribute("page", page);
                request.setAttribute("name", name);
                request.setAttribute("licensePlate", licensePlate);
                return "/pcManager/jsp/customer/customerCar.jsp";
            }
        }
    } catch (Exception e) {
        outPutErrorInfor(ManageController.class.getName(), "forJsp", e);
        e.printStackTrace();
    }
    return null;
}

From source file:org.getobjects.servlets.WOServletAdaptor.java

protected void woService(final HttpServletRequest _rq, final HttpServletResponse _r) {
    log.debug("woService ...");

    if (this.WOApp == null) {
        log.error("Cannot run service, missing application object!");
        return;// www.j av a2 s  . co  m
    }

    try {
        /* Changed in Jetty 6.1.12/6.1.14 (JETTY-633). Default encoding is now
         * Latin-1, which breaks Safari/Firefox, which submit forms in UTF-8.
         * (I think if the page was delivered in UTF-8)
         * (w/o tagging the charset in the content-type?!) 
         */
        if (_rq.getCharacterEncoding() == null)
            _rq.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e) {
        log.error("UTF-8 is unsupported encoding?!", e);
        e.printStackTrace();
    }

    final WORequest rq = new WOServletRequest(_rq, _r);
    final WOResponse r;

    try {
        log.debug("  dispatch ...");
        r = this.WOApp.dispatchRequest(rq);

        if (r != null) {
            log.debug("  flush ...");
            r.flush();

            if (!r.isStreaming())
                this.sendWOResponseToServletResponse(r, _r);
        } else
            log.debug("  got no response.");
    } catch (Exception e) {
        log.debug("dispatch exception", e);
        e.printStackTrace();
    }

    if (rq != null)
        rq.dispose(); /* this will delete temporary files, eg of file uploads */

    log.debug("done woService.");
}

From source file:cdr.forms.FormController.java

@RequestMapping(value = "/supplemental", method = { RequestMethod.POST, RequestMethod.GET })
public String collectSupplementalObjects(@Valid @ModelAttribute("deposit") Deposit deposit,
        BindingResult errors, SessionStatus sessionStatus,
        @RequestParam(value = "added", required = false) DepositFile[] addedDepositFiles,
        @RequestParam(value = "deposit", required = false) String submitDepositAction,
        HttpServletRequest request, HttpServletResponse response) {

    request.setAttribute("formattedMaxUploadSize", (getMaxUploadSize() / 1000000) + "MB");
    request.setAttribute("maxUploadSize", getMaxUploadSize());

    // Validate request and ensure character encoding is set

    this.getAuthorizationHandler().checkPermission(deposit.getFormId(), deposit.getForm(), request);

    try {//  w  w w. j a v  a2s  .c  o m
        request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e) {
        LOG.error("Failed to set character encoding", e);
    }

    // Update supplemental objects

    Iterator<SupplementalObject> iterator = deposit.getSupplementalObjects().iterator();

    while (iterator.hasNext()) {
        SupplementalObject file = iterator.next();
        if (file == null)
            iterator.remove();
    }

    if (addedDepositFiles != null) {
        for (DepositFile depositFile : addedDepositFiles) {
            if (depositFile != null) {

                depositFile.setExternal(true);

                SupplementalObject object = new SupplementalObject();
                object.setDepositFile(depositFile);

                deposit.getSupplementalObjects().add(object);

            }
        }
    }

    Collections.sort(deposit.getSupplementalObjects(), new Comparator<SupplementalObject>() {
        public int compare(SupplementalObject sf1, SupplementalObject sf2) {
            return sf1.getDepositFile().getFilename().compareTo(sf2.getDepositFile().getFilename());
        }
    });

    // Check the deposit's files for virus signatures

    IdentityHashMap<DepositFile, String> signatures = new IdentityHashMap<DepositFile, String>();

    for (DepositFile depositFile : deposit.getAllFiles())
        scanDepositFile(depositFile, signatures);

    // Validate supplemental objects

    if (submitDepositAction != null) {

        Validator validator = new SupplementalObjectValidator();

        int i = 0;

        for (SupplementalObject object : deposit.getSupplementalObjects()) {
            errors.pushNestedPath("supplementalObjects[" + i + "]");
            validator.validate(object, errors);
            errors.popNestedPath();

            i++;
        }

    }

    // Handle viruses, validation errors, and the deposit not having been finally submitted

    request.setAttribute("formId", deposit.getFormId());
    request.setAttribute("administratorEmail", getAdministratorEmail());

    if (signatures.size() > 0) {
        request.setAttribute("signatures", signatures);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

        deposit.deleteAllFiles(true);
        sessionStatus.setComplete();

        return "virus";
    }

    if (errors.hasErrors()) {
        return "supplemental";
    }

    if (submitDepositAction == null) {
        return "supplemental";
    }

    // Try to deposit

    DepositResult result = this.getDepositHandler().deposit(deposit);

    if (result.getStatus() == Status.FAILED) {

        LOG.error("deposit failed");

        if (getNotificationHandler() != null) {
            getNotificationHandler().notifyError(deposit, result);
        }

        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        deposit.deleteAllFiles(true);
        sessionStatus.setComplete();

        return "failed";

    } else {

        if (getNotificationHandler() != null) {
            getNotificationHandler().notifyDeposit(deposit, result);
        }

        deposit.deleteAllFiles(false);
        sessionStatus.setComplete();

        return "success";

    }

}