@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());
  }
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   if (req.getParameter("setPersistBlocks") != null) {
     this.nn
         .getNamesystem()
         .setPersistBlocks(req.getParameter("setPersistBlocks").equals("ON") ? true : false);
     resp.sendRedirect("/nnconf");
     return;
   }
   if (req.getParameter("setPermissionAuditLog") != null) {
     this.nn
         .getNamesystem()
         .setPermissionAuditLog(
             req.getParameter("setPermissionAuditLog").equals("ON") ? true : false);
     resp.sendRedirect("/nnconf");
     return;
   }
   PrintWriter out = resp.getWriter();
   String hostname = this.nn.getNameNodeAddress().toString();
   out.print("<html><head>");
   out.printf("<title>%s NameNode Admininstration</title>\n", hostname);
   out.print("<link rel=\"stylesheet\" type=\"text/css\" " + "href=\"/static/hadoop.css\">\n");
   out.print("</head><body>\n");
   out.printf(
       "<h1><a href=\"/dfshealth.jsp\">%s</a> " + "NameNode Configuration Admin</h1>\n", hostname);
   showOptions(out);
   out.print("</body></html>\n");
 }
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws ServletException {
    boolean result = super.preHandle(request, response, handler);

    ThemeResolver themeResolver = RequestContextUtils.getThemeResolver(request);

    String newTheme = themeResolver.resolveThemeName(request);

    if (!validThemes.contains(newTheme)) {
      // not found.
      logger.error("Invalid theme passed in: " + newTheme);
      try {
        response.sendRedirect("accessDenied.jsp");

        return false;
      } catch (IOException e) {
        throw new ServletException("Could not redirect to accessDenied page.", e);
      }
    } else if (request.getParameter(this.paramName) != null) {
      // found.  redirect to page without "param=.." extension.
      logger.warn("New theme set: " + newTheme + ".  Redirecting to login.htm");
      try {
        response.sendRedirect("login.htm");
      } catch (IOException e) {
        throw new ServletException("Could not redirect to login page.", e);
      }
    }

    return result;
  }
  /**
   * 覆盖默认实现,用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;
  }
Example #5
0
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    Customer customer = null;

    if (username == null || username.length() <= 0 || password == null || password.length() <= 0) {
      log.warn("Empty username and/or password used for login");
      return ViewUtil.createErrorView("error.empty.username.or.password");
    }

    // login function is handled by the appropriate access mode handler
    customer = accessModeController.login(username, password);

    if (customer == null) {
      log.warn("Invalid login attempt with username = "******" and password = "******"error.invalid.username.or.password");
    }

    UserSession userSession = new UserSession(customer);
    request.getSession().setAttribute("userSession", userSession);
    String forwardAction = request.getParameter("forwardAction");

    if (forwardAction != null) {
      log.info("Forwarding response to original request url: " + forwardAction);
      response.sendRedirect(forwardAction);
      return null;
    } else {
      response.sendRedirect("overview.htm");
      return null;
    }
  }
  @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;
  }
Example #7
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");
  }
Example #8
0
 @Override
 protected void redirectToCAS(
     final CasConfig casConfig,
     final HttpServletRequest request,
     final HttpServletResponse response)
     throws IOException, ServletException {
   if (UserView.getUser() == null) {
     String pendingRequest = request.getParameter("pendingRequest");
     if (pendingRequest == null) {
       pendingRequest = (String) request.getAttribute("pendingRequest");
     }
     final String barraAsAuthBroker =
         PropertiesManager.getProperty("barra.as.authentication.broker");
     final boolean useBarraAsAuthenticationBroker =
         barraAsAuthBroker != null && barraAsAuthBroker.equals("true");
     final String serviceString =
         encodeUrl(RequestUtils.generateRedirectLink(casConfig.getServiceUrl(), pendingRequest));
     String casLoginUrl = "";
     if (useBarraAsAuthenticationBroker) {
       final String barraLoginUrl = PropertiesManager.getProperty("barra.loginUrl");
       casLoginUrl += barraLoginUrl;
       casLoginUrl += "?next=";
     }
     casLoginUrl += casConfig.getCasLoginUrl();
     final String casLoginString = casLoginUrl + "?service=" + serviceString;
     response.sendRedirect(casLoginString);
   } else {
     response.sendRedirect(request.getContextPath() + "/home.do");
   }
 }
Example #9
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    // doGet(request, response);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession(true);
    String user = (String) session.getAttribute("currentuser");

    String plname = request.getParameter("plname");
    String ispublic = request.getParameter("secure");
    String[] tracks = request.getParameterValues("track");

    if (tracks.length <= 0) {
      session.setAttribute("playlistdata", "Invalid");
      response.sendRedirect("newplaylist.jsp");
    }

    if (ispublic == "") {
      session.setAttribute("playlistdata", "checkradio");
      response.sendRedirect("newplaylist.jsp");
    } else {
      if (HomepageAct.addPlaylist(user, tracks, plname, ispublic) == 0) {
        session.setAttribute("datavalid", "Valid");
        response.sendRedirect("myplaylist.jsp");
      } else {
        out.println("Sorry! there was some error during creating the playlist Please try again.");
        response.sendRedirect("newplaylist.jsp");
      }
    }
  }
Example #10
0
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   req.setCharacterEncoding("UTF-8");
   resp.setCharacterEncoding("UTF-8");
   String carname = req.getParameter("carname");
   String carinfo = req.getParameter("carinfo");
   float carprice = Float.parseFloat(req.getParameter("carprice"));
   String imgpath = req.getParameter("imgpath");
   int num = Integer.parseInt(req.getParameter("num"));
   if (!(carname.equals("") && carinfo.equals("") && imgpath.equals(""))
       && carprice > 0
       && num > 0) {
     CarDao cd = new CarDao();
     try {
       if (cd.updateCar(imgpath, carinfo, carprice, num, carname)) {
         resp.sendRedirect("carinfo.jsp?ok=1");
       } else {
         System.out.println("更新失败!");
       }
     } catch (SQLException e) {
       e.printStackTrace();
     }
   } else {
     resp.sendRedirect("carinfo.jsp?ok=0");
   }
 }
Example #11
0
  public void AddGrades(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession();
    this.adminDAO = new AdminDAO();
    ShowGradesForm form = new ShowGradesForm();
    form.setStu_num((String) request.getParameter("stu_num"));
    form.setCourse_id((String) request.getParameter("course_id"));
    form.setScore(request.getParameter("score"));
    String college_id = (String) session.getAttribute("adm_college");

    if (form.getStu_num() == null
        || form.getStu_num() == ""
        || form.getCourse_id() == null
        || form.getCourse_id() == ""
        || form.getScore() == null
        || form.getScore() == "") {
      // response.sendRedirect("update.jsp");
    } else {
      System.out.println("stu num:" + form.getStu_num());
      System.out.println("course id:" + form.getCourse_id());
      System.out.println("score:" + form.getScore());
      System.out.println("college id:" + college_id);

      int result = adminDAO.checkAddInfo(form.getStu_num(), form.getCourse_id(), form.getScore());
      if (result != 0) {
        System.out.println("result:" + result);
        session.setAttribute("addmode", Integer.toString(result));
        response.sendRedirect("update.jsp");
      } else if (adminDAO.addScore(form) != 0) {
        response.sendRedirect("add_ok.jsp");
      } else {
        System.out.println("添加失败");
      }
    }
  }
Example #12
0
  @RequestMapping(value = "editcomment", method = RequestMethod.POST)
  public void editComment(
      HttpServletResponse respone,
      @RequestParam("id") String id,
      @RequestParam("content") String content,
      @RequestParam("user_name") String user_name,
      @RequestParam("user_email") String user_email)
      throws IOException {
    if (content.equals("") || user_email.equals("") || user_name.equals("")) {
      respone.sendRedirect("article?id=" + id);
      return;
    }
    // 判断邮箱的正则表达式
    String checkemail =
        "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
    Pattern regex = Pattern.compile(checkemail);
    Matcher matcher = regex.matcher(user_email);
    if (matcher.matches() == false) {
      respone.sendRedirect("article?id=" + id);
      return;
    }

    Integer idact = Integer.parseInt(id);
    Date curtime = new Date(System.currentTimeMillis());
    synchronized (ComPostController.class) {
      // 首先是对一篇文章的评论
      Comment commentpojo = new Comment(0, user_name, user_email, curtime, content, "a", idact, 0);
      commentService.insertArt(commentpojo);
    }
    respone.sendRedirect("article?id=" + id);
  }
Example #13
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (!request.isUserInRole("2")) {
      response.sendRedirect("/");
    }

    Reponse uneReponse = new Reponse();
    uneReponse.setLibelle(request.getParameter("libelle"));
    uneReponse.setEst_correct(Boolean.parseBoolean(request.getParameter("estCorrect")));
    uneReponse.setId_question(Integer.parseInt(request.getParameter("idQuestion")));

    Question question = null;

    try {
      question = QuestionService.getQuestion(Integer.parseInt(request.getParameter("idQuestion")));
    } catch (NumberFormatException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    } catch (SQLException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    try {
      ReponseService.insert(uneReponse);
      response.sendRedirect(
          "themeQuestRep?idTheme="
              + String.valueOf(question.getId_theme())
              + "&idQuestion="
              + request.getParameter("idQuestion"));
    } catch (Exception e) {
      doGet(request, response);
    }
  }
  /**
   * 删除客户潜在项目
   *
   * @param request
   * @param response
   * @return
   * @throws Exception
   */
  public ModelAndView removeLatencyCustomer(
      HttpServletRequest request, HttpServletResponse response) throws Exception {

    Connection conn = null;

    String customerId = request.getParameter("customerid");
    try {
      conn = new DBConnect().getConnect("");
      // 要删除的客户潜在项目的autoid
      String autoid = request.getParameter("autoid");

      LatencyCustomerService latencyCustomerService = new LatencyCustomerService(conn);
      // 删除客户潜在项目
      latencyCustomerService.removeLatencyCustomer(autoid);

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      DbUtil.close(conn);
    }

    if ("".equals(customerId) || customerId == null) {
      response.sendRedirect("latencyCustomer.do");
    } else {
      response.sendRedirect("latencyCustomer.do?customerid=" + customerId);
    }

    return null;
  }
Example #15
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 {
   String url = request.getParameter("url_req");
   String user = request.getParameter("username");
   String password = request.getParameter("password");
   String[] remember = request.getParameterValues("cookie");
   try {
     User u = RegistrationManager.verifyUser(user, password);
     if (u != null) {
       if (!u.getProfile().equals(RegistrationManager.NO_PROFILES)) {
         request.getSession().setAttribute("user", u);
         if (remember != null) {
           Cookie cookie = new Cookie("user", user);
           cookie.setMaxAge(30 * 24 * 60 * 60); // 1 month.
           cookie.setPath("/");
           response.addCookie(cookie);
         }
         u.updateLastAccess(user);
         if (url.equals("null")) response.sendRedirect("index.jsp");
         else response.sendRedirect(url);
       } else {
         request.setAttribute(
             StringConstants.MESSAGE_ATTRIBUTE, StringConstants.MESSAGE_DOMAIN_ERROR);
         request.getRequestDispatcher("login.jsp").forward(request, response);
       }
     } else {
       request.setAttribute(StringConstants.MESSAGE_ATTRIBUTE, StringConstants.MESSAGE_ERROR);
       request.getRequestDispatcher("login.jsp").forward(request, response);
     }
   } catch (IOException | ServletException e) {
     request.setAttribute(StringConstants.MESSAGE_ATTRIBUTE, StringConstants.MESSAGE_ERROR_SERVER);
     request.getRequestDispatcher("login.jsp").forward(request, response);
   }
 }
Example #16
0
  // Get session json
  @RequestMapping(
      value = "/login",
      method = {RequestMethod.POST, RequestMethod.GET})
  public void login(
      @RequestParam(value = "database", required = true) String database,
      @RequestParam(value = "username", required = true) String username,
      @RequestParam(value = "password", required = true) String password,
      HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException, IOException {

    // Get profissional
    LoginDAO loginDAO = this.getDAO(database);

    Map<String, String> user = loginDAO.getUser(username, password);

    // Check if user exist
    if (user == null) {
      // return to login page
      System.out.println(Labels.USER_NOT_FOUND);
      response.sendRedirect("home");
      return;
    }

    user.put("username", username);
    user.put("database", database);

    HttpSession s = request.getSession();

    // Write values to session
    this.mapToSession(user, s);

    response.sendRedirect(LoginController.DASHBOARD);
  }
  /**
   * 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");
    }
  }
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response) {
   try (InputStream inputStream =
       getClass().getClassLoader().getResourceAsStream("Aconfig/adminconfig.properties")) {
     String S_error = "";
     HttpSession session;
     String _uname = request.getParameter("adusnam");
     String _pass = request.getParameter("adpass");
     Properties properties = new Properties();
     if (inputStream != null) {
       properties.load(inputStream);
     }
     if (_uname.equals(properties.get("adus")) && _pass.equals(properties.get("adpas"))) {
       session = request.getSession(true);
       session.setAttribute("username", _uname);
       response.sendRedirect("WriteConfig");
     } else {
       session = request.getSession(true);
       session.setAttribute("status", "The username and password did not match");
       response.sendRedirect("AdminAuth");
     }
   } catch (IOException e) {
     Logger.getLogger(AdminAuthServlet.class.getName()).log(Level.SEVERE, null, e);
     response.setStatus(500);
   }
 }
 @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;
     }
   }
 }
  protected void Register(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String username = request.getParameter("username");
    String password1 = request.getParameter("password1");
    String password2 = request.getParameter("password2");
    String email = request.getParameter("email");

    if (username == null
        || password1 == null
        || password2 == null
        || !password1.equals(password2)) {
      response.sendRedirect("register.jsp");
      return;
    }

    UserBean userBean = new UserBean();
    boolean isExist = userBean.isExist(username);
    if (!isExist) {
      userBean.add(username, password1, email);
      response.sendRedirect("login.jsp");
      return;
    } else {
      response.sendRedirect("register.jsp");
      return;
    }
  }
 /**
  * Handle all HTTP <tt>GET</tt> and <tt>POST</tt> requests. process only first "page" parameter
  * will be processes
  */
 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String site = request.getContextPath() + "/";
   String[] values = request.getParameterValues("page");
   String value = values[0].trim();
   if (value != null && value.trim().length() > 0) {
     if (value.equalsIgnoreCase("home")) {
       String urlWithSessionID = response.encodeRedirectURL(site + "index.jsf");
       response.encodeRedirectURL(site);
       response.sendRedirect(urlWithSessionID);
     } else if (value.equalsIgnoreCase("queryBuilder")) {
       String urlWithSessionID = response.encodeRedirectURL(site + "queryBuilderForm1.jsf");
       response.encodeRedirectURL(site);
       response.sendRedirect(urlWithSessionID);
     } else if (value.equalsIgnoreCase("submittedQueries")) {
       String urlWithSessionID = response.encodeRedirectURL(site + "submittedQueries.jsf");
       response.encodeRedirectURL(site);
       response.sendRedirect(urlWithSessionID);
     } else if (value.equalsIgnoreCase("queryFilter")) {
       String urlWithSessionID = response.encodeRedirectURL(site + "queryFilter.jsf");
       response.encodeRedirectURL(site);
       response.sendRedirect(urlWithSessionID);
     } else {
       String urlWithSessionID = response.encodeRedirectURL(site + "index.jsf");
       response.encodeRedirectURL(site);
       response.sendRedirect(urlWithSessionID);
     }
   }
 }
Example #22
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession(true); // Get client session

    String email = request.getParameter("email");
    String password = request.getParameter("password");

    if (!validUser(request, email, password)) {
      session.setAttribute("login", false);
      response.sendRedirect("/project2_10/login.jsp");
    } else {
      session.setAttribute("login", true);
      session = request.getSession();
      session.setAttribute("user.login", email);
      ShoppingCart.initCart(request, response);
      try {
        String target = (String) session.getAttribute("user.dest");
        // retrieve address if user goes to a page w/o logging in
        if (target != null) {
          session.removeAttribute("user.dest");
          // redirect to page the user was originally trying to go to
          response.sendRedirect(target);
          return;
        }
      } catch (Exception ignored) {
      }

      // Couldn't redirect to the target. Redirect to the site's homepage.
      response.sendRedirect("/project2_10/");
    }
  }
Example #23
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);
    }
  }
Example #24
0
  /* (non-Javadoc)
   * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    Author user = (Author) req.getSession().getAttribute("user");
    try {
      int hotelId = Integer.parseInt(req.getParameter("hotelId"));
      if (user != null) {
        String headline = req.getParameter("headline");
        String description = req.getParameter("description");
        int rating = Integer.parseInt(req.getParameter("rating"));

        if (!headline.equals("") && !description.equals("")) {
          Review review =
              new Review(0, hotelId, user.getId(), rating, new Date(), headline, description);
          Service service = new Service();
          service.addReview(review);
          resp.sendRedirect("hotel.jsp?id=" + hotelId + "&success=Successfully posted review!");
        } else {
          resp.sendRedirect(
              "hotel.jsp?id="
                  + hotelId
                  + "&msg=Please write something, mate. I don't like blank reviews");
        }
      } else {
        resp.sendRedirect("hotel.jsp?id=" + hotelId + "&msg=Please Login to post a review.");
      }
    } catch (NumberFormatException e) {
      resp.sendRedirect("error.jsp?msg=" + e.getLocalizedMessage());
    }
  }
 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);
   }
 }
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String contextPath = request.getContextPath();
    String path = request.getPathInfo();

    log.debug("path info: " + path);
    if (path != null) {
      path = path.substring(1); // remove first slash
      Integer nextSlash = path.indexOf("/");
      if (nextSlash != -1) {
        path = path.substring(0, nextSlash);
      }
      log.debug("new concept id: " + path);
      try {
        Integer i = Integer.valueOf(path);
        // view the concept if the path info was an integer
        response.sendRedirect(contextPath + "/dictionary/concept.htm?conceptId=" + i);
        return;
      } catch (Exception e) {
        // search for the concept if the path info was not an integer
        response.sendRedirect(contextPath + "/dictionary/index.htm?phrase=" + path);
        return;
      }
    }

    // redirect to the search screen if there wasn't any path info
    response.sendRedirect(contextPath + "/dictionary");
  }
Example #27
0
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {

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

    String relativeUrl = request.getRequestURI(); /* 以根开头的URL */
    String path = request.getContextPath(); /* 获取客户端请求的上下文根 */

    /** 如果是登录请求,则进行登录认证。 如果是其它请求,则进行IP绑定匹配。 */
    if (relativeUrl.replaceAll(path, "").equals("/login")) { // 登录请求,登录认证
      if (request.getMethod().equals("POST")) { // 登录参数必须通过post方式传过来,security要求的
        int status = myAuthentication.getAuthenticationStatus(request); // 调用认证逻辑
        if (status == 0) { // 通过认证,则保存登录IP到session,并通过此过滤器
          request.getSession().setAttribute("bindIp", RequestIP.getRequestIp(request));
          chain.doFilter(request, response);
        } else { // 未通过认证,则拒绝登录,并返回登录页面提示相关信息
          response.sendRedirect(path + "/toIndex.action?error=" + status);
        }
      } else { // 如果不是POST方式,则返回登录页面,并提示信息
        response.sendRedirect(path + "/toIndex.action?error=9"); // 登录必须用POST方式
      }
    } else { // 其它请求(filters="none"的请求不会被处理,logout请求在此filter之前会被处理)
      // PC端进行IP认证
      String loginIp = (String) request.getSession().getAttribute("bindIp"); // 登录时记录的IP
      String currentIp = RequestIP.getRequestIp(request); // 当前请求的IP
      if (loginIp != null && !loginIp.equals(currentIp)) { // 如果此次请求的IP与登录IP不符,则禁止访问,并返回提示
        response.sendRedirect(path + "/toIndex.action?error=10");
      } else { // 如果IP匹配,则通过此过滤器
        chain.doFilter(request, response);
      }
    }
  }
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub

    HttpSession session = request.getSession();

    Usuario usuario = (Usuario) session.getAttribute("usuario");

    if (usuario != null) {
      request.setAttribute("usuario", usuario);

      if (usuario.getTipoPerfil().equals("paciente")) {

        PacienteControl pacienteControl = new PacienteControl();

        List<Paciente> lista = pacienteControl.pesquisarPacienteEmail(usuario.getEmail());

        request.setAttribute("listaPacienteUsuario", lista);

        request.setAttribute("listaPaciente", lista);

        request
            .getRequestDispatcher("WEB-INF/paciente/menuPaciente.jsp")
            .forward(request, response);

      } else {
        response.sendRedirect("loginServlet");
      }

    } else {
      response.sendRedirect("loginServlet");
    }
  }
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException { // 登录界面login.jsp进入前判断是否已经登陆,是则直接跳转
   HttpServletRequest req = (HttpServletRequest) request;
   HttpServletResponse res = (HttpServletResponse) response;
   Cookie cookies[] = req.getCookies();
   Cookie login = null;
   Cookie user = null;
   Cookie admin = null;
   // 1)判断cookie为空。2)cookie存在,但没有"loginName"。
   // 3)cookie存在,但有"loginName",但loginName为null或0。
   if (cookies != null) {
     for (int i = 0; i < cookies.length; i++) {
       if (cookies[i].getName().equals("LoginName")) {
         login = cookies[i];
       } else if (cookies[i].getName().equals("superUser")) {
         user = cookies[i];
       } else if (cookies[i].getName().equals("adminRight")) {
         admin = cookies[i];
       }
     }
   }
   if (login != null && !login.getValue().equals("")) {
     if (admin != null && !admin.getValue().equals("")) {
       res.sendRedirect("/Login_Servlet/administrator/login/success.jsp");
     } else if (user != null && !user.getValue().equals("")) {
       res.sendRedirect("/Login_Servlet/user/login/success.jsp");
     }
   } else {
     chain.doFilter(request, response);
   }
 }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {

    try {

      // System.out.println("Invoke Search User Servlet.......");
      List userDetails = new ArrayList();

      UserMasterBean userMasterBean = new UserMasterBean();
      userMasterBean.setUserName(request.getParameter("un"));
      userDetails = UserMasterDAO.findSelectedUser(userMasterBean);

      HttpSession session = request.getSession(true);

      if (userDetails != null && userDetails.size() > 0) {
        System.out.println("User Details Found....");
        session.setAttribute("UserInfo", userDetails);
        response.sendRedirect("jsp/SelectedUserListing.jsp");
      } else {
        System.out.println("User Does Not Exist...");
        session.setAttribute("userCreationStatus", "User Does Not Exist...");
        response.sendRedirect("jsp/UserStatus.jsp");
      }

    } catch (Throwable theException) {
      System.out.println(theException);
    }
  }