Example usage for javax.servlet.http HttpServletRequest getRequestDispatcher

List of usage examples for javax.servlet.http HttpServletRequest getRequestDispatcher

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getRequestDispatcher.

Prototype

public RequestDispatcher getRequestDispatcher(String path);

Source Link

Document

Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.

Usage

From source file:atd.backend.Register.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    RequestDispatcher rd = null;//from ww  w.j  ava 2  s  .  c o m
    System.out.println(req.getParameter("checkbox"));
    if (req.getParameter("checkbox") != null) {
        String username = req.getParameter("username").toLowerCase();
        String realName = req.getParameter("realname");

        try {
            Class.forName("org.apache.commons.codec.digest.DigestUtils");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String wachtwoord = org.apache.commons.codec.digest.DigestUtils.sha256Hex(req.getParameter("password"));
        if (UsersDAO.searchUser(username) != null) {
            req.setAttribute("errorReg",
                    "<div class=\"alert alert-danger\" role=\"alert\"> <span class=\"sr-only\">Error:</span> Username is bezet</div>");
            rd = req.getRequestDispatcher("register/register.jsp");
            rd.forward(req, resp);
            return;
        }
        if (username.equals("") || realName.equals("") || wachtwoord.equals("")) {
            req.setAttribute("errorReg",
                    "<div class=\"alert alert-danger\" role=\"alert\"> <span class=\"sr-only\">Error:</span> Er is een veld leeg</div>");
            rd = req.getRequestDispatcher("register/register.jsp");
            rd.forward(req, resp);
            return;
        }

        // Hier moet nog een uurloon veld komen
        UsersDAO.setUser(new User(0, realName, username, Privilege.MONTEUR, 10.00), wachtwoord);
        req.setAttribute("error",
                "<div class=\"alert alert-success\" role=\"alert\"> <span class=\"sr-only\">Info:</span> nieuwe gebruiker is aangemaakt </div>");
        rd = req.getRequestDispatcher("login/login.jsp");
        rd.forward(req, resp);
    } else {
        String username = req.getParameter("username").toLowerCase();
        String realName = req.getParameter("realname");

        try {
            Class.forName("org.apache.commons.codec.digest.DigestUtils");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String wachtwoord = org.apache.commons.codec.digest.DigestUtils.sha256Hex(req.getParameter("password"));
        String postcode = req.getParameter("postcode");
        String email = req.getParameter("email");

        String kenteken = req.getParameter("kenteken");
        String merk = req.getParameter("merk");
        String type = req.getParameter("type");

        if (KlantenDAO.searchKlant(username) != null) {
            req.setAttribute("errorReg",
                    "<div class=\"alert alert-danger\" role=\"alert\"> <span class=\"sr-only\">Error:</span> Username bestaat al</div>");
            rd = req.getRequestDispatcher("register/register.jsp");
            rd.forward(req, resp);
            return;
        }

        if (username.equals("") || realName.equals("") || wachtwoord.equals("") || postcode.equals("")
                || email.equals("") || kenteken.equals("") || merk.equals("") || type.equals("")) {
            req.setAttribute("errorReg",
                    "<div class=\"alert alert-danger\" role=\"alert\"> <span class=\"sr-only\">Error:</span> Er is een veld leeg</div>");
            rd = req.getRequestDispatcher("register/register.jsp");
            rd.forward(req, resp);
            return;
        }

        AutoDAO.setAuto(new Auto(0, kenteken, merk, type));
        Klant k = new Klant(0, realName, username, postcode, email, AutoDAO.searchAuto(kenteken),
                Privilege.KLANT);
        KlantenDAO.setKlant(k, wachtwoord);
        sendRegMail(k);
        req.setAttribute("error",
                "<div class=\"alert alert-success\" role=\"alert\"> <span class=\"sr-only\">Info:</span> Gebruiker "
                        + k.getUsername() + " is aangemaakt </div>");
        rd = req.getRequestDispatcher("login/login.jsp");
        rd.forward(req, resp);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.FauxPropertyRetryController.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(req, response, SimplePermission.EDIT_ONTOLOGY.ACTION)) {
        return;/*from   www.jav a 2s. com*/
    }

    // create an EditProcessObject for this and put it in the session
    EditProcessObject epo = super.createEpo(req);

    // Populate it.
    EpoPopulator populator = new EpoPopulator(req, epo);
    populator.populate();

    req.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp");
    req.setAttribute("colspan", "5");
    req.setAttribute("formJsp", "/templates/edit/specific/fauxProperty_retry.jsp");
    req.setAttribute("scripts", "/templates/edit/formBasic.js");
    req.setAttribute("title", "Faux Property Editing Form");
    req.setAttribute("_action", epo.getAction());
    setRequestAttributes(req, epo);

    try {
        RequestDispatcher rd = req.getRequestDispatcher(Controllers.BASIC_JSP);
        rd.forward(req, response);
    } catch (Exception e) {
        log.error("Could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

}

From source file:feedme.controller.OrderCompleteServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*from   w  w w . j a  v  a  2 s  .c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    AuthenticatUser customer = (AuthenticatUser) request.getSession().getAttribute("AuthenticatUser");//getting the customer from the session
    try {//check if its a customer 
        if (customer != null && PasswordEncryptionService.authenticate(Integer.toString(0),
                customer.getEncrypRole(), "Customer".getBytes())) {
            request.setAttribute("customer",
                    (Customer) new DbUsersManagement().getUserById(customer.getUserId()));
        }
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(OrderCompleteServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeySpecException ex) {
        Logger.getLogger(OrderCompleteServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    RequestDispatcher dispatcher = request.getRequestDispatcher("website/complete_order.jsp");//displays the customer a jsp file
    dispatcher.forward(request, response);

}

From source file:com.oncloud6.atd.invoices.InvoicesShowServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/* www  . j  av  a2 s .co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    SessionFactory factory = new HibernateConnector().getSessionFactory();
    Session hibernateSession = factory.openSession();
    Transaction tx = null;

    boolean idSet = false;
    if (request.getParameter("id") == null || request.getParameter("id").equals("")) {
        response.sendRedirect("invoices");
    } else {
        try {
            Factuur gekozenFactuur = new Factuur();
            gekozenFactuur = (Factuur) hibernateSession.get(Factuur.class,
                    Integer.parseInt(request.getParameter("id")));
            if (gekozenFactuur == null) {
                response.sendRedirect("invoices");
            } else {
                HttpSession session = request.getSession(true);
                RequestDispatcher rd = null;
                if (!RightsControl.checkGroup("invoices_show", "own", session,
                        gekozenFactuur.getDeKlant().getGebruiker().getId())) {
                    rd = request.getRequestDispatcher("error/403error.jsp");
                    rd.forward(request, response);
                    return;
                }

                response.addHeader("Content-Disposition",
                        "attachment; filename=fac" + gekozenFactuur.getFactuurNummer() + ".pdf");
                Process process = Runtime.getRuntime().exec(
                        "c:\\rotativa\\wkhtmltopdf.exe -q -n --disable-smart-shrinking http://localhost:8080/Themaproject/invoicessource?id="
                                + request.getParameter("id") + "&secret=" + gekozenFactuur.getSecret() + " -");
                response.setContentType("application/pdf");
                try {
                    IOUtils.copy(process.getInputStream(), response.getOutputStream());
                } finally {
                    process.getInputStream().close();
                    response.getOutputStream().close();
                }
            }
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            hibernateSession.close();
        }
    }

}

From source file:com.alfaariss.oa.util.saml2.profile.AbstractSAML2Profile.java

/**
 * Forwards the user to the OA WebSSO Servlet.
 * <br>//www  .j ava2s.c  om
 * Before forwarding the session.setProfileURL() is set and the session is 
 * added as an attribute in the request .
 * @param request The servlet request.
 * @param response The servlet response.
 * @param session The user session
 * @throws OAException If the user can't be forwarded.
 */
protected void forwardUser(HttpServletRequest request, HttpServletResponse response, ISession session)
        throws OAException {
    try {
        StringBuffer sbProfileUrl = new StringBuffer();
        sbProfileUrl.append(_sProfileURL);
        sbProfileUrl.append("?");
        sbProfileUrl.append(ISession.ID_NAME);
        sbProfileUrl.append("=");
        sbProfileUrl.append(session.getId());

        session.setProfileURL(sbProfileUrl.toString());

        request.setAttribute(ISession.ID_NAME, session);

        RequestDispatcher oDispatcher = request.getRequestDispatcher(_sWebSSOPath);
        if (oDispatcher == null) {
            _logger.warn("There is no requestor dispatcher supported with name: " + _sWebSSOPath);
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        oDispatcher.forward(request, response);
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not forward user", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:org.guanxi.sp.engine.form.RegisterGuardFormController.java

/**
 * Output a visual representation of a certificate chain
 *
 * @param request Standard issue HttpServletRequest
 * @param response Standard issue HttpServletResponse
 * @param caBean CABean instance from a call to createSignedCertificateChain
 *//* w w  w. j  av a 2  s. c o m*/
private void displayChain(HttpServletRequest request, HttpServletResponse response, CABean caBean) {
    try {
        PEMWriter pemWriter = new PEMWriter(response.getWriter());
        X509Certificate[] certs = caBean.getChain();
        for (int count = 0; count < certs.length; count++) {
            pemWriter.writeObject(certs[count]);
        }
        pemWriter.close();
    } catch (Exception e) {
        logger.error(e);
        try {
            request.setAttribute("ERROR_ID", "ID_NEED_ALL_PARAMETERS");
            request.setAttribute("ERROR_MESSAGE", e.getMessage());
            request.getRequestDispatcher("/guanxi_sp/sp_error.jsp").forward(request, response);
        } catch (Exception ex) {
            logger.error(e);
        }
    }
}

From source file:grails.plugin.springsecurity.web.access.AjaxAwareAccessDeniedHandler.java

public void handle(final HttpServletRequest request, final HttpServletResponse response,
        final AccessDeniedException e) throws IOException, ServletException {

    if (e != null && isLoggedIn() && authenticationTrustResolver.isRememberMe(getAuthentication())) {
        // user has a cookie but is getting bounced because of IS_AUTHENTICATED_FULLY,
        // so Spring Security won't save the original request
        requestCache.saveRequest(request, response);
    }//  ww  w .  j  ava2  s  .  c om

    if (response.isCommitted()) {
        return;
    }

    boolean ajaxError = ajaxErrorPage != null && SpringSecurityUtils.isAjax(request);
    if (errorPage == null && !ajaxError) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
        return;
    }

    if (useForward && (errorPage != null || ajaxError)) {
        // Put exception into request scope (perhaps of use to a view)
        request.setAttribute(WebAttributes.ACCESS_DENIED_403, e);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        request.getRequestDispatcher(ajaxError ? ajaxErrorPage : errorPage).forward(request, response);
        return;
    }

    String redirectUrl;
    String serverURL = ReflectionUtils.getGrailsServerURL();
    if (serverURL == null) {
        boolean includePort = true;
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = portResolver.getServerPort(request);
        String contextPath = request.getContextPath();
        boolean inHttp = "http".equals(scheme.toLowerCase());
        boolean inHttps = "https".equals(scheme.toLowerCase());

        if (inHttp && (serverPort == 80)) {
            includePort = false;
        } else if (inHttps && (serverPort == 443)) {
            includePort = false;
        }
        redirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "") + contextPath;
    } else {
        redirectUrl = serverURL;
    }

    if (ajaxError) {
        redirectUrl += ajaxErrorPage;
    } else if (errorPage != null) {
        redirectUrl += errorPage;
    }
    response.sendRedirect(response.encodeRedirectURL(redirectUrl));
}

From source file:edu.lternet.pasta.portal.EventDeleteServlet.java

/**
 * The doPost method of the servlet. <br>
 * /*from   w ww  .  j a v a2  s. co m*/
 * 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 {

    HttpSession httpSession = request.getSession();

    String uid = (String) httpSession.getAttribute("uid");

    if (uid == null || uid.isEmpty())
        uid = "public";

    String subscriptionId = request.getParameter("subscriptionid");

    String message = null;
    String type = null;

    if (uid.equals("public")) {

        message = LOGIN_WARNING;
        type = "warning";

    } else {

        try {

            EventSubscriptionClient eventClient = new EventSubscriptionClient(uid);
            eventClient.deleteBySid(subscriptionId);
            message = "Event subscription with identifier '<b>" + subscriptionId + "</b>' has been deleted.";
            type = "info";

        } catch (Exception e) {
            handleDataPortalError(logger, e);
        }

    }

    request.setAttribute("deletemessage", message);
    request.setAttribute("type", type);

    RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward);
    requestDispatcher.forward(request, response);

}

From source file:Index.UploadFileServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w  w w .  j ava  2 s  .  c  o m
 *
 * @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");

    String ubicacionArchivo = "C:\\Users\\Romina\\Documents\\NetBeansProjects\\QuickOrderWeb\\web\\images";

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);
    factory.setRepository(new File(ubicacionArchivo));

    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List<FileItem> partes = upload.parseRequest(request);

        for (FileItem item : partes) {
            File file = new File(ubicacionArchivo,
                    request.getSession().getAttribute("userName").toString() + ".jpg");
            item.write(file);
            System.out.println("name: " + item.getName());
        }
        request.setAttribute("error", null);
        request.setAttribute("result", "Se ha registrado correctamente");
        request.setAttribute("funcionalidad", "Imagen");
        request.getSession().removeAttribute("userName");

        request.getRequestDispatcher("/Login.jsp").forward(request, response);
    } catch (FileUploadException ex) {
        System.out.println("Error al subir el archivo: " + ex.getMessage());

        request.setAttribute("error", "Error al subir la imagen");
        request.setAttribute("funcionalidad", "Imagen");

        request.getRequestDispatcher("/Login.jsp").forward(request, response);
    } catch (Exception ex) {
        System.out.println("Error al subir el archivo: " + ex.getMessage());
        request.setAttribute("error", "Error al subir la imagen");
        request.setAttribute("funcionalidad", "Imagen");

        request.getRequestDispatcher("/Login.jsp").forward(request, response);

    }

}

From source file:com.lrodriguez.SVNBrowser.java

private void doSort(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        Comparator comparator) throws ServletException, IOException {
    logDebug("dispatching Sort request");
    Collections.sort(((List) session.getAttribute(UNIQUE_ENTRIES)), comparator);
    request.getRequestDispatcher(INDEX_JSP).forward(request, response);
    return;//from w  ww.  j av a2 s  .c om
}