Пример #1
0
  /**
   * Removes any <code>ActionMessages</code> object stored in the session under <code>
   * Globals.MESSAGE_KEY</code> and <code>Globals.ERROR_KEY</code> if the messages' <code>isAccessed
   * </code> method returns true. This allows messages to be stored in the session, display one
   * time, and be released here.
   *
   * @param request The servlet request we are processing.
   * @param response The servlet response we are creating.
   * @since Struts 1.2
   */
  protected void processCachedMessages(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession(false);

    if (session == null) {
      return;
    }

    // Remove messages as needed
    ActionMessages messages = (ActionMessages) session.getAttribute(Globals.MESSAGE_KEY);

    if (messages != null) {
      if (messages.isAccessed()) {
        session.removeAttribute(Globals.MESSAGE_KEY);
      }
    }

    // Remove error messages as needed
    messages = (ActionMessages) session.getAttribute(Globals.ERROR_KEY);

    if (messages != null) {
      if (messages.isAccessed()) {
        session.removeAttribute(Globals.ERROR_KEY);
      }
    }
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @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 {
    HttpSession session = request.getSession(true);
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    session.removeAttribute("error");
    session.removeAttribute("sucesso");

    Usuario user = (Usuario) session.getAttribute("user");
    String idSecaoS = request.getParameter("idSecao");
    try {
      int id = Integer.parseInt(idSecaoS);
      if (user != null && user instanceof Editor) {
        Editor editor = (Editor) user;
        Secao secao = editor.getSecao(id);
        if (secao != null) {
          session.setAttribute("secao", secao);
          response.sendRedirect(request.getContextPath() + "/editorAdicionarSecao.jsp");
        } else {
          session.setAttribute("error", "Voce nao tem permissao para atualizar essa secao.");
          response.sendRedirect(request.getContextPath() + "/editorListarSecao.jsp");
        }
      } else {
        session.setAttribute("error", "Voce nao tem permissao para acessar essa area.");
        response.sendRedirect(request.getContextPath() + "/index.jsp");
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      session.invalidate();
      response.sendRedirect(request.getContextPath() + "/index.jsp");
    }
  }
Пример #3
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String op = request.getParameter("op");
    HttpSession session = request.getSession(true);

    Categoria c = new Categoria();
    dao.Dao<Categoria> daoC = new Dao<Categoria>(Categoria.class);
    if (op.equals("Salvar")) {
      c.setNome(request.getParameter("nomeCategoria"));
      daoC.insert(c);

      response.sendRedirect("categoria.jsp");
    }
    if (op.equals("Gerenciar")) {
      session.setAttribute("nomeBusca", "nao");
      response.sendRedirect("GerenciaCategoria.jsp");
    }
    if (op.equalsIgnoreCase("Buscar")) {
      session.setAttribute("nomeBusca", request.getParameter("nomeBusca"));
      response.sendRedirect("GerenciaCategoria.jsp");
    }
    if (op.equals("Atualizar")) {
      c = (Categoria) session.getAttribute("categoria");
      c.setNome(request.getParameter("nomeC"));
      daoC.update(c);
      session.removeAttribute("categoria");
      response.sendRedirect("GerenciaCategoria.jsp");
    }
    if (op.equalsIgnoreCase("OK")) {
      session.removeAttribute("remover");
      response.sendRedirect("GerenciaCategoria.jsp");
    }
  }
  /**
   * Зарегестрировать
   *
   * @param registrationInfo - Информация о пользователе и его организации
   * @return - отображение запрашиваемого ресурса
   * @throws UnsupportedEncodingException - ошибка о не правильной раскодировке
   */
  @RequestMapping(method = RequestMethod.POST)
  public String registration(@Valid RegistrationInfo registrationInfo, BindingResult result)
      throws UnsupportedEncodingException {

    HttpSession session = getSession();

    // Получаем сообщения об ошибках, если они есть
    List<ObjectError> erorList = result.getAllErrors();
    List<String> erorMessageList = new ArrayList<>();
    try {
      if (!erorList.isEmpty()) {
        erorMessageList = CompanyController.getListMessageForEror(erorList);
        session.setAttribute("uncorrectRegistrationUserCompany", registrationInfo);
        session.setAttribute("listErorRegistration", erorMessageList);
        return "redirect:/registration";
      }

      OrganizationInfo regestratingCompany = userService.registration(registrationInfo);

      session.removeAttribute("uncorrectRegistrationUserCompany");
      session.removeAttribute("listErorRegistration");
      return "redirect:/login";

    } catch (Exception e) {
      erorMessageList.add("Системная ошибка!");
      session.setAttribute("listErorRegistration", erorMessageList);
      session.setAttribute("uncorrectRegistrationUserCompany", registrationInfo);
      return "redirect:/registration";
    }
  }
Пример #5
0
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    resp.setContentType(TEXT_HTML);
    Enumeration<String> parameterNames = req.getParameterNames();
    Map<String, String> params = new HashMap<>();
    while (parameterNames.hasMoreElements()) {
      String current = parameterNames.nextElement();
      params.put(current, req.getParameter(current));
    }

    if (params.get(LOGIN) != null) {
      UserDto userDto = userController.getByLogin(params.get(EMAIL));
      User user = userDto.getUser();
      if (user == null || !user.getPassword().equals(params.get(PASSWORD))) {
        req.setAttribute(LOGIN_FAILED, true);
      } else {
        HttpSession session = req.getSession(true);
        session.setAttribute(USER, user);
      }
    }
    if (params.get(REGISTER) != null) {
      resp.sendRedirect("/cafe/register");
    } else {
      if (params.get(LOGOUT) != null) {
        HttpSession session = req.getSession(true);
        session.removeAttribute(USER);
        session.removeAttribute(ORDER);
      }
      RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(MAIN_JSP);
      dispatcher.forward(req, resp);
    }
  }
Пример #6
0
 public void logout() throws IOException {
   HttpSession session = (HttpSession) getExternalContext().getSession(true);
   session.removeAttribute("username");
   session.removeAttribute("passwd");
   session.invalidate();
   redirectLogin();
 }
 public boolean restoreRequest() {
   HttpSession session = myRequest.getSession(false);
   if (session == null) return false;
   synchronized (session) {
     String j_uri = (String) session.getAttribute(FormAuthenticator.__J_URI);
     if (j_uri != null) {
       // check if the request is for the same url as the original and restore
       // params if it was a post
       StringBuffer buf = myRequest.getRequestURL();
       if (myRequest.getQueryString() != null) buf.append("?").append(myRequest.getQueryString());
       if (j_uri.equals(buf.toString())) {
         String method = (String) session.getAttribute(JettyHttpFacade.__J_METHOD);
         myRequest.setMethod(HttpMethod.valueOf(method.toUpperCase()), method);
         MultivaluedHashMap<String, String> j_post =
             (MultivaluedHashMap<String, String>) session.getAttribute(CACHED_FORM_PARAMETERS);
         if (j_post != null) {
           myRequest.setContentType("application/x-www-form-urlencoded");
           MultiMap<String> map = new MultiMap<String>();
           for (String key : j_post.keySet()) {
             for (String val : j_post.getList(key)) {
               map.add(key, val);
             }
           }
           restoreFormParameters(map, myRequest);
         }
         session.removeAttribute(FormAuthenticator.__J_URI);
         session.removeAttribute(JettyHttpFacade.__J_METHOD);
         session.removeAttribute(FormAuthenticator.__J_POST);
       }
       return true;
     }
   }
   return false;
 }
Пример #8
0
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    HttpSession session = request.getSession();
    InternalStaff employee = (InternalStaff) session.getAttribute("user");
    InternalStaff changedEmployee = null;
    InternalStaff admin = null;
    String userId = request.getParameter("userId");
    String adminParam = request.getParameter("admin");

    if (userId != null) {
      changedEmployee = InternalStaffDao.getInternalAuthorByStaffId(Integer.parseInt(userId));
      System.out.println(changedEmployee.getEmployee().getName());
      session.removeAttribute("user");
      session.setAttribute("user", changedEmployee);
      response.sendRedirect("Home.jsp");

    } else if (adminParam != null && adminParam.equals("yes")) {
      session.removeAttribute("user");
      admin = InternalStaffDao.getAdmin();
      session.setAttribute("user", admin);
      response.sendRedirect("Home.jsp");

    } else if (employee != null) {
      response.sendRedirect("Home.jsp");
    } else response.sendRedirect("login.jsp");
  }
Пример #9
0
 /**
  * Sets the preferred locale for the specified session. It is the default locale for the whole Web
  * session.
  *
  * <p>Default: null (no preferred locale -- depending on browser's setting).
  *
  * @param locale the preferred Locale. If null, it means no preferred locale
  * @see #getPreferredLocale(HttpSession,ServletRequest)
  * @since 3.6.3
  */
 public static final void setPreferredLocale(HttpSession hsess, Locale locale) {
   if (locale != null) {
     hsess.setAttribute(Attributes.PREFERRED_LOCALE, locale);
   } else {
     hsess.removeAttribute(Attributes.PREFERRED_LOCALE);
     hsess.removeAttribute(PX_PREFERRED_LOCALE);
   }
 }
 @Override
 public void removeSessionParams(HttpSession session) {
   session.removeAttribute(ATTRIBUTE_NAME_SESSION_PARAM);
   session.removeAttribute(LINK_LANG_CODE_SESSION_PARAM);
   session.removeAttribute(LIST_ELEMENT_INDEX_SESSION_PARAM);
   session.removeAttribute(INCLUDED_ELEMENT_NAME_SESSION_PARAM);
   session.removeAttribute(SYMBOLIC_LINK_SESSION_PARAM);
 }
Пример #11
0
 @RequestMapping("/logout")
 public String logout() {
   HttpSession session = getSession(false);
   if (session != null) {
     session.removeAttribute(Constants.LOGIN_INFO);
     session.removeAttribute(Constants.CAR_INFO);
   }
   return "redirect:/welcome";
 }
Пример #12
0
 @PUT
 @Path("logout")
 public void appLogout() {
   HttpSession session = getSession(false);
   if (session != null) {
     session.removeAttribute(Constants.LOGIN_INFO);
     session.removeAttribute(Constants.CAR_INFO);
   }
 }
  public String logoutTwitter() {
    HttpServletRequest request = this.getThreadLocalRequest();
    HttpSession session = super.getThreadLocalRequest().getSession();
    session.removeAttribute("requestToken");
    session.removeAttribute("accessToken");

    String baseUrl = getBaseUrl(request);
    return (baseUrl);
  }
  /** {@inheritDoc} */
  @Override
  public ActionForward execute(
      @SuppressWarnings("unused") ComponentContext context,
      @SuppressWarnings("unused") ActionMapping mapping,
      @SuppressWarnings("unused") ActionForm form,
      HttpServletRequest request,
      @SuppressWarnings("unused") HttpServletResponse response)
      throws Exception {
    HttpSession session = request.getSession();

    Profile profile = SessionMethods.getProfile(session);
    PathQuery query = SessionMethods.getQuery(session);
    DisplayConstraintFactory factory = getFactory(session);

    if (session.getAttribute("newConstraintPath") != null) {
      // ADDING A NEW CONSTRAINT
      DisplayPath displayPath = (DisplayPath) session.getAttribute("newConstraintPath");
      DisplayConstraint displayConstraint = factory.get(displayPath.getPath(), profile, query);
      request.setAttribute("dec", displayConstraint);
      session.removeAttribute("newConstraintPath");
      saveToken(request);
    } else if (session.getAttribute("editingConstraint") != null) {
      // EDITING AN EXISTING CONSTRAINT
      PathConstraint con = (PathConstraint) session.getAttribute("editingConstraint");
      DisplayConstraint displayConstraint;
      if (query instanceof TemplateQuery) {
        TemplateQuery template = (TemplateQuery) query;
        displayConstraint = factory.get(con, profile, template);
      } else {
        displayConstraint = factory.get(con, profile, query);
      }

      request.setAttribute("dec", displayConstraint);
      session.removeAttribute("editingConstraint");
      if (session.getAttribute("editingTemplateConstraint") != null) {
        SessionMethods.moveToRequest("editingTemplateConstraint", request);
      }
      saveToken(request);
    } else if (session.getAttribute("joinStylePath") != null) {
      // ONLY EDITING JOIN STYLE
      String joinStylePathStr = (String) session.getAttribute("joinStylePath");
      Path joinStylePath = query.makePath(joinStylePathStr);
      DisplayConstraint displayConstraint = factory.get(joinStylePath, profile, query);
      session.removeAttribute("joinStylePath");

      if (query.getOuterMap().containsKey(joinStylePathStr)) {
        request.setAttribute("joinType", "outer");
      } else {
        request.setAttribute("joinType", "inner");
      }
      request.setAttribute("dec", displayConstraint);
      request.setAttribute("joinStyleOnly", "true");
      saveToken(request);
    }

    return null;
  }
Пример #15
0
  @SuppressWarnings("unchecked")
  @ResponseBody
  @RequestMapping(value = "/order/updateItemQuantity.ajax", method = RequestMethod.POST)
  public ResponseEntity<byte[]> updateItemQuantity(
      HttpServletRequest request, @RequestParam(value = "body") String body) throws Exception {

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Updating order items: " + body);
    }

    Map<String, Object> model = new HashMap<String, Object>();

    try {
      // Extract request parameters
      Map<String, Object> params = (Map<String, Object>) jsonUtils.deserialize(body);
      String orderItemId = (String) params.get("orderItemId");
      Integer quantity = (Integer) params.get("quantity");

      HttpSession session = request.getSession(true);
      String orderId = (String) session.getAttribute("orderid");
      Order order = null;
      if (orderId != null) {
        order = orderRepository.findByOrderId(orderId);
        if (order != null) {
          order.updateItemQuantity(orderItemId, quantity);
          order = orderRepository.saveOrder(order);
          // Update can checkout status of order
          session.setAttribute("cancheckout", order.getCanCheckout());

          // Update order restaurant id session attribute if any items present
          if (order.getOrderItems().size() > 0) {
            session.setAttribute("orderrestaurantid", order.getRestaurantId());
            session.setAttribute("orderrestauranturl", order.getRestaurant().getUrl());
          } else {
            // If the restaurant session id does not match the order restaurant id, update the order
            String restaurantId = (String) session.getAttribute("restaurantid");
            if (!order.getRestaurantId().equals(restaurantId)) {
              Restaurant restaurant = restaurantRepository.findByRestaurantId(restaurantId);
              order.setRestaurant(restaurant);
              order = orderRepository.save(order);
            }
            session.removeAttribute("orderrestaurantid");
            session.removeAttribute("orderrestauranturl");
          }
        }
      }
      model.put("success", true);
      model.put("order", order);
    } catch (Exception ex) {
      LOGGER.error("", ex);
      model.put("success", false);
      model.put("message", ex.getMessage());
    }
    return buildOrderResponse(model);
  }
Пример #16
0
 public ActionForward cancel(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response) {
   HttpSession session = request.getSession(false);
   session.removeAttribute("AssessPaperList");
   session.removeAttribute("AssessPaperTotal");
   session.removeAttribute("AssessPaperAvg");
   return mapping.findForward("back");
 }
 public void logout(
     HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
   if (this.supportSSO) {
     CookieUtil.deleteCookie(request, response, "jforumUserInfo");
   }
   HttpSession session = request.getSession(false);
   if (session != null) {
     session.removeAttribute("SPRING_SECURITY_LAST_USERNAME");
     session.removeAttribute("SPRING_SECURITY_CONTEXT");
   }
   super.logout(request, response, authentication);
 }
Пример #18
0
  @SuppressWarnings("unchecked")
  @ResponseBody
  @RequestMapping(value = "/order/updateFreeItem.ajax", method = RequestMethod.POST)
  public ResponseEntity<byte[]> updateFreeItem(
      HttpServletRequest request, @RequestParam(value = "body") String body) throws Exception {

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Updating free item: " + body);
    }

    Map<String, Object> model = new HashMap<String, Object>();

    try {
      // Extract request parameters
      Map<String, Object> params = (Map<String, Object>) jsonUtils.deserialize(body);
      String discountId = (String) params.get("discountId");
      String freeItem = (String) params.get("freeItem");

      HttpSession session = request.getSession(true);
      String orderId = (String) session.getAttribute("orderid");
      Order order = null;
      if (orderId != null) {
        order = orderRepository.findByOrderId(orderId);
        if (order != null) {
          OrderDiscount orderDiscount = order.getOrderDiscount(discountId);
          if (orderDiscount != null) {
            orderDiscount.setSelectedFreeItem(freeItem);
            order = orderRepository.save(order);
          }

          // Update order restaurant id session attribute if any items present
          if (order.getOrderItems().size() > 0) {
            session.setAttribute("orderrestaurantid", order.getRestaurantId());
            session.setAttribute("orderrestauranturl", order.getRestaurant().getUrl());
          } else {
            session.removeAttribute("orderrestaurantid");
            session.removeAttribute("orderrestauranturl");
          }

          // Update can checkout status of order
          session.setAttribute("cancheckout", order.getCanCheckout());
        }
      }

      model.put("success", true);
      model.put("order", order);
    } catch (Exception ex) {
      LOGGER.error("", ex);
      model.put("success", false);
      model.put("message", ex.getMessage());
    }
    return buildOrderResponse(model);
  }
 /**
  * Check that the expiration date was not reached. If it is the case, it discard the previously
  * set access_token and expiration date from session
  *
  * @param session the current user http session
  */
 public static void checkExpirationDate(HttpSession session) {
   DateTime now = new DateTime();
   DateTime expirationDate = (DateTime) session.getAttribute("expiration_date");
   LOG.debug("Checking for access token expiration, now = {}, expires = {}", now, expirationDate);
   // Expiration date reached
   if (now.isAfter(expirationDate)) {
     LOG.info("Expiration date reached, remove access token from session");
     session.removeAttribute("access_token");
     session.removeAttribute("expiration_date");
     session.removeAttribute("state");
   }
 }
Пример #20
0
 /**
  * 清空缓存
  *
  * @param session
  */
 public static void clearAllSession(HttpSession session) {
   String temp = "";
   String sessionId = session.getId();
   Enumeration<String> sessionKeys = session.getAttributeNames();
   for (Enumeration<String> e = sessionKeys; e.hasMoreElements(); ) {
     temp = e.nextElement().toString();
     if (temp.startsWith(sessionId)) {
       session.removeAttribute(temp);
     }
   }
   session.removeAttribute("userName");
 }
Пример #21
0
 static void destroySession(HttpSession session) {
   ServletContext context = session.getServletContext();
   String user = (String) session.getAttribute(ATTRIBUTE_SESSIONUSER);
   if (user != null) {
     String current = (String) session.getAttribute(ATTRIBUTE_SESSIONMATCH);
     String match = (String) context.getAttribute(ATTRIBUTE_SESSIONMATCH + "." + user);
     if (current != null && current.equals(match)) {
       context.removeAttribute(ATTRIBUTE_SESSIONMATCH + "." + user);
     }
   }
   session.removeAttribute(ATTRIBUTE_SESSIONUSER);
   session.removeAttribute(ATTRIBUTE_SESSIONMATCH);
 }
Пример #22
0
  @SuppressWarnings("unchecked")
  @RequestMapping(value = "/realizarVotacion", method = RequestMethod.POST) // voto.jsp
  @Transactional
  public String realizarVotacion(
      Model model,
      HttpSession session,
      HttpServletResponse response,
      @RequestParam("comentario") String comentario,
      @RequestParam("csrf") String token) {

    if (!isTokenValid(session, token)) response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

    model.addAttribute("prefix", "./");
    long idEmisor = ((Usuario) session.getAttribute("user")).getId();
    long idUsuarioVotacion = Long.parseLong((String) session.getAttribute("usuarioVotacion"));
    ArrayList<Categoria> lista = new ArrayList<Categoria>();
    lista = (ArrayList<Categoria>) session.getAttribute("valoraciones");
    Votacion v = new Votacion();
    v = v.crearVotacion(idEmisor, idUsuarioVotacion, lista, comentario);
    entityManager.persist(v);

    // Recalcular las puntuaciones
    Usuario u = null;
    u =
        (Usuario)
            entityManager
                .createNamedQuery("busquedaUsuarioId")
                .setParameter(
                    "param1", Long.parseLong((String) session.getAttribute("usuarioVotacion")))
                .getSingleResult();
    u.setPuntuacion(
        (Double)
            entityManager
                .createNamedQuery("puntuacionMedia")
                .setParameter(
                    "param1", Long.parseLong((String) session.getAttribute("usuarioVotacion")))
                .getSingleResult());
    entityManager.persist(u);

    // String subconsulta = ("SELECT AVG(V.PUNTUACION) FROM VOTACION WHERE
    // ID_RECEPTOR="+idUsuarioVotacion);
    // String query = "UPDATE USUARIO SET PUNTUACION_MEDIA=(" + subconsulta + ") WHERE ID="
    // +idUsuarioVotacion;
    // Integer puntuacion = (Integer) entityManager.createNativeQuery(query).getFirstResult();
    // u.setPuntuacion(puntuacion);
    // entityManager.createNativeQuery(subconsulta).executeUpdate();

    session.removeAttribute("valoraciones");
    session.removeAttribute("usuarioVotacion");
    return "home";
  }
  /**
   * @param actionMapping
   * @param actionForm
   * @param httpServletRequest
   * @param httpServletResponse
   * @return
   */
  public ActionForward execute(
      ActionMapping actionMapping,
      ActionForm actionForm,
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse) {

    // Seta o mapeamento de retorno para a tela de sucesso
    ActionForward retorno = actionMapping.findForward("telaSucesso");

    // Cria uma instância da sessão
    HttpSession sessao = httpServletRequest.getSession(false);

    MovimentarOSSeletivaInspecaoAnormalidadeActionForm form =
        (MovimentarOSSeletivaInspecaoAnormalidadeActionForm) actionForm;

    if (httpServletRequest.getAttribute("tipoMovimentacao") != null
        && !httpServletRequest.getAttribute("tipoMovimentacao").equals("")) {
      // Monta página de sucesso
      montarPaginaSucesso(
          httpServletRequest,
          "Ordem(ns) de Serviço "
              + httpServletRequest.getAttribute("tipoMovimentacao")
              + " com sucesso!",
          "Voltar",
          "exibirMovimentarOSSeletivaInspecaoAnormalidadeAction.do?comando=" + form.getIdComando());

      //    	} else if
      // (httpServletRequest.getAttribute("gerarRelatorioEmitirDocumentoVisitaCobranca") != null
      //    			&&
      // !httpServletRequest.getAttribute("gerarRelatorioEmitirDocumentoVisitaCobranca").equals(""))
      // {
      //
      //			return actionMapping.findForward("gerarRelatorioEmitirDocumentoVisitaCobranca");

    } else {
      // Monta página de sucesso
      montarPaginaSucesso(
          httpServletRequest,
          "Ordem de Serviço movimentada com sucesso!",
          "Voltar",
          "exibirMovimentarOSSeletivaInspecaoAnormalidadeAction.do?comando=" + form.getIdComando());
    }

    // Limpa a sessão depois de inserir os dados
    sessao.removeAttribute("grupo");
    sessao.removeAttribute("grupoFuncionalidades");

    // Retorna o mapeamento contido na variável "retorno"
    return retorno;
  }
Пример #24
0
 public static void setTour(HttpSession session, int tour) {
   if (SessionManager.isOnTour(session) && tour == 0) {
     System.out.println("*** Info, closing site tour");
     session.setAttribute("onTour", false);
     session.removeAttribute("tourStep");
     session.removeAttribute("tourQuery");
   } else if (!SessionManager.isOnTour(session) && tour > 0) {
     session.setAttribute("onTour", true);
     session.setAttribute("tourStep", 0);
   }
   if (SessionManager.isOnTour(session) && tour != (int) session.getAttribute("tourStep")) {
     session.setAttribute("tourStep", tour);
   }
 }
Пример #25
0
 /**
  * 注销登录时调用的方法
  *
  * @author 秦建华
  * @version 1.0 2008.7.10
  * @throws Exception
  */
 public ModelAndView logout(HttpServletRequest request, HttpServletResponse response, Object obj)
     throws Exception {
   HttpSession session = request.getSession();
   // session.removeAttribute("IAppTree");
   session.removeAttribute("UserBean");
   session.removeAttribute("reportTime");
   session.invalidate();
   List curRptTimelst = indexService.getCurrentReportTimes();
   List hisRptTimelst = indexService.getHistoryReportTimes();
   HashMap map = new HashMap();
   map.put("curRptTimelst", curRptTimelst);
   map.put("hisRptTimelst", hisRptTimelst);
   return new ModelAndView(this.getIndex(), map);
 }
Пример #26
0
 // 退出
 public String out() {
   HttpSession session = getHttpSession();
   user = (Users) session.getAttribute("loginAdmin");
   if (user != null) {
     OperLogUtil.log(user.getLoginname(), "退出系统", getHttpRequest());
   }
   session.removeAttribute("loginAdmin");
   session.removeAttribute("manageSite");
   session.removeAttribute("siteAdmin");
   session.removeAttribute("loginUnits");
   session.removeAttribute("loginRoles");
   session.removeAttribute("funcs");
   return "login";
 }
Пример #27
0
 @Override
 protected String buildLoginRedirectURL(HttpServletRequest request) {
   HttpSession session = request.getSession(false);
   if (session != null && session.getAttribute(REDIRECT_URI) != null) {
     String redirectUrl =
         session.getAttribute(REDIRECT_URI)
             + (session.getAttribute(REDIRECT_QUERY) != null
                 ? ("?" + session.getAttribute(REDIRECT_QUERY))
                 : "");
     session.removeAttribute(REDIRECT_URI);
     session.removeAttribute(REDIRECT_QUERY);
     return redirectUrl;
   }
   return super.buildLoginRedirectURL(request);
 }
Пример #28
0
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    int quantity = 0, idItem = 0, stock = 0, price = 0, type = 0;
    String desc = "";

    type = Integer.parseInt(request.getParameter("type"));
    HttpSession session = request.getSession();

    if (type == 1) {
      quantity = Integer.parseInt(request.getParameter("quantity"));
      idItem = Integer.parseInt(request.getParameter("id"));
      desc = request.getParameter("desc");
      stock = Integer.parseInt(request.getParameter("stock"));
      price = Integer.parseInt(request.getParameter("price"));

      if (stock < quantity) {
        // fail
        out.println(-1);
      } else {
        try {
          ShoppingCart sc = new ShoppingCart();
          if (session.getAttribute("shoppingCart") != null)
            sc = (ShoppingCart) session.getAttribute("shoppingCart");
          sc.getItems().add(new Item(quantity, idItem, price, desc));
          if (session.getAttribute("shoppingCart") != null) session.removeAttribute("shoppingCart");
          session.setAttribute("shoppingCart", sc);
          out.println(1);
        } catch (Exception x) {
          out.println(0);
        }
      }
    } else if (type == 2) {
      ShoppingCart sc = new ShoppingCart();
      idItem = Integer.parseInt(request.getParameter("id"));
      if (session.getAttribute("shoppingCart") != null) {
        sc = (ShoppingCart) session.getAttribute("shoppingCart");
        sc.getItems().remove(idItem);
        if (session.getAttribute("shoppingCart") != null) session.removeAttribute("shoppingCart");
        session.setAttribute("shoppingCart", sc);
        out.println(idItem);
      } else out.println(-1);
    }
  }
 /**
  * Questo controller si incarica di caricare in sessione, quando possibile, la configurazione
  * personalizzata dell'utente correntemente loggato. NOTA: la sessione viene esplicitamente
  * ripulita da qualsiasi configurazione personalizzata non allineata all'utente corrente
  */
 @Override
 public int service(RequestContext reqCtx, int status) {
   if (_log.isLoggable(Level.FINEST)) {
     _log.finest("Invocata " + this.getClass().getName());
   }
   int retStatus = ControllerManager.INVALID_STATUS;
   if (status == ControllerManager.ERROR) {
     return status;
   }
   try {
     HttpServletRequest req = reqCtx.getRequest();
     HttpSession session = req.getSession();
     UserDetails currentUser =
         (UserDetails) session.getAttribute(SystemConstants.SESSIONPARAM_CURRENT_USER);
     if (null == currentUser) {
       throw new ApsSystemException("no user on session");
     }
     PageModelUserConfigBean userConfigBean =
         (PageModelUserConfigBean)
             session.getAttribute(
                 JpmyportalSystemConstants.SESSIONPARAM_CURRENT_USER_PAGE_MODEL_CONFIG);
     if (!currentUser.getUsername().equals(SystemConstants.GUEST_USER_NAME)
         && !currentUser.getUsername().equals(SystemConstants.ADMIN_USER_NAME)) {
       if ((null == userConfigBean
           || !currentUser.getUsername().equals(userConfigBean.getUsername()))) {
         userConfigBean =
             this.getPageModelUserConfigManager().getUserConfig(currentUser.getUsername());
         if (null != userConfigBean) {
           session.setAttribute(
               JpmyportalSystemConstants.SESSIONPARAM_CURRENT_USER_PAGE_MODEL_CONFIG,
               userConfigBean);
         } else {
           session.removeAttribute(
               JpmyportalSystemConstants.SESSIONPARAM_CURRENT_USER_PAGE_MODEL_CONFIG);
         }
       }
     } else {
       session.removeAttribute(
           JpmyportalSystemConstants.SESSIONPARAM_CURRENT_USER_PAGE_MODEL_CONFIG);
     }
     retStatus = ControllerManager.CONTINUE;
   } catch (Throwable t) {
     ApsSystemUtils.logThrowable(t, this, "service", "Error while processing the request");
     retStatus = ControllerManager.SYS_ERROR;
     reqCtx.setHTTPError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
   }
   return retStatus;
 }
Пример #30
0
  /** 头部栏目 */
  @RequestMapping(value = "/headbar", method = RequestMethod.GET)
  public String headbar(HttpServletRequest request, HttpSession session, Model model) {

    String backurl = request.getParameter("backurl");
    //        System.out.println(backurl);

    Subject subject = SecurityUtils.getSubject();
    // 已登陆则 获取信息
    if (subject.isAuthenticated()) {

      String username = String.valueOf(subject.getPrincipal());
      //            System.out.println("登录用户"+username);

      List<Role> roleInfos = roleService.selectRolesByUsername(username);
      //            request.getSession().setAttribute("roleInfos", roleInfos);

      String ticket = UUID.randomUUID().toString();
      cache.set(ticket, gson.toJson(roleInfos), 60);
      //            System.out.println(ticket);
      //            logger.info(ticket);
      //            logger.info(cache.get(ticket));
      model.addAttribute("ticket", ticket);

    } else {
      session.removeAttribute("userInfo");
      //            System.out.println("未登录");
    }

    model.addAttribute("backurl", (backurl == null || "".equals(backurl)) ? successUrl : backurl);

    return "authmanager/headbar";
  }