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.icb123.Controller.ManageController.java

@RequestMapping(value = "/forAjax")
public void forAjax(HttpServletRequest request, HttpServletResponse response) {
    try {// w  w w  .ja  v a  2 s  . co  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");
        Employee employee = (Employee) request.getSession().getAttribute("Employee");
        if ("car1".equals(requestType)) {//??
            String parentCode = request.getParameter("carCode") == null ? "" : request.getParameter("carCode");
            List<CarInfo> list = carInfoManager.findListByParentCode(parentCode);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("time1".equals(requestType)) {//?
            List<ServiceTime> list = serviceManager.findAllServiceTime();
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("service1".equals(requestType)) {//??
            String parentCode = request.getParameter("code") == null ? "" : request.getParameter("code");
            List<Service> list = serviceManager.findServiceByParentCode(parentCode);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("access1".equals(requestType)) {//????
            String serviceCode = request.getParameter("serviceCode") == null ? ""
                    : request.getParameter("serviceCode");
            String carCode = request.getParameter("carCode") == null ? "" : request.getParameter("carCode");
            List<AccessoriesInfo> list = accessoriesInfoManager.findServiceMatchAccessories(serviceCode,
                    carCode);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("access2".equals(requestType)) {//????
            String type = request.getParameter("type") == null ? "" : request.getParameter("type");
            List<AccessoriesInfo> list = accessoriesInfoManager.findAccessoriesByType(type);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("wxMenu".equals(requestType)) {//???
            String accessToken = WeixinUntil.getAccessToken();
            int flag = wmenuManager.creatMenu(accessToken);
            Map<String, String> map = new HashMap<String, String>();
            map.put("flag", flag + "");
            OutputUtil.outPutJsonObject(response, map);
        } else if ("100".equals(requestType)) {//?
            String loginName = request.getParameter("loginName") == null ? ""
                    : request.getParameter("loginName");
            String password = request.getParameter("password") == null ? "" : request.getParameter("password");
            String nickname = request.getParameter("nickname") == null ? "" : request.getParameter("nickname");
            int flag = employeeManager.saveWeixinKefu(loginName, password, nickname, employee.getCode());
            Map<String, String> map = new HashMap<String, String>();
            map.put("flag", flag + "");
            OutputUtil.outPutJsonObject(response, map);
        } else if ("1".equals(requestType)) {//???
            String psw1 = request.getParameter("psw") == null ? "" : request.getParameter("psw");
            String id1 = request.getParameter("id") == null ? "" : request.getParameter("id");
            int i = Integer.valueOf(id1).intValue();
            Employee icbEmployee = new Employee();
            Map<String, String> result = new HashMap<String, String>();
            icbEmployee.setId(i);
            icbEmployee.setPassword(psw1);
            int num = employeeManager.findPsw(icbEmployee);
            if (num == 1) {
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            } else {
                result.put("msg", "0");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("2".equals(requestType)) {//?id?
            String psw1 = request.getParameter("psw") == null ? "" : request.getParameter("psw");
            String id1 = request.getParameter("id") == null ? "" : request.getParameter("id");
            int id = Integer.valueOf(id1).intValue();
            int num = employeeManager.updatePwd(id, psw1);
            Map<String, String> result = new HashMap<String, String>();
            if (num != 0) {
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            } else {
                result.put("msg", "0");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("3".equals(requestType)) {//session?
            String num = "";
            if (null != request.getSession()) {
                Employee user = (Employee) request.getSession().getAttribute("Employee");
                if (null != user && !"".equals(user)) {
                    num = "1";
                    response.getWriter().write(num);
                } else {
                    num = "2";
                    response.getWriter().write(num);
                }
            }
        } else if ("4".equals(requestType)) {//?id??
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            Map<String, Object> map = employeeManager.findEmployee(code);
            OutputUtil.outPutJsonObject(response, map);
        } else if ("5".equals(requestType)) {//???            
            String nam = request.getParameter("name") == null ? "" : request.getParameter("name");
            int num = employeeManager.findEmployeeName(nam);
            Map<String, String> result = new HashMap<String, String>();
            if (num >= 1) {
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            } else {
                result.put("msg", "0");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("6".equals(requestType)) {//???
            String logN = request.getParameter("loginName") == null ? "" : request.getParameter("loginName");
            int num = employeeManager.findEmployeeloName(logN);
            Map<String, String> result = new HashMap<String, String>();
            if (num >= 1) {
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            } else {
                result.put("msg", "0");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("9".equals(requestType)) {//
            List<Role> listRole = employeeManager.findAllRole();
            OutputUtil.outPutJsonArrary(response, listRole);
        } else if ("10".equals(requestType)) {//??
            List<Position> listposition = employeeManager.findPosition();
            OutputUtil.outPutJsonArrary(response, listposition);
        } else if ("11".equals(requestType)) {//
            List<Department> listDepartment = employeeManager.findDepartment();
            OutputUtil.outPutJsonArrary(response, listDepartment);
        } else if ("12".equals(requestType)) {//?Code
            String nickName = request.getParameter("nickName") == null ? "" : request.getParameter("nickName");
            WeixinCustomer weixinCustomer = weixinCustomerManager.findByName(nickName);
            Map<String, String> result = new HashMap<String, String>();
            if (weixinCustomer == null) {
                result.put("msg", "0");
                OutputUtil.outPutJsonObject(response, result);

            } else {
                String weixinCode = weixinCustomer.getCode();
                String code = (String) request.getSession().getAttribute("code");
                int num = employeeManager.saveEmployeeweixinCode(code, weixinCode);
                if (num == 1) {
                    result.put("msg", "1");
                    OutputUtil.outPutJsonObject(response, result);
                }
            }
        } else if ("13".equals(requestType)) {
            String code = request.getParameter("weixinCode") == null ? "" : request.getParameter("weixinCode");
            WeixinCustomer weixinCustomer = weixinCustomerManager.findByCode(code);
            Map<String, String> result = new HashMap<String, String>();
            if (weixinCustomer == null) {
                result.put("msg", "0");
                OutputUtil.outPutJsonObject(response, result);
            } else {
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("14".equals(requestType)) {//
            String name = request.getParameter("name") == null ? "" : request.getParameter("name");
            String orderCol = request.getParameter("orderCol") == null ? "" : request.getParameter("orderCol");
            String parentCode = request.getParameter("parentCode") == null ? ""
                    : request.getParameter("parentCode");
            Map<String, String> result = new HashMap<String, String>();
            String maxCode = carInfoManager.findMaxCode(parentCode);
            String code;
            if (maxCode == null || maxCode.trim().length() == 0) {
                maxCode = "";
                code = carInfoManager.saveCar(name, parentCode, orderCol, maxCode);
            } else {
                code = carInfoManager.saveCar(name, parentCode, orderCol, maxCode);
            }
            if (StringUtils.isNotBlank(code)) {
                result.put("msg", "1");
                result.put("code", code);
                OutputUtil.outPutJsonObject(response, result);
            } else {
                result.put("msg", "0");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("15".equals(requestType)) {//?
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            CarInfo listCarInfo = carInfoManager.findByCode(code);
            if (listCarInfo != null) {
                OutputUtil.outPutJsonObject(response, listCarInfo);
            }
        } else if ("16".equals(requestType)) {//
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            String name = request.getParameter("name") == null ? "" : request.getParameter("name");
            String orderCol = request.getParameter("orderCol") == null ? "" : request.getParameter("orderCol");
            int number = carInfoManager.updateByCode(name, code, orderCol);
            Map<String, String> result = new HashMap<String, String>();
            if (number == 1) {
                result.put("msg", "1");
                result.put("code", code);
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("17".equals(requestType)) {//????
            String name = request.getParameter("name") == null ? "" : request.getParameter("name");
            String parentCode = request.getParameter("parentCode") == null ? ""
                    : request.getParameter("parentCode");
            Map<String, String> result = new HashMap<String, String>();
            int number = carInfoManager.findName(name, parentCode);
            if (number >= 1) {
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("18".equals(requestType)) {//
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            Map<String, String> result = new HashMap<String, String>();
            int num = carInfoManager.deleteByCode(code);
            if (num == 1) {
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("19".equals(requestType)) {//Car
            String parentCode = request.getParameter("parentCode") == null ? ""
                    : request.getParameter("parentCode");
            List<CarInfo> list = carInfoManager.findListByParentCode(parentCode);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("20".equals(requestType)) {//? 2015/11/11 ?
            String parentCode = request.getParameter("parentCode") == null ? ""
                    : request.getParameter("parentCode");
            List<CarInfo> list = carInfoManager.findListByParentCode(parentCode);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("21".equals(requestType)) {
            String accCode = request.getParameter("name") == null ? "" : request.getParameter("name");
            String num = request.getParameter("num") == null ? "" : request.getParameter("num");
            String ioType = request.getParameter("ioType") == null ? "" : request.getParameter("ioType");
            String carCode = request.getParameter("carCode") == null ? "" : request.getParameter("carCode");
            String beizhu = request.getParameter("beizhu") == null ? "" : request.getParameter("beizhu");
            String price = request.getParameter("price") == null ? "" : request.getParameter("price");
            String empCode = request.getParameter("empCode") == null ? "" : request.getParameter("empCode");
            String moneyType = request.getParameter("moneyType") == null ? ""
                    : request.getParameter("moneyType");
            Map<String, String> result = accessoriesInfoManager.accInAndOutStorage(accCode, num, price, ioType,
                    beizhu, empCode, employee.getCode(), carCode, moneyType);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("22".equals(requestType)) {//??
            String creatCode = employee.getCode();
            String id = request.getParameter("id") == null ? "" : request.getParameter("id");
            String newBrand = request.getParameter("newBrand") == null ? "" : request.getParameter("newBrand");
            String newManufacturer = request.getParameter("newManufacturer") == null ? ""
                    : request.getParameter("newManufacturer");
            String typeCode = request.getParameter("typeCode") == null ? "" : request.getParameter("typeCode");
            String unit = request.getParameter("unit") == null ? "" : request.getParameter("unit");
            String newModel = request.getParameter("newModel") == null ? "" : request.getParameter("newModel");
            Map<String, String> result = accessoriesInfoManager.saveOrUpdateAccessoriesStorage(id, newBrand,
                    newManufacturer, typeCode, unit, newModel, creatCode);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("23".equals(requestType)) {//?id?? 2015/11/11 ?
            String id1 = request.getParameter("id") == null ? "" : request.getParameter("id");
            int id = Integer.valueOf(id1).intValue();
            AccessoriesStorage accessoriesStorage = accessoriesInfoManager.findAccessoriesStorageById(id);
            if (accessoriesStorage != null) {
                OutputUtil.outPutJsonObject(response, accessoriesStorage);
            }
        } else if ("24".equals(requestType)) {//?? 2015/11/11 ?
            String name = request.getParameter("name") == null ? "" : request.getParameter("name");
            String address = request.getParameter("address") == null ? "" : request.getParameter("address");
            String phone = request.getParameter("phone") == null ? "" : request.getParameter("phone");
            String models = request.getParameter("models") == null ? "" : request.getParameter("models");
            falseAccountManager.saveAccount(name, address, models, phone);
            Map<String, String> result = new HashMap<String, String>();
            result.put("msg", "1");
            OutputUtil.outPutJsonObject(response, result);
        } else if ("25".equals(requestType)) {//? 2015/11/11 ?
            String id1 = request.getParameter("id") == null ? "" : request.getParameter("id");
            int id = Integer.valueOf(id1).intValue();
            Map<String, String> result = new HashMap<String, String>();
            int number = falseAccountManager.deleteById(id);
            if (number == 1) {
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("26".equals(requestType)) {//?? 2015/11/11 ?
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            List<Menu> list1 = menuManager.findMenu(code);
            OutputUtil.outPutJsonArrary(response, list1);
        } else if ("27".equals(requestType)) {//?
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            List<Map<String, String>> list = roleManager.findByCodeUpdate(code);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("28".equals(requestType)) {//?? 2015/11/11 ?
            List<Menu> list = menuManager.selectAllMenu();
            if (list.size() > 0) {
                OutputUtil.outPutJsonArrary(response, list);
            }
        } else if ("29".equals(requestType)) {//comment 2015/11/11 ?
            String comment = request.getParameter("comment") == null ? "" : request.getParameter("comment");
            String RoleName = request.getParameter("name") == null ? "" : request.getParameter("name");
            String chestr = request.getParameter("chestr") == null ? "" : request.getParameter("chestr");
            String roleCode = request.getParameter("code") == null ? "" : request.getParameter("code");
            int number = roleManager.updateNameByCode(RoleName, roleCode, comment, employee.getCode());
            int num = roleManager.deleteRoleByCode(roleCode);
            if (num > 0) {
                String[] cheStrings = chestr.split(",");
                for (int i = 0; i < cheStrings.length; i++) {
                    String menuCode = cheStrings[i];
                    roleManager.add(roleCode, menuCode);
                }
                if (number == 1) {
                    Map<String, String> result = new HashMap<String, String>();
                    result.put("msg", "1");
                    OutputUtil.outPutJsonObject(response, result);
                }
            }
        } else if ("30".equals(requestType)) {// 2015/11/11 ?
            String isValid = "0";
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            int number = roleManager.deleteRole(isValid, code);
            if (number > 0) {
                Map<String, String> result = new HashMap<String, String>();
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("31".equals(requestType)) {// 2015/11/11 ?
            String isValid = "1";
            String comment = request.getParameter("comment") == null ? "" : request.getParameter("comment");
            String chestr = request.getParameter("chestr") == null ? "" : request.getParameter("chestr");
            String name = request.getParameter("name") == null ? "" : request.getParameter("name");
            String MaxCode = roleManager.findMaxCode();
            int IntCode = Integer.valueOf(MaxCode).intValue();
            int number = IntCode + 1;
            String code = "0" + String.valueOf(number);
            int num = roleManager.addOneRole(name, comment, isValid, code, employee.getCode());
            if (num == 1) {
                String[] cheStrings = chestr.split(",");
                for (int i = 0; i < cheStrings.length; i++) {
                    String menuCode = cheStrings[i];
                    roleManager.add(code, menuCode);
                }
                Map<String, String> result = new HashMap<String, String>();
                result.put("msg", "1");
                OutputUtil.outPutJsonObject(response, result);
            }
        } else if ("32".equals(requestType)) {//?code ?? 2015/11/11 ?
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            List<Map<String, Object>> list = customerManager.findCustomerAllService(code);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("33".equals(requestType)) {//
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            CustomerCar customerCar = customerManager.findCustomerCar(code);
            Map<Object, Object> map = new HashMap<Object, Object>();
            Date time = customerCar.getInsuranceTime();
            String insuranceTime = "";
            if (time != null) {
                insuranceTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(time);
            }
            Date time1 = customerCar.getCarefulTime();
            String carefulTime = "";
            if (time1 != null) {
                carefulTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(time1);
            }
            map.put("insuranceTime", insuranceTime);
            map.put("carefulTime", carefulTime);
            map.put("virCode", customerCar.getVirCode());
            map.put("engineCode", customerCar.getEngineCode());
            map.put("mileage", customerCar.getMileage());
            if (map != null) {
                OutputUtil.outPutJsonObject(response, map);
            }
        } else if ("34".equals(requestType)) {//?
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            List<AccessoriesStorage> list = accessoriesInfoManager.findAccessoriesStorageByTypeCode(code);
            if (list != null) {
                OutputUtil.outPutJsonArrary(response, list);
            }
        } else if ("35".equals(requestType)) {//??
            List<Employee> list = employeeManager.findAllEmployee();
            if (list != null) {
                OutputUtil.outPutJsonArrary(response, list);
            }
        } else if ("36".equals(requestType)) {//? 2015.11.25 ?
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            List<Map<String, String>> list = accessoriesInfoManager.findOutAccessoriesStorageRecord(code);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("37".equals(requestType)) {//? 2015.11.25 ?
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            List<Map<String, String>> list = accessoriesInfoManager.findInAccessoriesStorageRecord(code);
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("39".equals(requestType)) {
            List<AccessoriesStorage> list = accessoriesInfoManager.findAllAccessoriesStorage();
            if (list != null && list.size() != 0) {
                OutputUtil.outPutJsonArrary(response, list);
            }
        } else if ("40".equals(requestType)) {//?
            String code = request.getParameter("name") == null ? "" : request.getParameter("name");
            String num = request.getParameter("num") == null ? "" : request.getParameter("num");
            Map<String, Object> result = accessoriesInfoManager.outNumberChecked(code, num);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("41".equals(requestType)) {//? ? 2015.11.28
            String code = request.getParameter("code") == null ? "" : request.getParameter("code");
            int number = weixinCustomerManager.setVip(code);
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("msg", number);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("42".equals(requestType)) {//???
            List<AccessoriesType> list = accessoriesTypeManager.selectAll();
            Iterator<AccessoriesType> iterator = list.iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }
            if (list.size() != 0) {
                OutputUtil.outPutJsonArrary(response, list);
            }
        } else if ("43".equals(requestType)) {
            String typeName = request.getParameter("typeName") == null ? "" : request.getParameter("typeName");
            String maxCode = accessoriesTypeManager.findMaxCode();
            System.out.println(maxCode + "aaa");
            if (maxCode != "") {
                int num = Integer.valueOf(maxCode).intValue();
                int num1 = num + 1;
                System.out.println(num1);
                String code = String.valueOf(num1);
                int number = accessoriesTypeManager.addAccessoriesType(code, typeName);
                if (number == 1) {
                    Map<String, Object> result = new HashMap<String, Object>();
                    result.put("msg", number);
                    result.put("typeName", typeName);
                    result.put("maxCode", code);
                    OutputUtil.outPutJsonObject(response, result);
                }
            }
        } else if ("44".equals(requestType)) {//??
            String typeName = request.getParameter("typeName") == null ? "" : request.getParameter("typeName");
            int num2 = accessoriesTypeManager.textName(typeName);
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("msg", num2);
            OutputUtil.outPutJsonObject(response, result);
        } else if ("45".equals(requestType)) {//
            String parentCode = request.getParameter("parentCode") == null ? ""
                    : request.getParameter("parentCode");
            List<CarInfo> list = carInfoManager.findNewCar(parentCode);
            System.out.println(list.size());
            OutputUtil.outPutJsonArrary(response, list);
        } else if ("46".equals(requestType)) {//
            String parentCode = request.getParameter("parentCode") == null ? ""
                    : request.getParameter("parentCode");
            List<CarInfo> list = carInfoManager.findUpdateCar(parentCode);
            OutputUtil.outPutJsonArrary(response, list);
        }

    } catch (UnsupportedEncodingException e) {
        outPutErrorInfor(ManageController.class.getName(), "?", e);
    } catch (IOException e) {
        outPutErrorInfor(ManageController.class.getName(), "?", e);
    }
}

From source file:com.jkkp.modules.supplier.controller.SupplierController.java

@RequestMapping(value = "/updateOne.do", method = RequestMethod.POST)
public String updateOneSupplier(HttpServletRequest req, Integer regionId, String spName, String contactUser,
        String contactMobile, String legalPerson, Float gainRate, String address, Integer type, Integer levelId,
        Integer spId, String bindMobile, Integer levelMoney) {
    try {/*w w  w  .  j a  va2 s  .  co  m*/
        req.setCharacterEncoding("utf-8");
        String abbreviation = req.getParameter("abbreviation");
        System.out.println("updateOne abbreviation=" + abbreviation);
        Supplier supplier = new Supplier();
        supplier.setAbbreviation(abbreviation);
        supplier.setId(spId);
        //supplier.setCityDomain(cityDomain);
        supplier.setSpName(spName);
        supplier.setContactUser(contactUser);
        supplier.setLegalPerson(legalPerson);
        supplier.setContactMobile(contactMobile);
        supplier.setGainRate(gainRate / 100);
        //         supplier.setStartDate(startDate);
        //         supplier.setEndDate(endDate);
        supplier.setAddress(address);
        supplier.setType(type);
        supplier.setBindMobile(bindMobile);
        supplier.setLevelId(levelId);
        supplier.setRegionId(regionId);
        if (levelId != null && levelId == 0) {
            List<SupplierLevel> levelMoneyList = supplierLevelService.selectByProperty("levelMoney",
                    levelMoney);
            if (levelMoneyList.size() > 0) {
                supplier.setLevelId(levelMoneyList.get(0).getId());
            } else {
                SupplierLevel supplierLevel = supplierLevelService.saveOne(levelMoney);
                supplier.setLevelId(supplierLevel.getId());
            }
        }
        supplierService.saveOrUpdate(supplier);
        String params = RequestParamUtils.joinRedirectParams(req, new String[] { "mid", "pid" });
        return "redirect:index.xhtml" + params;
    } catch (Exception e) {
        logger.error("?", e);
        return "404";
    }
}

From source file:org.apache.struts2.dispatcher.Dispatcher.java

private void applyEncoding(HttpServletRequest request, String encoding) {
    try {//from w w  w  .  j a  v  a2  s  .co  m
        if (!encoding.equals(request.getCharacterEncoding())) {
            // if the encoding is already correctly set and the parameters have been already read
            // do not try to set encoding because it is useless and will cause an error
            request.setCharacterEncoding(encoding);
        }
    } catch (Exception e) {
        LOG.error("Error setting character encoding to '{}' - ignoring.", encoding, e);
    }
}

From source file:controllers.controller.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww w. ja  va2  s. c om
 *
 * @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, Exception {

    request.setCharacterEncoding(PageParameters.getParameter("charset").toString());
    response.setCharacterEncoding(PageParameters.getParameter("charset").toString());
    response.setContentType(PageParameters.getParameter("servletSetContentType").toString());
    response.setHeader("Cache-Control", "no-cache");
    HttpSession session;
    PrintWriter out;
    QUID quid;
    LinkedList<String> userAccess;
    quid = new QUID();
    quid.setRequest(request);
    session = request.getSession(true);
    SessionUtil.addIfNotExistSession(session);
    out = response.getWriter();
    try {
        try {
            if (PageParameters.getParameter("SiteOnMaintenance").equals("true")) {
                response.sendRedirect(PageParameters.getParameter("SiteOnMaintenanceURL").toString());
            } else // <editor-fold defaultstate="collapsed" desc="Realizando LogIn de usuario">
            //si proviene de la pgina  de login aqui se detectara y se validara al usuario
            {
                if (request.getParameter("LogInPage") != null) {
                    //aqui consulta el usuario en Base de Datos.
                    //                        if (request.getParameter("captcha").equals(session.getAttribute("captcha")) && request.getParameter("captcha").equalsIgnoreCase("") == false) {
                    if (true) {
                        if (request.getParameter("user").equalsIgnoreCase("") == false
                                && request.getParameter("pass").equalsIgnoreCase("") == false) {

                            LinkedList infoUser = null;
                            LinkedList<String> accessos = null;

                            infoUser = quid.selectIdUsuario(request.getParameter("user"),
                                    request.getParameter("pass"), "ACTIVO");

                            if (infoUser != null) {
                                session.removeAttribute("captcha");
                                SessionUtil.clearNCloseSession(session);
                                session = request.getSession(true);
                                session.setAttribute("tipoRol", infoUser.get(3));
                                session.setAttribute("userID", infoUser.get(0));
                                session.setAttribute("userName", infoUser.get(1));
                                session.setAttribute("FK_ID_Plantel", infoUser.get(2));
                                //asignacion de permisos
                                //LinkedList<String> accessos = new LinkedList();
                                accessos = quid.selectPermisosUsuarios(infoUser.get(0).toString());
                                session.setMaxInactiveInterval(3 * 60 * 60); // 2hrs * 60 min * 60 seg

                                //accesos del usaurio y parametros del mismo
                                session.setAttribute("userAccess", accessos);
                                SessionUtil.addIfNotExistSession(session);
                                request.getRequestDispatcher(PageParameters.getParameter("mainMenuServLet"))
                                        .forward(request, response);
                            } else {
                                this.getServletConfig().getServletContext().getRequestDispatcher(""
                                        + PageParameters.getParameter("msgUtil")
                                        + "/msgNRedirectFull.jsp?title=Error&type=error&msg=Usuario o password incorrectos.&url=/"
                                        + PageParameters.getParameter("appName")
                                        + PageParameters.getParameter("LogInPage")).forward(request, response);
                            }
                        } else {
                            this.getServletConfig().getServletContext().getRequestDispatcher(""
                                    + PageParameters.getParameter("msgUtil")
                                    + "/msgNRedirectFull.jsp?title=Error&type=error&msg=El usuario y password no pueden estar vacos.&url=/"
                                    + PageParameters.getParameter("appName")
                                    + PageParameters.getParameter("LogInPage")).forward(request, response);
                        }
                    } else {
                        this.getServletConfig().getServletContext().getRequestDispatcher(""
                                + PageParameters.getParameter("msgUtil")
                                + "/msgNRedirectFull.jsp?title=Error&type=error&msg=Cdigo de verificacin incorrecto.&url=/"
                                + PageParameters.getParameter("appName")
                                + PageParameters.getParameter("LogInPage")).forward(request, response);
                    }
                    // </editor-fold> 
                    // <editor-fold defaultstate="expanded" desc="Validando que sea un usuario logeado">
                } else if (session.getAttribute("userAccess") == null) {
                    response.sendRedirect("/" + PageParameters.getParameter("appName")
                            + PageParameters.getParameter("LogInPage"));
                    // </editor-fold> 
                } else // <editor-fold defaultstate="collapsed" desc="Cerrando sesion">
                {
                    if (request.getParameter("exit") != null) {
                        //session.invalidate();
                        this.clearNCloseSession(session, request, response, quid, out);
                        //quid.insertLog("SysLogOut", "exit", "", "", "", "");
                        response.sendRedirect(PageParameters.getParameter("mainContext")
                                + PageParameters.getParameter("LogInPage").toString());
                        // </editor-fold>
                        // <editor-fold defaultstate="collapsed" desc="Revisando de que form viene">
                    } else if (request.getParameter("FormForm") != null) {
                        switch (request.getParameter("FormForm")) {
                        case "agregaFichaTecnica":
                            this.agregaFichaTecnica(session, request, response, quid, out);
                            break;
                        case "modificaFichaTecnica":
                            this.modificaFichaTecnica(session, request, response, quid, out);
                            break;
                        case "agregaEtapaDesarrollo":
                            this.agregaEtapaDesarrollo(session, request, response, quid, out);
                            break;
                        case "modificaEtapaDesarrollo":
                            this.modificaEtapaDesarrollo(session, request, response, quid, out);
                            break;
                        case "eliminaStage":
                            this.eliminaEtapa(session, request, response, quid, out);
                            break;
                        case "agregaActivity":
                            this.agregaActividad(session, request, response, quid, out);
                            break;
                        case "modificaActivity":
                            this.modificaActividad(session, request, response, quid, out);
                            break;
                        case "eliminaActivity":
                            this.eliminaActividad(session, request, response, quid, out);
                            break;
                        case "deleteObjetoArchivo":
                            this.deleteObjetoArchivo(session, request, response, quid, out);
                            break;
                        }
                        // </editor-fold>
                    } else if (ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) {
                        this.subirArchivo(session, request, response, quid, out);

                    } else {
                        out.println("UPS.... Algo malo ha pasado");
                    }
                }
            }

        } catch (Exception ex) {
            Logger.getLogger(controller.class.getName()).log(Level.SEVERE, null, ex);
        }
    } finally {
        quid = null;
        out.close();
    }
}

From source file:com.megaeyes.web.controller.VISController.java

@ControllerDescription(description = "?", isLog = false, isCheckSession = true)
@RequestMapping("/updateVisJson.json")
public void updateVIS(HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException {
    request.setCharacterEncoding("UTF-8");
    // System.out.println("In updateVIS ...");
    BaseResponse resp = new BaseResponse();
    resp.setCode(ErrorCode.SUCCESS);//from   w w w  . j av a  2 s . co  m
    // ??
    String id = (String) request.getAttribute("id");
    String name = (String) request.getAttribute("name");
    String deviceNumber = (String) request.getAttribute("deviceNumber");
    String installLocation = (String) request.getAttribute("location");
    String ip = (String) request.getAttribute("ip");
    String linkType = (String) request.getAttribute("linkType");
    String hc = (String) request.getAttribute("heartCycle");

    // String organId=(String) request.getAttribute("organId");
    Long heartCycle = null;
    if (StringUtils.isNotBlank(hc)) {
        try {
            heartCycle = Long.parseLong(hc);
        } catch (NumberFormatException e) {
            resp.setCode(ErrorCode.ERROR);
            resp.setMessage("heartCycle");
        }
    }
    String rebootTime = (String) request.getAttribute("rebootTime");
    String rc = (String) request.getAttribute("rebootCycle");
    Long rebootCycle = null;
    if (StringUtils.isNotBlank(rc)) {
        try {
            rebootCycle = Long.parseLong(rc);
        } catch (NumberFormatException e) {
            resp.setCode(ErrorCode.ERROR);
            resp.setMessage("rebootCycle");
        }
    }
    String mca = (String) request.getAttribute("maxConnectAmount");
    Long maxConnectAmount = null;
    if (StringUtils.isNotBlank(mca)) {
        try {
            maxConnectAmount = Long.parseLong(mca);
            System.out.println("maxConnectAmount:" + maxConnectAmount);
        } catch (NumberFormatException e) {
            resp.setCode(ErrorCode.ERROR);
            resp.setMessage("maxConnectAmount");
        }
    }
    String videoInputServerModelId = request.getParameter("videoInputServerModelId");
    String iss = (String) request.getAttribute("isSupportScheme");
    Short isSupportScheme = null;
    if (StringUtils.isNotBlank(iss)) {
        try {
            isSupportScheme = Short.parseShort(iss);
        } catch (NumberFormatException e) {
            resp.setCode(ErrorCode.ERROR);
            resp.setMessage("maxConnectAmount");
        }
    }
    String note = (String) request.getAttribute("note");
    String sipCode = (String) request.getAttribute("sipCode");
    String longitude = (String) request.getAttribute("longitude");
    String latitude = (String) request.getAttribute("latitude");
    if (resp.getCode().equals(ErrorCode.SUCCESS)) {
        try {
            vISManager.updateVIS(id, name, deviceNumber, installLocation, ip, linkType, heartCycle, rebootTime,
                    rebootCycle, maxConnectAmount, videoInputServerModelId, isSupportScheme, note, sipCode,
                    longitude, latitude);
            resp.setCode(ErrorCode.SUCCESS);
        } catch (BusinessException be) {
            resp.setCode(be.getCode());
            resp.setMessage(be.getMessage());
        }
        writePageNoZip(response, resp);
    }
}

From source file:dk.dma.msiproxy.web.MessageDetailsServlet.java

/**
 * Main GET method//from  www .ja v a2 s. c  o m
 * @param request servlet request
 * @param response servlet response
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // Never cache the response
    response = WebUtils.nocache(response);

    // Read the request parameters
    String providerId = request.getParameter("provider");
    String lang = request.getParameter("lang");
    String messageId = request.getParameter("messageId");
    String activeNow = request.getParameter("activeNow");
    String areaHeadingIds = request.getParameter("areaHeadings");

    List<AbstractProviderService> providerServices = providers.getProviders(providerId);

    if (providerServices.size() == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid 'provider' parameter");
        return;
    }

    // Ensure that the language is valid
    lang = providerServices.get(0).getLanguage(lang);

    // Force the encoding and the locale based on the lang parameter
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    final Locale locale = new Locale(lang);
    request = new HttpServletRequestWrapper(request) {
        @Override
        public Locale getLocale() {
            return locale;
        }
    };

    // Get the messages in the given language for the requested provider
    MessageFilter filter = new MessageFilter().lang(lang);
    Date now = "true".equals(activeNow) ? new Date() : null;
    Integer id = StringUtils.isNumeric(messageId) ? Integer.valueOf(messageId) : null;
    Set<Integer> areaHeadings = StringUtils.isNotBlank(areaHeadingIds) ? Arrays
            .asList(areaHeadingIds.split(",")).stream().map(Integer::valueOf).collect(Collectors.toSet())
            : null;

    List<Message> messages = providerServices.stream().flatMap(p -> p.getCachedMessages(filter).stream())
            // Filter on message id
            .filter(msg -> (id == null || id.equals(msg.getId())))
            // Filter on active messages
            .filter(msg -> (now == null || msg.getValidFrom() == null || msg.getValidFrom().before(now)))
            // Filter on area headings
            .filter(msg -> (areaHeadings == null || areaHeadings.contains(getAreaHeadingId(msg))))
            .collect(Collectors.toList());

    // Register the attributes to be used on the JSP apeg
    request.setAttribute("messages", messages);
    request.setAttribute("baseUri", app.getBaseUri());
    request.setAttribute("lang", lang);
    request.setAttribute("locale", locale);
    request.setAttribute("provider", providerId);

    if (request.getServletPath().endsWith("pdf")) {
        generatePdfFile(request, response);
    } else {
        generateHtmlPage(request, response);
    }
}

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

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

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

    //request.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF8");
    providerIDList = providerDAO.getProvidersIDList();

    //        String stt = request.getParameter("id_product");
    //        int st;
    //        if(stt ==null){
    //            return INPUT;
    //        }
    //        st = Integer.parseInt(stt);

    productsList = productDAO.getProductList();
    //product = productDAO.loadProduct(st);

    return SUCCESS;
}

From source file:com.megaeyes.web.controller.VISController.java

@ControllerDescription(description = "?id?", isLog = false, isCheckSession = true)
@RequestMapping("/list_vis_byorgan_Id.json")
public void ListVic(HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException {
    // System.out.println("In ListVicServlet ...");
    request.setCharacterEncoding("UTF-8");
    ListVisByOrganIdResponse resp = new ListVisByOrganIdResponse();
    String organId = (String) request.getAttribute("organId");
    String isqueryregstr = (String) request.getAttribute("isqueryreg");
    boolean isqueryreg = false;
    try {//  w w w .  j  av  a  2s .  c  o  m
        isqueryreg = Boolean.parseBoolean(isqueryregstr);
    } catch (Exception e) {
        resp.setCode(ErrorCode.PARAMETER_VALUE_INVALIDED);
        resp.setMessage("isqueryreg");
    }
    if (resp.getCode().equals(ErrorCode.SUCCESS)) {
        try {
            List<VideoInputChannel> list = vISManager.listVicByOrganId(organId, isqueryreg);
            resp.setList(list);
            resp.setCode(ErrorCode.SUCCESS);
        } catch (BusinessException be) {
            resp.setCode(be.getCode());
            resp.setMessage(be.getMessage());
        }
    }
    writePageNoZip(response, resp);
}

From source file:com.exilant.exility.core.HtmlRequestHandler.java

/**
 * process a request from client. This is the main method used by
 * Service.jsp//from w w w  . j a  v  a2  s  . co  m
 * 
 * @param req
 * @param resp
 * @param formIsSubmitted
 *            has the caller submitted the form?
 * @param hasSerializedDc
 *            is it an xmlHttp request with serialised DC as data?
 * @return output data
 * @throws ExilityException
 */
public ServiceData processRequest(HttpServletRequest req, HttpServletResponse resp, boolean formIsSubmitted,
        boolean hasSerializedDc) throws ExilityException {
    try {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e) {
        Spit.out("Not UTF-8 : '" + e.getMessage() + "'");
    }

    ServiceData outData = new ServiceData();

    String simpleFileUpload = req.getHeader("simple_file_upload");
    String outDataServiceId = null;
    if (simpleFileUpload != null) {
        boolean isFileUploadSucceeded = this.processSimpleFileUpload(req, outData);
        /**
         * in case of any error in upload, above method would have already
         * put error message. we have to get out of here
         */
        if (isFileUploadSucceeded == false) {
            return outData;
        }
        outDataServiceId = outData.getValue("serviceId");
    }
    // ServiceData inData = this.createInData(req, formIsSubmitted,
    // hasSerializedDc, outData);
    /*
     * the above is commented and changes are done below by introducing a
     * new request header parameter "isStream" in razor plan to avoid the
     * execution of req.getParameterNames() before reading input from
     * request stream , ******these changes has to be relooked for
     * refactoring*****
     */
    ServiceData inData = new ServiceData();
    String isStream = req.getHeader("isStream");

    if (isStream == null) {
        inData = this.createInData(req, formIsSubmitted, hasSerializedDc, outData);
    } else {
        inData = this.createInDataForStream(req, formIsSubmitted, hasSerializedDc, outData);
    }
    /*
     * If user ask for simple file upload and with serviceId then execute
     * it. Like fileUpload. Need to look it.
     */
    if (outDataServiceId != null && inData != null) {
        inData.extractData(outData);
    }

    if (inData == null) {
        return outData;
    }

    String serviceName = inData.getValue("serviceId");

    if (serviceName == null || serviceName.length() == 0) {
        outData.addMessage("exilNoService");
        return outData;
    }

    if (serviceName.equals(HtmlRequestHandler.getLoginServiceName())) {
        this.executeService(req, inData, outData, serviceName);
        this.doLogin(req, resp, outData);
        return outData;
    }

    if (serviceName.equals(HtmlRequestHandler.getLogoutServiceNamr())) {
        this.executeService(req, inData, outData, serviceName);
        this.doLogout(req, resp);
        return outData;
    }

    // TODO: investigate why list service is exempt from security, and make
    // changes for internal service security arrangement
    if (serviceName.equals(HtmlRequestHandler.LIST_SERVICE)) {
        // System.out.print("green channel granted to " + serviceName);
    } else if (SecurityGuard.getGuard().cleared(req, inData, outData) == false) {
        return outData;
    }

    if (serviceName.equals(HtmlRequestHandler.PAGINATION_SERVICE_ID)) {
        this.getPaginationData(req, inData, outData);
        return outData;
    }

    this.executeService(req, inData, outData, serviceName);
    this.savePaginationData(req, inData, outData);

    // do we have to set session variables?
    if (outData.hasValue(HtmlRequestHandler.GLOBAL_FIELDS_NAME)) {
        String sessionObjName = HtmlRequestHandler.GLOBAL_SERVER_DATA_NAME
                + outData.getValue(HtmlRequestHandler.getUserIdName());
        @SuppressWarnings("unchecked")
        Map<String, String> sessionData = (Map<String, String>) req.getSession(true)
                .getAttribute(sessionObjName);
        if (sessionData == null) {
            sessionData = new HashMap<String, String>();
            req.getSession(true).setAttribute(sessionObjName, sessionData);
        }
        String fieldNames = outData.getValue(HtmlRequestHandler.GLOBAL_FIELDS_NAME);
        for (String fieldName : fieldNames.split(",")) {
            sessionData.put(fieldName, outData.getValue(fieldName));
        }
        outData.removeValue(HtmlRequestHandler.GLOBAL_FIELDS_NAME);
    }
    return outData;
}

From source file:jp.or.openid.eiwg.scim.servlet.Users.java

/**
 * POST?/*ww  w  .  j  av a 2 s. co  m*/
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ?
    ServletContext context = getServletContext();

    // ??
    Operation op = new Operation();
    boolean result = op.Authentication(context, request);

    if (!result) {
        // 
        errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
    } else {
        // ?
        String targetId = request.getPathInfo();
        String attributes = request.getParameter("attributes");

        if (targetId != null && !targetId.isEmpty()) {
            // ?'/'???
            targetId = targetId.substring(1);
        }

        if (targetId == null || targetId.isEmpty()) {
            // POST(JSON)?
            request.setCharacterEncoding("UTF-8");
            String body = IOUtils.toString(request.getReader());

            // ?
            LinkedHashMap<String, Object> resultObject = op.createUserInfo(context, request, attributes, body);
            if (resultObject != null) {
                // javaJSON??
                ObjectMapper mapper = new ObjectMapper();
                StringWriter writer = new StringWriter();
                mapper.writeValue(writer, resultObject);

                // Location?URL?
                String location = request.getScheme() + "://" + request.getServerName();
                int serverPort = request.getServerPort();
                if (serverPort != 80 && serverPort != 443) {
                    location += ":" + Integer.toString(serverPort);
                }
                location += request.getContextPath();
                location += "/scim/Users/";
                if (resultObject.get("id") != null) {
                    location += resultObject.get("id").toString();
                }

                // ??
                response.setStatus(HttpServletResponse.SC_CREATED);
                response.setContentType("application/scim+json;charset=UTF-8");
                response.setHeader("Location", location);

                PrintWriter out = response.getWriter();
                out.println(writer.toString());
            } else {
                // 
                errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
            }
        } else {
            errorResponse(response, HttpServletResponse.SC_BAD_REQUEST, null,
                    MessageConstants.ERROR_NOT_SUPPORT_OPERATION);
        }
    }
}