@Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String token = request.getParameter("tk");
    String email = request.getParameter("email");

    if (token != null && !token.isEmpty() && email != null && !email.isEmpty()) {
      SolicitacaoRecuperacaoSenha solicitacaoRecuperacaoSenha =
          solicitacaoRecuperacaoSenhaBO.getSolicitacaoRecuperacaoSenha(token, email);
      if (solicitacaoRecuperacaoSenha != null) {
        // criar faces-context (no servlet o faces context nao existe e esse metodo forca sua
        // criacao)
        FacesContext context = FacesUtils.getFacesContext(request, response);
        Object object =
            context
                .getApplication()
                .evaluateExpressionGet(context, "#{sessaoUsuarioMB}", Object.class);
        if (object != null && object instanceof SessaoUsuarioMB) {
          SessaoUsuarioMB sessaoUsuarioMB = (SessaoUsuarioMB) object;
          sessaoUsuarioMB.setUser(null);
          sessaoUsuarioMB.setSolicitacaoRecuperacaoSenha(solicitacaoRecuperacaoSenha);
          response.sendRedirect(request.getContextPath() + "/cadastroNovaSenha.jsf");
          return;
        }
      }
    }

    response.sendRedirect(request.getContextPath());
  }
Пример #2
0
  protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, SQLException, AuthorizeException {
    Integer itemID = UIUtil.getIntParameter(request, "itemID");
    Item item = Item.find(context, itemID);
    String submit = UIUtil.getSubmitButton(request, "submit");
    if (submit != null && submit.equals("submit")) {
      request.setAttribute("itemID", itemID);
      JSPManager.showJSP(request, response, "/tools/version-summary.jsp");
      return;
    }

    String summary = request.getParameter("summary");
    if (submit != null && submit.equals("submit_version")) {
      Integer wsid = VersionUtil.processCreateNewVersion(context, itemID, summary);
      response.sendRedirect(request.getContextPath() + "/submit?resume=" + wsid);
      context.complete();
      return;
    } else if (submit != null && submit.equals("submit_update_version")) {
      String versionID = request.getParameter("versionID");
      request.setAttribute("itemID", itemID);
      request.setAttribute("versionID", versionID);
      JSPManager.showJSP(request, response, "/tools/version-update-summary.jsp");
      return;
    }

    // Send us back to the item page if we cancel !
    response.sendRedirect(request.getContextPath() + "/handle/" + item.getHandle());
    context.complete();
  }
Пример #3
0
 private void process(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String login = request.getParameter("login");
   String password = request.getParameter("password");
   if (login != null && password != null) {
     UserService service = null;
     try {
       service = new UserService();
       User user = service.findByLoginAndPassword(login, password);
       if (user != null) {
         HttpSession session = request.getSession();
         session.setAttribute("currentUser", user);
         response.sendRedirect(request.getContextPath());
       } else {
         response.sendRedirect(
             request.getContextPath()
                 + "/login.html?message="
                 + URLEncoder.encode("Имя пользователя или пароль неопознанны", "UTF-8"));
       }
     } catch (SQLException e) {
       throw new ServletException(e);
     } finally {
       if (service != null) {
         service.close();
       }
     }
   } else {
     getServletContext().getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
   }
 }
  @Override
  public boolean preHandle(
      HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o)
      throws Exception {
    HttpSession session = httpServletRequest.getSession();
    User user = (User) session.getAttribute("user");
    if (user == null || user.getStatus() != UserConstant.Status.ACTIVE.value()) {
      return false;
    }

    Map<Privilege, Integer> map = PrivilegeHelper.getPrivilegeMap();

    Privilege privilege =
        new Privilege(
            httpServletRequest
                .getRequestURI()
                .substring(httpServletRequest.getContextPath().length()),
            httpServletRequest.getMethod());
    System.out.println("privilege = " + privilege);

    if (CollectionUtils.isEmpty(user.getPrivilegeIds())) {
      httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/error/low.html");
      return false;
    }

    if (MapUtils.isNotEmpty(map)
        && map.containsKey(privilege)
        && !user.getPrivilegeIds().contains(map.get(privilege))) {
      httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/error/low.html");
      return false;
    }

    return true;
  }
Пример #5
0
  @RequestMapping
  public @ResponseBody String dispatch(HttpServletRequest request) throws Exception {
    String path = request.getRequestURI();
    if (path.indexOf(request.getContextPath()) > -1) {
      path = path.substring(request.getContextPath().length());
    }
    List<Service> services = serviceRepository.findAll();
    for (Service service : services) {
      if (service.getUrl().matches(path)) {
        System.out.println("MATCH: " + service.getUrl());
        SoapService soap = new SoapService();
        soap.setBody(request.getInputStream());
        System.out.println(soap.dispatch());
      }
    }
    System.out.println("PATH " + request.getServletPath());
    System.out.println("QUERY " + request.getQueryString());
    System.out.println("URL " + request.getRequestURL());

    System.out.println("CONTEXT " + request.getContextPath());
    System.out.println("URI " + request.getRequestURI());

    System.out.println(serviceRepository.count());

    return "RESPONSE: " + request;
  }
Пример #6
0
 /**
  * Prepare a search helper with all required information, ready to execute the query implied by
  * the related request parameters and cookies.
  *
  * <p>NOTE: One should check the {@link SearchHelper#errorMsg} as well as {@link
  * SearchHelper#redirect} and take the appropriate action before executing the prepared query or
  * continue processing.
  *
  * <p>This method stops populating fields as soon as an error occurs.
  *
  * @return a search helper.
  */
 public SearchHelper prepareSearch() {
   SearchHelper sh = new SearchHelper();
   sh.dataRoot = getDataRoot(); // throws Exception if none-existent
   List<SortOrder> sortOrders = getSortOrder();
   sh.order = sortOrders.isEmpty() ? SortOrder.RELEVANCY : sortOrders.get(0);
   if (getRequestedProjects().isEmpty() && getEnv().hasProjects()) {
     sh.errorMsg = "You must select a project!";
     return sh;
   }
   sh.builder = getQueryBuilder();
   if (sh.builder.getSize() == 0) {
     // Entry page show the map
     sh.redirect = req.getContextPath() + '/';
     return sh;
   }
   sh.start = getSearchStart();
   sh.maxItems = getSearchMaxItems();
   sh.contextPath = req.getContextPath();
   // jel: this should be IMHO a config param since not only core dependend
   sh.parallel = Runtime.getRuntime().availableProcessors() > 1;
   sh.isCrossRefSearch = getPrefix() == Prefix.SEARCH_R;
   sh.compressed = env.isCompressXref();
   sh.desc = getEftarReader();
   sh.sourceRoot = new File(getSourceRootPath());
   sh.lastEditedDisplayMode = isLastEditedDisplayMode();
   return sh;
 }
  /**
   * Handles the HTTP <code>POST</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // processRequest(request, response);
    String username = request.getParameter("usrname");
    String password = request.getParameter("pw");
    HttpSession session = request.getSession(true);
    session.setAttribute("Sessionusername", username);
    session.setAttribute("Sessionpassword", password);

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet LoginSessionServlet</title>");
      out.println("</head>");
      out.println("<body>");
      out.println("<h1>Servlet LoginSessionServlet at " + request.getContextPath() + "</h1>");
      out.println(
          "<a href=\""
              + request.getContextPath()
              + "/CheckSessionServlet\">Check the session page</a>");
      out.println("</body>");
      out.println("</html>");
    } finally {
      out.close();
    }
  }
Пример #8
0
  /**
   * 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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet TestServlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>");
    Client client = ClientBuilder.newClient();
    client.register(MyReader.class).register(MyWriter.class);

    WebTarget target =
        client.target(
            "http://"
                + request.getServerName()
                + ":"
                + request.getServerPort()
                + request.getContextPath()
                + "/webresources/endpoint");
    System.out.println("POST request");
    MyObject mo =
        target
            .request()
            .post(
                Entity.entity(new MyObject("Duke", 18), MediaType.APPLICATION_JSON),
                MyObject.class);
    out.println("Received response: " + mo.getName() + ", " + mo.getAge() + "<br><br>");

    out.println("Check server.log for client/server interceptor output.");
    out.println("</body>");
    out.println("</html>");
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    System.out.println(req);
    Integer id = Integer.parseInt(req.getParameter("id").trim());
    if (id != 0) {
      Connection con = (Connection) getServletContext().getAttribute("DBConnection");
      PositionTable positionTable = new PositionTable(con);
      Position position;
      position = positionTable.getPositionById(id);
      if (position.getId() != null) {
        req.setAttribute("positionName", position.getName());
        req.setAttribute("positionId", position.getId());
        req.setAttribute("actionUrl", req.getContextPath() + "/positions/edit/?id=" + id);
        req.setAttribute("minSalary", position.getMinSalary());
        req.setAttribute("maxSalary", position.getMaxSalary());
        getServletContext().getRequestDispatcher("/positions/add.jsp").forward(req, resp);
      } else {

      }

    } else {
      resp.setStatus(resp.SC_MOVED_TEMPORARILY);
      resp.setHeader("Location", req.getContextPath() + "/positions");
    }
  }
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String idParam = (String) request.getParameter(ATT_ID);
   int id = -1;
   boolean ok = true;
   if (idParam == null || idParam.isEmpty()) {
     response.sendRedirect(request.getContextPath() + SERVLET_MNG_CATEGORIES);
   } else {
     try {
       id = Integer.parseInt(idParam);
     } catch (Exception e) {
       ok = false;
       e.printStackTrace();
     }
     if (!ok) {
       response.sendRedirect(request.getContextPath() + SERVLET_MNG_CATEGORIES);
     } else {
       Category category = DAOCategory.getInstance().find(id);
       if (category != null) {
         DAOCategory.getInstance().delete(category);
         response.sendRedirect(request.getContextPath() + SERVLET_MNG_CATEGORIES);
       } else {
         response.sendRedirect(request.getContextPath() + SERVLET_MNG_CATEGORIES);
       }
     }
   }
 }
Пример #11
0
 /**
  * 首页登录中添加记住我的功能
  *
  * @param request
  * @param response
  * @throws UnsupportedEncodingException
  */
 public static void remeberMeByCookie(HttpServletRequest request, HttpServletResponse response)
     throws UnsupportedEncodingException {
   // 获取登录名和密码
   String logonName = request.getParameter("name");
   String pwd = request.getParameter("password");
   // 处理cookie中存在中文字符的问题
   String codeName = URLEncoder.encode(logonName, "UTF-8");
   String codePwd = URLEncoder.encode(pwd, "UTF-8");
   // 创建cookie
   Cookie nameCookie = new Cookie("name", codeName);
   Cookie pwdCookie = new Cookie("password", codePwd);
   // 设置cookie有效路径
   nameCookie.setPath(request.getContextPath() + "/");
   pwdCookie.setPath(request.getContextPath() + "/");
   // 是否选中记住我
   if (request.getParameter("remeberMe") != null
       && "yes".equals(request.getParameter("remeberMe"))) {
     // 设置cookie有效时长
     nameCookie.setMaxAge(7 * 24 * 60 * 60);
     pwdCookie.setMaxAge(7 * 24 * 60 * 60);
   } else {
     // 清空cookie有效时长
     pwdCookie.setMaxAge(0);
     nameCookie.setMaxAge(0);
   }
   // 将cookie存放到response中
   response.addCookie(nameCookie);
   response.addCookie(pwdCookie);
 }
Пример #12
0
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest hreq = (HttpServletRequest) request;
    String ctx = hreq.getContextPath();
    System.out.println("==ctx==" + ctx);
    String urlwrong = ctx + "/login/toAjaxLogin.do";

    HttpServletResponse hres = (HttpServletResponse) response;
    HttpSession session = hreq.getSession();

    // 首先要有登录,其次要有权限,权限过滤要进行请求区别,如果是ajax则提示无权限,或者直接跳到登录界面
    if (session != null && session.getAttribute(KeyWords.USER_INFO) != null) {
      log.info("session is exist");
      // 这里写权限过滤逻辑
      // authority filter logic
      Map<String, Map> authorities = (Map<String, Map>) session.getAttribute(KeyWords.USER_AUTH);
      String url = hreq.getRequestURL().toString();
      url =
          url.substring(
              url.indexOf(hreq.getContextPath()) + hreq.getContextPath().length(), url.length());
      if (!authorities.containsKey(url)) {
        hres.sendRedirect(urlwrong); // 重定向到该url
        return;
      }
    }
    chain.doFilter(request, response);
  }
  @RequestMapping(value = "/createprocedure", method = RequestMethod.GET)
  public String createProcedure(
      Model model, HttpServletResponse response, HttpServletRequest request, HttpSession session)
      throws Exception {

    if (session.getAttribute("user_key") == null) {
      logger.debug("user_key is null new Login required");
      response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
      return null;
    } else {
      Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
      if (conn == null) {
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
      } else {
        if (conn.isClosed()) {
          response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
          return null;
        }
      }
    }

    logger.debug("Received request to create a new Procedure");

    session.setAttribute("numParams", "0");
    model.addAttribute("numParams", "0");
    model.addAttribute("procedureAttribute", new NewProcedure());

    // This will resolve to /WEB-INF/jsp/create-procedure.jsp
    return "create-procedure";
  }
Пример #14
0
  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {
    /* Cast des objets request et response */
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    /* Récupération de la session depuis la requête */
    HttpSession session = request.getSession();

    /**
     * Si l'objet utilisateur n'existe pas dans la session en cours, alors l'utilisateur n'est pas
     * connecté.
     */
    if (session.getAttribute(SESSION_USER) == null) {
      System.out.println("La session est : " + session.getAttribute(SESSION_USER));
      /* Redirection vers la page publique */
      response.sendRedirect(request.getContextPath() + ACCES_CONNEXION);
    } else if (!SESSION_PROFIL.equals((String) session.getAttribute(SESSION_PROFIL))) {
      /* Redirection vers la page publique */
      response.sendRedirect(request.getContextPath() + ACCES_PUBLIC);
    } else {
      System.out.println("La session est : " + session.getAttribute(SESSION_USER));
      /* Affichage de la page restreinte */
      chain.doFilter(request, response);
    }
  }
  @ModelAttribute
  public void frontUrl(ModelMap model, HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    // model.addAttribute("frontUrl", request.getContextPath() + "/resources");
    userLoad(model);
    model.addAttribute("frontUrl", request.getContextPath() + "/resources");
    // System.out.println("xDamsController.frontUrl() multiAccount: " + multiAccount);
    // System.out.println("xDamsController.frontUrl() model.get(\"userBean\"): " +
    // model.get("userBean"));
    if (multiAccount && model.get("userBean") != null) {
      model.addAttribute(
          "frontUrl",
          request.getContextPath()
              + "/resources/"
              + ((UserBean) model.get("userBean")).getAccountRef());
    }

    // System.out.println("xDamsController.frontUrl() model.get(\"frontUrl\"): " +
    // model.get("frontUrl"));
    model.addAttribute("contextPath", request.getContextPath());
    String userAgent = ((HttpServletRequest) request).getHeader("User-Agent");
    if (userAgent.toLowerCase().contains("msie")) {
      response.addHeader("X-UA-Compatible", "IE=edge");
    }

    try {
      Locale locale = RequestContextUtils.getLocale(request);
      ((UserBean) model.get("userBean")).setLanguage(locale.getLanguage());
    } catch (Exception e) {
      // TODO: handle exception
    }
    model.put("realPath", WebUtils.getRealPath(servletContext, ""));
  }
  void redirectToPrimarilyRequestedUrl(
      FilterChain chain,
      HttpServletRequest httpRequest,
      HttpServletResponse httpResponse,
      ServiceAccess serviceAccess,
      AuthorizationRequestData rdo)
      throws IOException, ServletException {

    String forwardUrl =
        (String) httpRequest.getSession().getAttribute(Constants.SESS_ATTR_FORWARD_URL);

    if (BesServletRequestReader.onlyServiceLogin(httpRequest.getSession())) {
      if (forwardUrl == null) {
        forwardUrl = Constants.SERVICE_BASE_URI + "/" + rdo.getSubscriptionKey() + "/";
      }
      JSFUtils.sendRedirect(httpResponse, httpRequest.getContextPath() + forwardUrl);
      return;
    }

    if (ADMStringUtils.isBlank(forwardUrl) || forwardUrl.startsWith(MenuBean.LINK_DEFAULT)) {
      forwardUrl = getDefaultUrl(serviceAccess, rdo, httpRequest);
    }

    if ((ADMStringUtils.isBlank(forwardUrl) || rdo.getRelativePath().startsWith(forwardUrl))
        && !rdo.isMarketplaceLoginPage()) {
      chain.doFilter(httpRequest, httpResponse);
    } else {
      JSFUtils.sendRedirect(httpResponse, httpRequest.getContextPath() + forwardUrl);
    }
  }
Пример #17
0
  public String active(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    /*
     * 获取激活码
     * 查询数据库,查出来一个User对象
     */
    String code = request.getParameter("code");
    User user = userService.findByCode(code);
    if (user == null) {
      request.setAttribute("msg", "无效的激活码!");
      List<String> links = new ArrayList<String>();
      links.add("<a href='" + request.getContextPath() + "/index.jsp'>主页</a>");
      links.add("<a href='" + request.getContextPath() + "/jsps/regist.jsp'>注册</a>");
      request.setAttribute("links", links);
      return "/jsps/msg.jsp";
    }
    if (user.isState()) {
      response.sendError(500, "您已经激活,无需重复激活!");
      return null;
    }

    // 修改状态
    request.setAttribute("msg", "恭喜!您已激活成功!");
    List<String> links = new ArrayList<String>();
    links.add("<a href='" + request.getContextPath() + "/index.jsp'>主页</a>");
    links.add("<a href='" + request.getContextPath() + "/jsps/login.jsp'>登录</a>");
    request.setAttribute("links", links);
    return "/jsps/msg.jsp";
  }
Пример #18
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String name = req.getParameter("name").trim();
    Integer id = Integer.parseInt(req.getParameter("id").trim());
    BigDecimal minSalary = new BigDecimal(req.getParameter("minSalary").trim());
    BigDecimal maxSalary = new BigDecimal(req.getParameter("maxSalary").trim());

    if (!name.equals("") && id != 0) {
      Position position = new Position(id, name, minSalary, maxSalary);
      Connection con = (Connection) getServletContext().getAttribute("DBConnection");
      PositionTable dt = new PositionTable(con);
      try {
        dt.savePosition(position);
      } catch (SQLException e) {
        e.printStackTrace();
        // TODO handle this
      }
      resp.setStatus(resp.SC_MOVED_TEMPORARILY);
      resp.setHeader("Location", req.getContextPath() + "/positions");
    }
    req.setAttribute("positionName", name);
    req.setAttribute("positionId", id);
    req.setAttribute("minSalary", minSalary);
    req.setAttribute("maxSalary", maxSalary);
    req.setAttribute("actionUrl", req.getContextPath() + "/positions/edit/?id=" + id);
    getServletContext().getRequestDispatcher("/positions/add.jsp").forward(req, resp);
  }
Пример #19
0
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    String uri = request.getRequestURI();
    log.info("uri=" + uri);
    uri = uri.replaceFirst(request.getContextPath(), "");

    if (!uri.startsWith("/page")) {
      return true;
    }

    if (request.getSession().getAttribute(Constant.USER_SESSION_KEY) == null) {
      // 未登录
      PrintWriter out = response.getWriter();
      StringBuilder builder = new StringBuilder();
      builder.append("<script type=\" text/javascript \" charset=\"UTF-8\">");
      builder.append("window.top.location.href=\"");
      builder.append(request.getContextPath());
      builder.append("/\";</script>");
      out.print(builder.toString());
      out.close();
      return false;
    } else {
      return true;
    }
  }
  /**
   * 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");
    }
  }
Пример #21
0
  /**
   * 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 {
    response.setContentType("text/html;charset=UTF-8");
    HttpSession sess = request.getSession();
    session se = (session) sess.getAttribute("actualsession");
    response.setContentType("text/html;charset=UTF-8");

    if (se == null) {

      response.sendRedirect(request.getContextPath());

    } else {

      if (se.getUs().getTipo().equals("aluno") && se.isvalid()) {
        HtmlCoder d = new HtmlCoder();
        String resposta = d.relatorioProva(se, se.getListaPerguntas());
        se.setListaPerguntas(null);
        try (PrintWriter out = response.getWriter()) {
          out.print(resposta);
        }

      } else {

        response.sendRedirect(request.getContextPath());
      }
    }
  }
Пример #22
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String username = req.getParameter("username");
    String password = req.getParameter("password");

    HttpSession session = req.getSession(false);
    if (session != null && session.getAttribute("user") != null) {
      resp.sendRedirect(req.getContextPath() + "/home");
      return;
    }

    if (!userService.isUsernameAlreadyRegistered(username)) {
      req.setAttribute(
          "error",
          "Could not find user "
              + username
              + ". Check its spelling or register if you aren't registered yet.");
      req.getRequestDispatcher("/login.jsp").forward(req, resp);
    } else {
      User user = userService.getUser(username);
      if (!BCrypt.checkpw(password, user.getPassword())) {
        req.setAttribute(
            "error", "Could not sign you in. Please check your username and password.");
        req.getRequestDispatcher("/login.jsp").forward(req, resp);
      }
      // these are the droids we are looking for
      session = req.getSession(true); // creates a new session if no session available
      session.setAttribute("user", user);
      resp.sendRedirect(req.getContextPath() + "/home");
    }
  }
Пример #23
0
  /**
   * 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 {

    Tools tools = new Tools();
    String access_token = tools.getCookie("access_token", request);

    AnswerWS.Answer answer = new Answer();

    answer.setContent(request.getParameter("content"));
    answer.setIdQuestion(Integer.parseInt(request.getParameter("qid")));

    int ret = insertAnswer(access_token, answer);

    switch (ret) {
      case 1:
        response.sendRedirect(
            request.getContextPath()
                + "/question?id="
                + Integer.parseInt(request.getParameter("qid")));
        break;
      case 0:
        response.sendRedirect(request.getContextPath() + "/login?alert=0");
        break;
      case -1:
        response.sendRedirect(request.getContextPath() + "/login?alert=-1");
        break;
      default:
        response.sendRedirect(request.getContextPath() + "/login?alert=-1");
    }
  }
Пример #24
0
  /**
   * The doPost method of the servlet. <br>
   * This method is called when a form has its tag value method equals to post.
   *
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html;charset=utf-8");
    Admin adm = new Admin();
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    adm.setUsername(username);

    adm.setPasswd(password);

    LogDAO log = new LogDAO();

    if (adm.getUsername() != null
        && adm.getUsername() != ""
        && adm.getPasswd() != null
        && adm.getPasswd() != "") {

      if (log.check(adm.getUsername(), adm.getPasswd())) {
        response.sendRedirect(request.getContextPath() + "/adminMenu.jsp");
      } else {
        response.sendRedirect(request.getContextPath() + "/failLogin.jsp");
      }
    } else {
      response.sendRedirect(request.getContextPath() + "/index.jsp");
    }
  }
Пример #25
0
 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
     throws Exception {
   HttpSession session = request.getSession();
   Principal principal = (Principal) session.getAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME);
   if (principal != null) {
     return true;
   } else {
     String requestType = request.getHeader("X-Requested-With");
     if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
       response.addHeader("loginStatus", "accessDenied");
       response.sendError(HttpServletResponse.SC_FORBIDDEN);
       return false;
     } else {
       if (request.getMethod().equalsIgnoreCase("GET")) {
         String redirectUrl =
             request.getQueryString() != null
                 ? request.getRequestURI() + "?" + request.getQueryString()
                 : request.getRequestURI();
         response.sendRedirect(
             request.getContextPath()
                 + loginUrl
                 + "?"
                 + REDIRECT_URL_PARAMETER_NAME
                 + "="
                 + URLEncoder.encode(redirectUrl, urlEscapingCharset));
       } else {
         response.sendRedirect(request.getContextPath() + loginUrl);
       }
       return false;
     }
   }
 }
Пример #26
0
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   HttpSession session = request.getSession(false);
   User user = (User) session.getAttribute("user");
   MessageBox messageBox = new MessageBox();
   // Check the permissions.
   if (user.getRole() == UserRole.ADMIN || user.getRole() == UserRole.EDITOR) {
     if (request.getParameter("selectionIds") == null) {
       // The method is called from the chain list page.
       this.doGet(request, response);
     } else {
       // The method is called from the chain delete page.
       String[] selection = (request.getParameter("selectionIds")).split(",");
       List<String> selectionList = chainIdsToListOfTitles(selection);
       for (int i = 0; i < selection.length; i++) {
         ChainService.removeChain(Long.valueOf(selection[i].trim()));
       }
       // Form the success message.
       messageBox.setTitle("The following chains have been successfully deleted:");
       messageBox.setMessages(selectionList);
       Messager.sendMessage(request, messageBox, MessageSeverity.SUCCESS);
       response.sendRedirect(request.getContextPath() + "/ChainList");
     }
   } else {
     // Form the error message.
     messageBox.setTitle(
         "Not enough previlegues to perform the operation. Please contact the administrator.");
     Messager.sendMessage(request, messageBox, MessageSeverity.ERROR);
     response.sendRedirect(request.getContextPath() + "/ChainList");
   }
 }
Пример #27
0
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    String uri = req.getRequestURI();

    log.info(req.getRemoteAddr() + "\tvisite\t" + uri);
    String project = req.getContextPath();
    /*if (SESSION_COMPANY == null && SESSION_BUYER == null && SESSION_BRANCH==null && !uri.endsWith(project+"/logout.do")) {
    	cookieLogin((HttpServletRequest)request, (HttpServletResponse)response);
    }*/
    if ((project + "/").equals(uri) || (project + "/index.jsp").equals(uri)) {
      res.sendRedirect(req.getContextPath() + "/index.do"); // 用户未登
    }

    if (isNeedCheck(uri, project)) {
      if (1 == 1) {
        // 如果toLogin参数存在,则登录以后跳回到原页面
        String toLogin = req.getParameter("toLogin");
        String returnURL = "";
        if (null != toLogin) returnURL = req.getHeader("Referer");
        // 用户未登
        res.sendRedirect(req.getContextPath() + "/login.jsp?returnURL=" + returnURL);
      } else {
        chain.doFilter(request, response);
      }
    } else {
      chain.doFilter(request, response);
    }
  }
Пример #28
0
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    HttpSession session = request.getSession();
    // if (!(((HandlerMethod)handler).getBean() instanceof
    // BaseReportController)) {
    if (!(request.getRequestURI().equals(request.getContextPath() + "/report/request"))) {
      if (session == null || session.getAttribute("USER_SESSION") == null) {

        String requestedWithHeader = request.getHeader("X-Requested-With");
        if (requestedWithHeader.equalsIgnoreCase("XMLHttpRequest")) {
          response.sendRedirect(
              request.getContextPath()
                  + "/exception/ajaxResponse?message="
                  + SESSION_TIME_OUT_MSG
                  + "&exceptionHandler="
                  + CustomGenericException.class.getName());
        }
        // logger.debug("Invalid session from requesting URL={}", request.getRequestURL());
        logger.error(
            "Invalid session from requesting URL={}",
            request.getRequestURL(),
            new CustomGenericException(SESSION_TIME_OUT_MSG));
        throw new CustomGenericException(SESSION_TIME_OUT_MSG);
      }
    }
    // }
    return true;
  }
  /**
   * 覆盖默认实现,用sendRedirect直接跳出框架,以免造成js框架重复加载js出错。
   *
   * @param token
   * @param subject
   * @param request
   * @param response
   * @return
   * @throws Exception
   * @see
   *     org.apache.shiro.web.filter.authc.FormAuthenticationFilter#onLoginSuccess(org.apache.shiro.authc.AuthenticationToken,
   *     org.apache.shiro.subject.Subject, javax.servlet.ServletRequest,
   *     javax.servlet.ServletResponse)
   */
  @Override
  protected boolean onLoginSuccess(
      AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response)
      throws Exception {
    // issueSuccessRedirect(request, response);
    // we handled the success redirect directly, prevent the chain from continuing:
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    ShiroDbRealm.ShiroUser shiroUser = (ShiroDbRealm.ShiroUser) subject.getPrincipal();
    // 加入ipAddress
    shiroUser.setIpAddress(request.getRemoteAddr());

    // 这个是放入user还是shiroUser呢?
    httpServletRequest.getSession().setAttribute(SecurityConstants.LOGIN_USER, shiroUser.getUser());

    if (!"XMLHttpRequest".equalsIgnoreCase(httpServletRequest.getHeader("X-Requested-With"))
        || request.getParameter("ajax") == null) { // 不是ajax请求
      httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + this.getSuccessUrl());
    } else {
      httpServletResponse.sendRedirect(
          httpServletRequest.getContextPath() + "/login/timeout/success");
    }

    return false;
  }
  /**
   * Publish the request/response statistics
   *
   * @param request
   * @param requestTime
   * @param response : boolean
   * @return
   * @throws APIFaultException
   * @throws APIManagementException
   */
  public boolean publishStatistics(HttpServletRequest request, long requestTime, boolean response)
      throws APIManagementException {

    UsageStatConfiguration statConf = new UsageStatConfiguration();
    APIMgtUsageDataPublisher publisher = statConf.getPublisher();
    if (publisher != null) {
      publisher.init();
      APIStatsPublisher statsPublisher = new APIStatsPublisher(publisher, statConf.getHostName());
      if (response) {
        statsPublisher.publishResponseStatistics(
            apiKeyValidationDTO,
            request.getRequestURI(),
            request.getContextPath(),
            request.getPathInfo(),
            request.getMethod(),
            requestTime);
      } else {
        statsPublisher.publishRequestStatistics(
            apiKeyValidationDTO,
            request.getRequestURI(),
            request.getContextPath(),
            request.getPathInfo(),
            request.getMethod(),
            requestTime);
      }
      return true;
    }
    return false;
  }