コード例 #1
0
 @RequestMapping(
     value = "/debitAndCredit",
     method = {RequestMethod.POST, RequestMethod.GET})
 public ModelAndView creditAndDebit(HttpServletRequest request, HttpSession session) {
   ModelAndView model = new ModelAndView();
   String userName = "";
   LoginHandler handler = new LoginHandler();
   userName = (String) session.getAttribute("USERNAME");
   String role = (String) session.getAttribute("Role");
   try {
     if (role != null
         && !role.isEmpty()
         && (role.equalsIgnoreCase("USER") || role.equalsIgnoreCase("MERCHANT"))) {
       getAccountNumbers(model, userName, session);
       model.setViewName("creditAndDebit");
     } else {
       if (!userName.isEmpty() || !userName.equalsIgnoreCase(null)) {
         handler.updateLoggedInFlag(userName, 0);
       }
       session.invalidate();
       model.setViewName("index");
     }
   } catch (Exception e) {
     session.invalidate();
     model.setViewName("index");
   }
   return model;
 }
コード例 #2
0
  @RequestMapping(value = "/login", method = RequestMethod.POST)
  // public ModelAndView login(@RequestParam("username")String
  // name,@RequestParam("password")String password)throws Exception{
  public ModelAndView login(@ModelAttribute User user) throws Exception {
    // service.login(name,password);
    // System.out.println(name+password);
    ModelAndView model = new ModelAndView();
    User user1 = service.login(user);

    if (user1.getUser_role() == 1) {
      String msg = "userlogin";
      model.setViewName("userdashboard");
      model.addObject("msg", msg);
    } else if (user1.getUser_role() == 2) {
      model.setViewName("admindashboard");
      String msg = "adminlogin";
      model.addObject("msg", msg);
    } else if (user1.getUser_role() == 3) {
      String msg = null;
      model.addObject("msg", msg);
      model.setViewName("home");
    } else {
      String msg = "error username or password error";
      model.addObject("msg", msg);
      model.setViewName("home");
    }
    return model;
  }
コード例 #3
0
	@RequestMapping(value="/doLogin",method=RequestMethod.GET)
	public ModelAndView login(HttpServletRequest request,User user){
		//System.out.println("in the login");
		User dbUser = userService.getUserByName(user.getUserName());
		ModelAndView mav = new ModelAndView();
		//mav.addObject(ERROR_MSG_KEY,"一切正常");
		if(dbUser==null) {
			mav.addObject(ERROR_MSG_KEY, "用户名不存在");
			mav.setViewName("redirect:/common/resource_not_found.jsp");
			}
//		else if(!dbUser.getPassword().equals(user.getPassword())){
//			mav.addObject(ERROR_MSG_KEY,"用户密码不正确");
//			mav.setViewName("redirect:/common/resource_not_found.jsp");
//		}else{
//			dbUser.setLastIp(request.getRemoteAddr());
//			dbUser.setLastVisit(new Date());
			userService.loginSuccess(dbUser);
			this.setSessionUser(request, dbUser);
			String toUrl=(String)request.getSession().getAttribute(CommonConstant.LOGIN_TO_URL);
			//toUrl要访问的页面,由于拦截器,如果不能通过拦截器不能访问到正确的页面
			request.getSession().removeAttribute(CommonConstant.LOGIN_TO_URL);
			//mav.setViewName("success");//逻辑视图,与applicationContext-mvc下定义的viewResolver对应,不光前面,还有后面的Jsp也不能加
			//这里解析为:/view/success.jsp
			//System.out.println("用户申请跳转到页面:"+toUrl);
			if(StringUtils.isEmpty(toUrl)){
				toUrl="/view/success.jsp";
			}
			mav.setViewName("redirect:"+toUrl);
		}
コード例 #4
0
  @RequestMapping(
      value = {"/", "/welcome**"},
      method = RequestMethod.GET)
  public ModelAndView defaultPage() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    ModelAndView model = new ModelAndView();
    if (!(auth instanceof AnonymousAuthenticationToken)) {
      UserDetails userDetail = (UserDetails) auth.getPrincipal();
      model.addObject("nextBeers", nextBeerDAO.getBeers(userDetail.getUsername()));
      model.addObject(
          "hasBeersWithoutDate", nextBeerDAO.hasBeersWithoutDate(userDetail.getUsername()));
      model.setViewName("homeLogged");
    } else {
      model.setViewName("home");
    }
    NextBeer nextestBeer = nextBeerDAO.getNextBeer();
    Calendar today = Calendar.getInstance();
    today.set(Calendar.HOUR_OF_DAY, 23);
    today.set(Calendar.MINUTE, 59);
    if (nextestBeer != null && today.before(nextestBeer.getDateToPay())) {
      model.addObject("dateToPayNextBeers", nextestBeer.getDateToPay());
    }
    model.addObject("allNextBeers", nextBeerDAO.getAllNextBeers());

    return model;
  }
コード例 #5
0
ファイル: MainController.java プロジェクト: UserYulia/kursach
  @RequestMapping(value = "/reg", method = RequestMethod.POST)
  public ModelAndView register(
      @RequestParam("login") String login,
      @RequestParam("password") String password,
      @RequestParam("mail") String mail) {
    ModelAndView model = new ModelAndView();

    try {
      if (StringUtils.isEmpty(mail)
          || StringUtils.isEmpty(login)
          || StringUtils.isEmpty(password)) {
        throw new IllegalArgumentException();
      }
      User user = new User(login, password, mail);
      model.addObject("title", "Access granted");
      model.addObject("message", "Enter in your mail for activate your account");
      model.setViewName("mail");
      model.addObject(user);
      userService.addUser(user);
    } catch (IllegalArgumentException ex) {
      model.addObject("title", "Registration failed");
      model.addObject("message", "Check your credentials");
      model.setViewName("error");
    } catch (Exception ex) {
      model.addObject("title", "Registration failed");
      model.addObject("message", "Login is already exists");
      model.setViewName("error");
    }
    return model;
  }
コード例 #6
0
  @RequestMapping(method = RequestMethod.POST)
  public ModelAndView processFormSubmit(
      @RequestParam(value = EDIT_PARAM, required = false) String edit,
      @RequestParam(value = CANCEL_PARAM, required = false) String cancel,
      @ModelAttribute("formBean") HolidayFormBean formBean,
      BindingResult result,
      SessionStatus status) {

    String viewName = REDIRECT_TO_ADMIN_SCREEN;

    ModelAndView modelAndView = new ModelAndView();
    if (StringUtils.isNotBlank(edit)) {
      viewName = "defineNewHoliday";
      modelAndView.setViewName(viewName);
      modelAndView.addObject("formBean", formBean);
    } else if (StringUtils.isNotBlank(cancel)) {
      modelAndView.setViewName("redirect:viewHolidays.ftl");
      status.setComplete();
    } else if (result.hasErrors()) {
      modelAndView.setViewName("previewHoliday");
    } else {

      HolidayDetails holidayDetail = holidayAssembler.translateHolidayFormBeanToDto(formBean);
      List<Short> branchIds = holidayAssembler.convertToIds(formBean.getSelectedOfficeIds());

      this.holidayServiceFacade.createHoliday(holidayDetail, branchIds);

      viewName = REDIRECT_TO_ADMIN_SCREEN;
      modelAndView.setViewName(viewName);
      status.setComplete();
    }
    return modelAndView;
  }
コード例 #7
0
ファイル: MainController.java プロジェクト: UserYulia/kursach
 @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
 public ModelAndView authenticate(
     @RequestParam("username") String username, @RequestParam("password") String password) {
   UsernamePasswordAuthenticationToken authenticationToken =
       new UsernamePasswordAuthenticationToken(username, password);
   ModelAndView modelAndView = new ModelAndView();
   User user = userService.getUserByLogin(username);
   if (user != null) {
     if (!user.isEnabled()) {
       modelAndView.addObject("title", "Activate failed");
       modelAndView.addObject("message", "You must activate before log in");
       modelAndView.setViewName("error");
       return modelAndView;
     }
     String token = securityUserService.authWithToken(authenticationToken);
     modelAndView.addObject("token", token);
     modelAndView.addObject("users", userService.findAllUsers());
     modelAndView.addObject("currentUser", userService.getUserByToken(token));
     modelAndView.setViewName("/profile");
     return modelAndView;
   }
   modelAndView.addObject("title", "Invalid credentials ");
   modelAndView.addObject("message", "Check your login and password!");
   modelAndView.setViewName("error");
   return modelAndView;
 }
コード例 #8
0
  /**
   * Description:进入手机认证页面<br>
   *
   * @author justin.xu
   * @version 0.1 2014年4月25日
   * @param session
   * @param request
   * @return ModelAndView
   */
  @RequiresAuthentication
  @RequestMapping(value = "mobileforinsert")
  public ModelAndView mobileforinsert(HttpSession session, HttpServletRequest request) {
    ModelAndView mv = new ModelAndView();
    try {
      ShiroUser shiroUser = currentUser();
      // 手机认证
      MobileApproVo mobileAppro =
          mobileApproService.queryMobileApproByUserId(shiroUser.getUserId());
      // 邮件认证
      EmailApproVo emailApproVo = emailApprService.queryEmailApproByUserId(shiroUser.getUserId());
      mv.addObject("mobileAppro", mobileAppro);
      mv.addObject("emailApproVo", emailApproVo);

      // 修改手机号时原有手机号是否验证通过,不为空代表通过
      if (null
          != session.getAttribute(
              BusinessConstants.MOBILE_APPRO_RESET_FUNCTION + shiroUser.getUserId())) {
        mv.setViewName("account/approve/mobile/newMobile");
        return mv;
      }
      if (null != mobileAppro
          && null != mobileAppro.getPassed()
          && mobileAppro.getPassed() == Constants.YES) {
        mv.setViewName("account/approve/mobile/verifyOldMobile");
      } else {
        mv.setViewName("account/approve/mobile/newMobile");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return mv;
  }
コード例 #9
0
  @RequestMapping(value = "/addCustomer.htm", method = RequestMethod.POST)
  public ModelAndView addCustomer(
      @ModelAttribute("customer") @Valid Customer customer,
      BindingResult result,
      SessionStatus status) {

    ModelAndView mav = new ModelAndView();

    if (result.hasErrors()) {
      LOGGER.info("Error occurred in AddCustomer form ");
      mav.setViewName("AddCustomer");
      mav.addObject("customer", customer);
      return mav;
    } else {
      int resultValue = 0;
      resultValue = customerService.addCustomer(customer);
      if (StringUtils.isBlank(customer.getCustomerID()))
        customer.setCustomerID(Integer.toString(resultValue));

      LOGGER.info("Customer added !! ");
      mav.setViewName("AddCustomer");
      // mav.addObject("resultValue", resultValue);
      mav.addObject("customer", customer);
      return mav;
    }
  }
コード例 #10
0
  @Transactional
  @RequestMapping(value = "/fileRegistered", method = RequestMethod.POST)
  public ModelAndView newFileRegistered(
      @ModelAttribute("file") file file,
      BindingResult result1,
      @ModelAttribute("client") @Valid client client,
      BindingResult result2,
      ModelAndView model) {

    if (result1.hasErrors()) {
      model.setViewName("error");
      System.out.println("File error");
      return model;
    }

    if (result2.hasErrors()) {
      model.setViewName("error");
      System.out.println("Client error");
      return model;
    }

    model.setViewName("success");

    em.persist(client);
    em.flush();
    em.refresh(client);

    file.setClient_ClientID(client.getClientId());
    em.persist(file);

    mapFileWithEmployee(file.getFileNumber(), file.getFileName(), file.getAssignedAdvocate());

    return model;
  }
コード例 #11
0
 @RequestMapping(
     value = {"/addmechanic"},
     method = {RequestMethod.POST})
 public ModelAndView addmechanic(
     @ModelAttribute("mechanic") Mechanic mechanic,
     BindingResult bindingResult,
     Model model,
     HttpSession session,
     Authentication auth) {
   ModelAndView mav = new ModelAndView();
   mechanicValidator.validate(mechanic, bindingResult);
   if (bindingResult.hasErrors()) {
     UserPrincipal user = userService.getUserByName(auth.getName());
     mav.addObject("user", user);
     mav.addObject("stos", directorService.getSto());
     mav.setViewName("director.addmechanic");
     return mav;
   }
   mechanic.setLogin(mechanic.getName());
   mechanic.setRating((float) 0);
   mechanic.setRole(UserRole.MECHANIC);
   directorService.saveOrUpdateMechanic(mechanic);
   mav.setViewName("redirect:/home");
   return mav;
 }
コード例 #12
0
  @RequestMapping(
      value = {"/updateapplicationdetail/{id}"},
      method = {RequestMethod.POST})
  public ModelAndView updateapplicationdetail(
      @PathVariable Long id,
      @ModelAttribute("applicationdetails") ApplicationDetail applicationDetail,
      BindingResult bindingResult,
      Model model,
      HttpSession session,
      Authentication auth) {
    ModelAndView mav = new ModelAndView();
    applicationDetailValidator.validate(applicationDetail, bindingResult);
    if (bindingResult.hasErrors()) {
      UserPrincipal user = userService.getUserByName(auth.getName());
      mav.addObject("statuss", directorService.getStatus());
      mav.addObject("applicationdetail", directorService.getApplicationDetailById(id));
      mav.addObject("user", user);
      mav.setViewName("director.updateapplicationdetail");
      return mav;
    }

    ApplicationDetail applicationDetail1 =
        directorService.getApplicationDetailById(applicationDetail.getId());
    applicationDetail1.setStatus(applicationDetail.getStatus());
    applicationDetail1.setDateDelivery(applicationDetail.getDateDelivery());
    // applicationDetail.setId(1l);
    directorService.saveApplicationDetail(applicationDetail1);
    mav.setViewName("redirect:/home");
    return mav;
  }
コード例 #13
0
  // 옵션 비교페이지로 이동합니다.
  @SuppressWarnings("unchecked")
  @RequestMapping(value = "/option_03.isnet")
  public ModelAndView option_03() {

    logger.debug("[" + getClass().getSimpleName() + "] [option_03] start");

    ModelAndView mav = new ModelAndView();
    mav.setViewName("/option/option_03");

    try {
      Map<String, Object> resultData = commonCodeMap.getCommonCodeMap();

      List<Map<String, Object>> customerList =
          (List<Map<String, Object>>) resultData.get("customerList");
      List<Map<String, Object>> productList =
          (List<Map<String, Object>>) resultData.get("productList");
      // List<Map<String, Object>> optionFile = optionService.select_option_03_05();

      mav.addObject("customerList", customerList);
      mav.addObject("productList", productList);
      // mav.addObject("optionFile", optionFile);

    } catch (Exception e) {
      e.printStackTrace();
      logger.error("[" + getClass().getSimpleName() + "] [option_03] 조회 오류");
      mav.addObject("error_msg", "옵션 조회중  오류가 발생하였습니다.");
      mav.setViewName("error");
    } finally {
      logger.debug("[" + getClass().getSimpleName() + "] [option_03] end");
    }

    return mav;
  }
コード例 #14
0
  @RequestMapping(
      value = {"/updatesto/{id}"},
      method = {RequestMethod.POST})
  public ModelAndView updatesto(
      @PathVariable Long id,
      @ModelAttribute("sto") Sto sto,
      BindingResult bindingResult,
      Model model,
      HttpSession session,
      Authentication auth) {
    ModelAndView mav = new ModelAndView();
    rentValidator.validate(sto, bindingResult);
    if (bindingResult.hasErrors()) {
      logger.info("Returning updatesto.jsp page");
      UserPrincipal user = userService.getUserByName(auth.getName());
      mav.addObject("user", user);
      mav.addObject("sto", directorService.getStoById(id));
      mav.setViewName("director.updatesto");
      return mav;
    }

    Sto sto1 = directorService.getStoById(id);
    sto1.setName(sto.getName());
    sto1.setPrice(sto.getPrice());
    directorService.addSto(sto1);
    mav.setViewName("redirect:/home");
    return mav;
  }
コード例 #15
0
  @RequestMapping(method = RequestMethod.GET, value = "/criaRespostaCotacao")
  public ModelAndView newRespostaCotacao(Cotacao cotacao) {

    RespostaCotacao resposta = new RespostaCotacao();

    if (usuarioService.ehUsuarioLogado()) {
      ModelAndView mv = new ModelAndView("/cotacao/cotacao", "cotacao", cotacao);
      mv.addObject("msg", "A abertura de negociação é sempre feita por um Fornecedor.");
      mv.setViewName("mostraCotacao");
      return mv;
    } else {
      if (!service.possuiNegociacaoAberta(
          cotacao.getId(), fornecedorService.getLoggedFornecedor().getId())) {
        cotacao = service.getCotacao(cotacao.getId());
        cotacao.setStatus(Status.TRABALHO);
        cotacao.setDataAtualizacao(new Date());
        service.atualizarCotacao(cotacao);

        resposta.setCotacao(cotacao);
        resposta.setPredio(cotacao.getPredio());
        resposta.setFornecedor(fornecedorService.getLoggedFornecedor());
        ModelAndView mv =
            new ModelAndView("/cotacao/respostaCotacao/criaResposta", "resposta", resposta);
        mv.setViewName("criaRespostaCotacao");
        return mv;
      } else {
        ModelAndView mv = new ModelAndView("/cotacao/cotacao", "cotacao", cotacao);
        mv.addObject("msg", "Fornecedor já possui negociação na Cotação.");
        mv.setViewName("mostraCotacao");
        return mv;
      }
    }
  }
コード例 #16
0
ファイル: cartController.java プロジェクト: ak826843/ordero
  @RequestMapping(value = "/billing")
  public ModelAndView confirmOrder(
      @RequestParam("username") String username,
      @RequestParam("prodId") int prodId,
      @RequestParam("prodType") String prodType,
      @RequestParam("prodRate") double rate,
      @RequestParam("quantity") int quantityByUser,
      @RequestParam("qty") int qtyInInventory) {
    System.out.println("in checkout");

    ModelAndView mv = new ModelAndView();

    if (quantityByUser <= qtyInInventory) {
      System.out.println("username inside checkout controller:" + username);
      mv.addObject("prodId", prodId);
      mv.addObject("prodType", prodType);
      mv.addObject("username", username);
      mv.addObject("prodRate", rate);
      mv.addObject("quantity", quantityByUser);
      mv.setViewName("billing");
    } else {
      mv.setViewName("error");
      mv.addObject("error", "Invalid input! Quantity requested is more than available.");
    }

    return mv;
  }
コード例 #17
0
  // Filtros
  @RequestMapping(value = "/centrocusto_lista", method = RequestMethod.POST)
  public ModelAndView filtros(
      @ModelAttribute CentroCusto filtros, @PageableDefault(size = 10) Pageable pageable) {
    ModelAndView mav = new ModelAndView();
    Usuario usuario = rotinas.usuarioLogado();
    List<Empresa> listaEmpresa = empresaDao.selectEmpresasUsuario(usuario.getId_usuario());

    if (!listaEmpresa.isEmpty()) {
      filtros.setId_Empresa(listaEmpresa.get(0).getId_Empresa());
    }
    ;

    Boolean lista = rotinas.validaTransacaoUsuario(usuario.getId_usuario(), "1501");
    if (lista != true) {
      mav.addObject("mensagem", "AVISO: Transação não permitida.");
      mav.setViewName("mensagemerro");
      return mav;
    }
    Boolean novo = rotinas.validaTransacaoUsuario(usuario.getId_usuario(), "150101");
    Boolean editar = rotinas.validaTransacaoUsuario(usuario.getId_usuario(), "150102");
    Boolean deletar = rotinas.validaTransacaoUsuario(usuario.getId_usuario(), "150103");
    Boolean detalhes = rotinas.validaTransacaoUsuario(usuario.getId_usuario(), "150104");

    mav.addObject("novo", novo);
    mav.addObject("editar", editar);
    mav.addObject("deletar", deletar);
    mav.addObject("detalhes", detalhes);

    mav.addObject("filtros", filtros);
    mav.addObject("listaempresa", listaEmpresa);
    mav.addObject("lista", centroCustoDao.selectAll_paginado(filtros.getId_Empresa(), pageable));
    mav.addObject("pagina", new Pagina(pageable, centroCustoDao.count(filtros.getId_Empresa())));
    mav.setViewName("centrocusto_lista");
    return mav;
  }
コード例 #18
0
 @RequestMapping(value = "/find.html")
 public ModelAndView find(@RequestParam(value = "q", required = false) String q) {
   ModelAndView mav = new ModelAndView();
   mav.addObject("operation", "find");
   if (StringUtils.isEmpty(q)) {
     mav.setViewName("find");
     return mav;
   }
   try {
     if (NumberUtils.isNumber(q) && StringUtils.length(q) == 7) {
       return show(Integer.valueOf(q));
     } else {
       long startTs = System.currentTimeMillis();
       List<TConcept> concepts = nodeService.findConcepts(q);
       mav.addObject("concepts", concepts);
       long endTs = System.currentTimeMillis();
       mav.addObject("q", q);
       mav.addObject("elapsed", new Long(endTs - startTs));
     }
   } catch (Exception e) {
     mav.addObject("error", e.getMessage());
   }
   mav.setViewName("find");
   return mav;
 }
コード例 #19
0
ファイル: PDFController.java プロジェクト: chasethenag420/sbs
  @RequestMapping(value = "/bankStatement", method = RequestMethod.GET)
  public ModelAndView getCreditForm(HttpServletRequest request) {

    String username = (String) request.getSession().getAttribute("username");
    if (username == null || username.equals("")) {
      ModelAndView modelView = new ModelAndView();
      modelView.addObject("error", "User does not exit. Enter valid username");

      modelView.setViewName("login");
      return modelView;
    }
    Users user = userDao.getUserByUserName(username);
    List<String> accountNumbers = new ArrayList<String>();
    for (Account account : accountService.getAccounts(user.getUserId())) {
      accountNumbers.add("" + account.getAccountNumber());
    }
    //

    // logs debug message
    if (logger.isDebugEnabled()) {
      logger.debug("bank statement Screen is executed!");
    }
    ModelAndView modelView = new ModelAndView();

    modelView.addObject("form", new TransactionForm());
    modelView.addObject("accounts", accountNumbers);
    modelView.setViewName("bankStatement");
    return modelView;
  }
コード例 #20
0
 @RequestMapping(value = "create.htm", method = RequestMethod.POST)
 public ModelAndView createTumbon(@ModelAttribute Tumbon tumbon, BindingResult result) {
   logger.info(" Start  ");
   ModelAndView mav = new ModelAndView();
   try {
     new TumbonValidator().validate(tumbon, result);
     if (result.hasErrors()) {
       mav.setViewName("tumbonCreate");
     } else {
       BuckWaRequest request = new BuckWaRequest();
       request.put("tumbon", tumbon);
       BuckWaResponse response = tumbonService.create(request);
       if (response.getStatus() == BuckWaConstants.SUCCESS) {
         mav.addObject("tumbon", new Tumbon());
         mav.addObject("successCode", response.getSuccessCode());
         mav.setViewName("tumbonCreateSuccess");
       } else {
         mav.addObject("errorCode", response.getErrorCode());
         mav.setViewName("tumbonCreate");
       }
     }
   } catch (Exception ex) {
     ex.printStackTrace();
     mav.addObject("errorCode", "E001");
   }
   return mav;
 }
コード例 #21
0
  @RequestMapping(method = RequestMethod.POST)
  public ModelAndView processFormSubmit(
      @RequestParam(value = CANCEL_PARAM, required = false) String cancel,
      @ModelAttribute("savingsProduct") @Valid SavingsProductFormBean savingsProductFormBean,
      BindingResult result,
      SessionStatus status) {

    ModelAndView modelAndView =
        new ModelAndView("redirect:/previewSavingsProducts.ftl?editFormview=editSavingsProduct");

    configurationDto = this.configurationServiceFacade.getAccountingConfiguration();
    modelAndView.addObject("GLCodeMode", configurationDto.getGlCodeMode());

    if (StringUtils.isNotBlank(cancel)) {
      modelAndView.setViewName(REDIRECT_TO_ADMIN_SCREEN);
      status.setComplete();
    } else if (result.hasErrors()) {
      new SavingsProductValidator().validateGroup(savingsProductFormBean, result);
      modelAndView.setViewName("editSavingsProduct");
    } else {
      new SavingsProductValidator().validateGroup(savingsProductFormBean, result);
      if (result.hasErrors()) {
        modelAndView.setViewName("editSavingsProduct");
      }
    }

    return modelAndView;
  }
コード例 #22
0
  @RequestMapping(
      value = {"/updateapplication/{id}"},
      method = {RequestMethod.POST})
  public ModelAndView updateapplication(
      @PathVariable Long id,
      @ModelAttribute("application") Application application,
      Model model,
      BindingResult bindingResult,
      HttpSession session,
      Authentication auth) {
    ModelAndView mav = new ModelAndView();
    Application application1 = mechanicService.getApplicationById(id);
    applicationValidator.validate(application, bindingResult);
    if (bindingResult.hasErrors()) {

      UserPrincipal user = userService.getUserByName(auth.getName());
      Number size1 = directorService.getSizeMechanicOnSto(application1.getSto());
      int size = Integer.parseInt(size1.toString());
      mav.addObject("application", application1);
      mav.addObject("statuss", directorService.getStatus());
      mav.addObject("mechanics", directorService.getMechanicsOnSto(application1.getSto(), 0, size));
      mav.addObject("user", user);
      mav.setViewName("director.updateapplication");
      return mav;
    }

    application1.setMechanic(application.getMechanic());
    application1.setStatus(application.getStatus());
    clientService.addOrUpdateApplication(application1);
    mav.setViewName("redirect:/home");
    return mav;
  }
コード例 #23
0
  @RequestMapping(value = "/index", method = RequestMethod.POST)
  public org.springframework.web.servlet.ModelAndView checkLogin(
      HttpServletRequest request, Model model) {

    org.springframework.web.servlet.ModelAndView mv =
        new org.springframework.web.servlet.ModelAndView();

    LoginCheck loginCheck =
        new LoginCheck(request.getParameter("username"), request.getParameter("password"));

    if (loginCheck.check()) {
      mv.addObject("message", "Hello World");
      UserBean ub = loginCheck.getUserBean();
      mv.addObject("bean", ub);
      HttpSession session = request.getSession();

      session.setMaxInactiveInterval(60 * 15);

      session.setAttribute("username", request.getParameter("username"));
      session.setAttribute("password", request.getParameter("password"));
      mv.setViewName("admin/index");
    } else {
      mv.addObject("message", "hehehe");
      mv.setViewName("error");
    }

    return mv;
  }
  @RequestMapping(value = "/newtransemployee/op1", method = RequestMethod.POST)
  public ModelAndView newTransEmployeePost(
      @ModelAttribute @Valid User user,
      BindingResult result,
      final RedirectAttributes attributes,
      Principal principal)
      throws BankDeactivatedException {
    System.out.println("INSIDE trans manager post Controller for new employee .............");
    OneTimePassword otp = new OneTimePassword();
    String message;
    ModelAndView mav = new ModelAndView();
    try {
      System.out.println("\n Inside Employee signup post controller");
      if (result.hasErrors()) {
        // return new ModelAndView("hr/newhremployee", "signupemployee",employee);
        // return savedMav;
        // return new ModelAndView("hr/manager/manager","signupemployee",user);
        message = "Validation Errors observed.Please go back and fill valid information";
        mav.addObject("message", message);
        mav.setViewName("signup/saveData");
        return mav;
        // return new ModelAndView("signup/saveData", "signupemployee",user);
      }

      mav.setViewName("signup/saveData");
      message =
          "Congratulations..!! Your request has been approved. Please ask the user to check the email and login";
      user.setDepartment("TM");
      user.setRole("ROLE_TRANSACTION_EMPLOYEE");
      user.setCreatedBy(principal.getName());
      Md5PasswordEncoder passwordEncoder = new Md5PasswordEncoder();
      String password = otp.getPassword();
      String hashedPassword = passwordEncoder.encodePassword(otp.getPassword(), null);

      transManager.insertValidUser(user, hashedPassword, principal.getName());
      enManager.sendPassword(user, password);
      mav.addObject("message", message);
      mav.addObject("username", principal.getName());
      return mav;
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      if (e instanceof com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException) {
        message = "Username already Exists.Choose a different username";
        mav.addObject("message", message);
        mav.setViewName("signup/saveData");
        mav.addObject("username", principal.getName());
        return mav;
      } else if (e instanceof BankDeactivatedException) {
        throw new BankDeactivatedException(e.getMessage());
      } else {
        message = "Error in saving your data.Please try again";
        mav.addObject("message", message);
        mav.setViewName("signup/saveData");
        mav.addObject("username", principal.getName());
        return mav;
      }
    }
  }
コード例 #25
0
  @RequestMapping(value = "/", method = RequestMethod.POST)
  public ModelAndView process(
      @Valid RecommenderForm recommenderForm,
      HttpServletRequest request,
      ModelAndView mav,
      BindingResult result)
      throws IOException, TasteException {
    if (result.hasErrors()) {
      mav.setViewName("/");
      return mav;
    }
    // 이웃은
    int neighborhoodCount = recommenderForm.getNeighborhoodCount();

    // 임계치
    double trainingPercentage = recommenderForm.getTrainingPercentage();

    // 파일로 데이터 모델 생성
    DataModel dataModel =
        new FileDataModel(
            new File(request.getSession().getServletContext().getRealPath("resources/ua.base")));

    mav.addObject("neighborhoodCount", neighborhoodCount);
    mav.addObject("trainingPercentage", trainingPercentage);

    // 각 알고리즘 별 평가치
    mav.addObject(
        "euclideanDistanceSimilarity",
        recommenderService.getRecommenderScore(
            dataModel,
            new EuclideanDistanceSimilarity(dataModel),
            neighborhoodCount,
            trainingPercentage));
    mav.addObject(
        "pearsonCorrelationSimilarity",
        recommenderService.getRecommenderScore(
            dataModel,
            new PearsonCorrelationSimilarity(dataModel),
            neighborhoodCount,
            trainingPercentage));
    mav.addObject(
        "logLikelihoodSimilarity",
        recommenderService.getRecommenderScore(
            dataModel,
            new LogLikelihoodSimilarity(dataModel),
            neighborhoodCount,
            trainingPercentage));
    mav.addObject(
        "tanimotoCoefficientSimilarity",
        recommenderService.getRecommenderScore(
            dataModel,
            new TanimotoCoefficientSimilarity(dataModel),
            neighborhoodCount,
            trainingPercentage));

    mav.setViewName("home");
    return mav;
  }
コード例 #26
0
ファイル: SettingsController.java プロジェクト: DM-TOR/nhin-d
  @PreAuthorize("hasRole('ROLE_ADMIN')")
  @RequestMapping(value = "/addsetting", method = RequestMethod.POST)
  public ModelAndView addSetting(
      @RequestHeader(value = "X-Requested-With", required = false) String requestedWith,
      HttpSession session,
      @ModelAttribute SettingsForm settingsForm,
      Model model,
      @RequestParam(value = "submitType") String actionPath) {

    ModelAndView mav = new ModelAndView();
    String strid = "";
    String key = "";
    String value = "";
    if (log.isDebugEnabled()) log.debug("Enter domain/addsetting");

    if (actionPath.equalsIgnoreCase("cancel")) {
      if (log.isDebugEnabled()) log.debug("trying to cancel from saveupdate");
      SearchDomainForm form2 = (SearchDomainForm) session.getAttribute("searchDomainForm");
      model.addAttribute(form2 != null ? form2 : new SearchDomainForm());
      model.addAttribute("ajaxRequest", AjaxUtils.isAjaxRequest(requestedWith));

      mav.setViewName("main");
      mav.addObject("statusList", EntityStatus.getEntityStatusList());
      return mav;
    }
    if (actionPath.equalsIgnoreCase("newsetting") || actionPath.equalsIgnoreCase("add setting")) {
      if (log.isDebugEnabled()) log.debug("trying to get/set settings");
      strid = "" + settingsForm.getId();
      key = "" + settingsForm.getKey();
      value = "" + settingsForm.getValue();
      try {
        if (log.isDebugEnabled()) log.debug("trying set settings services");
        configSvc.addSetting(key, value);
        if (log.isDebugEnabled()) log.debug("PAST trying set settings services");
      } catch (ConfigurationServiceException e) {
        e.printStackTrace();
      }

      model.addAttribute("ajaxRequest", AjaxUtils.isAjaxRequest(requestedWith));
      SimpleForm simple = new SimpleForm();
      simple.setId(Long.parseLong(strid));
      model.addAttribute("simpleForm", simple);

      try {
        model.addAttribute("settingsResults", configSvc.getAllSettings());
      } catch (ConfigurationServiceException e) {
        e.printStackTrace();
      }
      mav.setViewName("settings");
      // the Form's default button action
      String action = "Update";
      model.addAttribute("settingsForm", settingsForm);
      model.addAttribute("action", action);
      model.addAttribute("ajaxRequest", AjaxUtils.isAjaxRequest(requestedWith));
    }

    return mav;
  }
コード例 #27
0
ファイル: OpentimeController.java プロジェクト: jrtMgr/mgr
  @RequestMapping("/list")
  public ModelAndView list(
      @RequestParam(value = "lotno") String lotno,
      @RequestParam(value = "batchcode") String batchcode,
      @RequestParam(value = "starttime") String starttime,
      @RequestParam(value = "endtime") String endtime,
      ModelAndView view) {
    logger.info("opentime/list");
    if (StringUtil.isEmpty(lotno) || StringUtil.isEmpty(starttime) || StringUtil.isEmpty(endtime)) {
      view.addObject("errormsg", "时间不允许为空");
      view.setViewName("opentime/list");
      return view;
    }
    StringBuilder builder = new StringBuilder("where");
    List<Object> params = new ArrayList<Object>();
    StringBuilder mysql = new StringBuilder("where");
    builder.append(" o.id.lotno=? and");
    params.add(lotno);
    mysql.append(" o.lotno = ? and");
    if (!StringUtil.isEmpty(batchcode)) {
      builder.append(" o.batchcode =? and");
      params.add(batchcode);
      mysql.append(" o.batchcode = ? and");
    }
    if (!StringUtil.isEmpty(starttime)) {
      builder.append(" to_char(o.agencyopentime, 'yyyy-mm-dd') >= ? and");
      params.add(starttime);
      mysql.append(" o.codedate >= ? and");
    }
    if (!StringUtil.isEmpty(endtime)) {
      builder.append(" to_char(o.agencyopentime, 'yyyy-mm-dd') <= ? and");
      params.add(endtime + " 23:59:59");
      mysql.append(" o.codedate <= ? and");
    }
    if (builder.toString().endsWith("and")) {
      builder.delete(builder.length() - 3, builder.length());
      mysql.delete(mysql.length() - 3, mysql.length());
    }
    if (builder.toString().endsWith("where")) {
      builder.delete(builder.length() - 5, builder.length());
      mysql.delete(mysql.length() - 5, mysql.length());
    }

    try {
      if (!StringUtil.isEmpty(builder.toString())) {
        view.addObject("list", Twininfo.findAllTwininfoes(builder.toString(), params));
        view.addObject(
            "list2", prizecrawlerDao.findAllTagencyprizecode2(mysql.toString(), params.toArray()));
      }

    } catch (Exception e) {
      view.addObject("errormsg", "查询出错");
      logger.error("opentime/list error", e);
    }
    view.setViewName("opentime/list");
    return view;
  }
コード例 #28
0
  @RequestMapping(method = RequestMethod.POST)
  public ModelAndView add(DatasetForm datasetEntryForm, Errors errors, HttpSession session) {
    ModelAndView mav = new ModelAndView();

    validatorDataEntry.validate(datasetEntryForm, errors);
    if (errors.hasErrors()) {
      logger.error("Errores en la validacion del formulario");
      mav.addObject("privateKey", properties.getReCaptchaPrivateKey());
      mav.addObject("publicKey", properties.getReCaptchaPublicKey());
      mav.setViewName("dataset/add");
      return mav;
    }

    PreDataset aDataset = datasetEntryForm.build();

    // the resource's length will be calculated later on a separate thread.
    aDataset.setSize(0);

    ArgendataUser user = (ArgendataUser) session.getAttribute("user");

    if (!aDataset.getDistribution().equals("Download")) {
      aDataset.setFormat("");
      aDataset.setSize(0);
    }

    if (!user.isAdmin()) {
      try {
        aDataset.setSize(getResourceLength(aDataset));
        datasetService.store(aDataset);
      } catch (Exception e) {
        logger.error("No se pudo agregar el dataset al store relacional");
        logger.error(e.getMessage(), e);
        mav.setViewName("redirect:../static/error");
        return mav;
      }

      mav.setViewName("redirect:../user/home?state=1");
    } else {
      Dataset readyDataset = aDataset.toNoRelationalDataset();

      try {
        datasetService.store(readyDataset);
      } catch (Exception e) {
        logger.error("No se pudo agregar el dataset al store semántico");
        logger.error(e.getMessage(), e);
        mav.setViewName("redirect:../static/error");

        return mav;
      }

      mav.setViewName("redirect:../search/searchDataHome");
    }

    asyncResourceLength(aDataset, user.isAdmin());

    return mav;
  }
コード例 #29
0
  @RequestMapping(
      value = "/viewBal",
      method = {RequestMethod.POST, RequestMethod.GET})
  public ModelAndView viewBalance(HttpServletRequest request, HttpSession session) {
    ModelAndView model = new ModelAndView();
    LoginHandler handler = new LoginHandler();
    String userName = "";
    userName = (String) session.getAttribute("USERNAME");
    String role = (String) session.getAttribute("Role");
    try {
      if (role != null
          && !role.isEmpty()
          && (role.equalsIgnoreCase("USER") || role.equalsIgnoreCase("MERCHANT"))) {
        ResultSet rs = handler.requestBalance(userName);
        List<AccountDetails> acntdetails = new ArrayList<AccountDetails>();

        try {
          while (rs.next()) {
            AccountDetails details = new AccountDetails();
            details.setAccountNumber(rs.getString("accountnumber"));
            details.setAccountType(rs.getString("accounttype"));
            details.setBalance(rs.getDouble("balance"));
            acntdetails.add(details);
          }
          model.addObject("accountDetails", acntdetails);
          rs.close();

        } catch (SQLException e) {
          model.addObject("accountDetails", "");
          try {
            if (!userName.isEmpty() || !userName.equalsIgnoreCase(null)) {
              handler.updateLoggedInFlag(userName, 0);
            }
          } catch (Exception e1) {
            session.invalidate();
            model.setViewName("index");
          }
          session.invalidate();
          model.setViewName("index");
          e.printStackTrace();
        }

        model.setViewName("viewBalance");
      } else {
        if (!userName.isEmpty() || !userName.equalsIgnoreCase(null)) {
          handler.updateLoggedInFlag(userName, 0);
        }
        session.invalidate();
        model.setViewName("index");
      }
    } catch (Exception e) {
      session.invalidate();
      model.setViewName("index");
    }

    return model;
  }
コード例 #30
0
ファイル: cartController.java プロジェクト: ak826843/ordero
  @RequestMapping(value = "/checkout", method = RequestMethod.POST)
  public ModelAndView validateUser(
      @RequestParam("username") String username,
      @RequestParam("password") String password,
      @RequestParam("prodType") String prodType,
      @RequestParam("prodId") int prodId) {
    System.out.println("in checkout");

    DBConnection connection = new DBConnection();
    boolean signingin = false;
    signingin = connection.signIn(username, password);

    ModelAndView mv = new ModelAndView();

    // Validate user
    if (signingin) {
      // Valid user
      MongoDBConnection mongoConnection = new MongoDBConnection();

      if (!mongoConnection.mongoDBProdAvail(prodType, prodId)) {
        mv.addObject("error", "Database down! Please come back later.");
        mv.setViewName("error");
        return mv;
      }
      DBObject product = mongoConnection.mongoDBGetProduct(prodType, prodId);

      boolean result = connection.checkInventoryForMoreThanZeroItems(prodType, prodId);
      if (result) {
        System.out.println("username inside login controller:" + username);
        Inventory obj = new Inventory();
        obj = connection.displayItemType(prodType, prodId);
        mv.addObject("username", username);
        mv.addObject("prodId", prodId);
        mv.addObject("prodType", prodType);
        mv.addObject("prodRate", obj.getRateperitem());
        mv.addObject("qty", obj.getQty());
        mv.addObject("message", "Product available");
        mv.addObject("product", product);
        mv.setViewName("checkout");
      } else {
        // 0 products available
        mv.addObject("error", "Sorry! Item Not on Sale.");
        // mv.addObject("redirectUrl", "http://localhost:8090/store");
        // mv.addObject("button", "Back to store");
        mv.setViewName("error");
      }
    } else {
      // Invalid user
      mv.setViewName("failure");
      mv.addObject("error", "Invalid login! Wrong username or password. ");
      mv.addObject("redirectUrl", "http://localhost:8080/cart/login/" + prodType + '/' + prodId);
    }
    return mv;
  }