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:com.gigglinggnus.controllers.ModifyAppointmentController.java

/**
 *
 * @param request servlet request/*  w  w  w  .  j av a 2s . c om*/
 * @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 {
    EntityManager em = (EntityManager) request.getSession().getAttribute("em");
    Clock clk = (Clock) (request.getSession().getAttribute("clock"));

    boolean modified = false;
    String userId = request.getParameter("userid");
    User user = em.find(User.class, userId);
    String examId = request.getParameter("examid");
    Exam exam = em.find(Exam.class, examId);
    Appointment appt = user.getAppointmentByExam(exam);
    String startTime = request.getParameter("startTime");
    String seatZone = request.getParameter("seatingZone");
    String seatNum = request.getParameter("seatNum");
    String cancel = request.getParameter("cancel");
    try {
        em.getTransaction().begin();
        if (startTime != "") {
            appt.changeStartTime(Instant.parse(startTime), clk);
            em.persist(appt);
            modified = true;
        }
        if (seatZone != "") {
            appt.setSeatingZone(Seating.parse(seatZone));
            em.persist(appt);
            modified = true;
        }
        if (seatNum != "") {
            appt.setSeatNum(Integer.parseInt(seatNum));
            em.persist(appt);
            modified = true;
        }
        em.getTransaction().commit();
    } catch (Exception e) {
        em.getTransaction().rollback();
        request.setAttribute("msg", e);
        RequestDispatcher rd = request.getRequestDispatcher("/home.jsp");
        rd.forward(request, response);
    }
    if (cancel != null) {

        request.setAttribute("msg", "Appointment cancelled");
        RequestDispatcher rd = request.getRequestDispatcher("/home.jsp");
        rd.forward(request, response);
    }
    if (modified == true) {
        request.setAttribute("msg", "Appointment modified");
        RequestDispatcher rd = request.getRequestDispatcher("/home.jsp");
        rd.forward(request, response);
    } else {
        request.setAttribute("msg", "Appointment unchanged");
        RequestDispatcher rd = request.getRequestDispatcher("/home.jsp");
        rd.forward(request, response);
    }
}

From source file:Index.RegisterClienteImagesServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w w .  j a  v  a  2s  .  co  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");
    try (PrintWriter out = response.getWriter()) {

        String ubicacionArchivo = "~\\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);
            webservice.Cliente client = new webservice.Cliente();

            for (FileItem item : partes) {
                client = (webservice.Cliente) request.getSession().getAttribute("registroUsuario");
                File file = new File(ubicacionArchivo, client.getNickname() + ".jpg");
                item.write(file);
                System.out.println("name: " + item.getName());
                client.setImagen(client.getNickname() + ".jpg");
            }

            QuickOrderWebService webService = new QuickOrderWebService();
            ControllerInterface port = webService.getQuickOrderWebServicePort();
            port.registrarCliente(client);

            request.setAttribute("error", null);
            request.setAttribute("agregado", "OK");
            request.removeAttribute("registroUsuario");
            request.getSession().removeAttribute("userName");

            request.getRequestDispatcher("/AltaCliente.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:edu.lternet.pasta.portal.MetadataPreviewerServlet.java

/**
 * The doPost method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to post.
 * // w  w  w  .  j ava 2  s  .c om
 * @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");
    String forward = "./metadataViewer.jsp";

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

    String html = null;

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        try {

            List /* FileItem */ items = upload.parseRequest(request);

            // Process the uploaded items
            Iterator iter = items.iterator();

            while (iter.hasNext()) {

                FileItem item = (FileItem) iter.next();

                if (!(item.isFormField())) {

                    String eml = processUploadedFile(item);

                    EmlUtility emlUtility = new EmlUtility(eml);
                    html = emlUtility.xmlToHtmlSaxon(cwd + xslpath, null);
                }

            }

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

    request.setAttribute("metadataHtml", html);
    RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward);
    requestDispatcher.forward(request, response);
}

From source file:com.edgenius.wiki.webapp.servlet.InstallServlet.java

/**
 * @param request//from w  w w  .j  av a  2s .c  o m
 * @param response
 * @throws ServletException
 * @throws IOException
 */
private void viewTableCreate(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //echo back value
    Server server = (Server) request.getSession().getAttribute("server");
    String dbType = server.getDbType();
    request.setAttribute("dbType", dbType);
    request.setAttribute("connectType", server.getDbConnectType());
    request.setAttribute("host", DBLoader.detectHost(dbType, server.getDbUrl()));
    request.setAttribute("dbname", DBLoader.detectDBName(dbType, server.getDbUrl()));
    request.setAttribute("userDBUrl", server.getDbUrl());
    request.setAttribute("username", server.getDbUsername());
    request.setAttribute("password", server.getDbPassword());
    request.setAttribute("jndi", server.getDbJNDI());
    request.getRequestDispatcher("/WEB-INF/pages/install/createtables.jsp").forward(request, response);
}

From source file:controller.ProductProcess.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    String fileName = processImage(request, response);

    String todo = request.getParameter("todo");
    String page = "";

    String name = (String) request.getAttribute("name");
    int quantity = Integer.parseInt((String) request.getAttribute("quantity"));
    double price = Double.parseDouble((String) request.getAttribute("price"));
    int categoryID = Integer.parseInt((String) request.getAttribute("category"));
    String description = (String) request.getAttribute("description");
    System.out.println(description);

    Category c = categoryDAO.getCategoryById(categoryID);

    switch (todo) {
    case "add":

        Watch w = new Watch(c, name, price);
        w.setDescription(description);//from  ww  w . ja  v  a  2  s .  co m
        w.setQuantity(quantity);
        w.setImage(fileName);
        watchDAO.addOrUpdateWatch(w);
        page = "admin-addProduct.jsp";
        break;
    case "edit":
        String image = request.getParameter("imageLink");
        int id = Integer.parseInt(request.getParameter("idWatch"));
        Watch w1 = new Watch(c, name, price);
        w1.setDescription(description);
        w1.setQuantity(quantity);
        w1.setImage(image);
        w1.setWatchId(id);
        watchDAO.addOrUpdateWatch(w1);
        page = "admin-product.jsp";
        break;
    }

    request.getRequestDispatcher(page).forward(request, response);
}

From source file:com.lrodriguez.SVNBrowser.java

private void doXpathQuery(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws ServletException, IOException {
    //example//from   ww  w  . j  a  va2 s  .  c  om
    //?xpathQuery=.[revision < 9315 and revision>9000 and author='echow' or author ='lrodrigu' and type='A']
    logDebug("dispatching xpath query: " + request.getParameter(XPATH_QUERY));

    SVNRepository repository = ((SVNHttpSession) request.getSession().getAttribute(SVNSESSION)).getRepository();
    Collection svnLogEntries = null;
    try {
        svnLogEntries = getSVNLogEntries(request, 0, repository.getDatedRevision(new Date()));
    } catch (SVNException e) {
        e.printStackTrace();
        request.setAttribute(ERROR, e.getErrorMessage());
        request.getRequestDispatcher(INDEX_JSP).forward(request, response);
        return;
    }
    List entriesList = new ArrayList();
    if (svnLogEntries != null && svnLogEntries.size() > 0) {
        List entryFacadeList = getAllEntries(svnLogEntries);

        JXPathContext context = JXPathContext.newContext(entryFacadeList);
        context.setLenient(true);
        for (Iterator iter = context.iterate(request.getParameter(XPATH_QUERY)); iter.hasNext();) {
            Object currEntryFacade = iter.next();
            entriesList.add(currEntryFacade);
        }
    }
    session.setAttribute(UNIQUE_ENTRIES, entriesList);
    request.getRequestDispatcher(INDEX_JSP).forward(request, response);
    return;
}

From source file:nl.surfnet.mujina.saml.SingleSignOnService.java

@SuppressWarnings("rawtypes")
@Override//from   ww w.  j  ava2  s.  co m
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    SAMLMessageContext messageContext = null;
    try {
        messageContext = adapter.extractSAMLMessageContext(request);
    } catch (MessageDecodingException mde) {
        logger.error("Exception decoding SAML message", mde);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    } catch (SecurityException se) {
        logger.error("Exception decoding SAML message", se);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    AuthnRequest authnRequest = (AuthnRequest) messageContext.getInboundSAMLMessage();

    try {
        validatorSuite.validate(authnRequest);
    } catch (ValidationException ve) {
        logger.warn("AuthnRequest Message failed Validation", ve);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    AuthnRequestInfo info = new AuthnRequestInfo(authnRequest.getAssertionConsumerServiceURL(),
            authnRequest.getID(), authnRequest.getIssuer().getValue());

    logger.debug("AuthnRequest {} verified.  Forwarding to SSOSuccessAuthnResponder", info);
    request.getSession().setAttribute(AuthnRequestInfo.class.getName(), info);

    logger.debug("request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION) is {}",
            request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION));

    logger.debug("forwarding to authnResponderURI: {}", authnResponderURI);

    request.getRequestDispatcher(authnResponderURI).forward(request, response);

}

From source file:com.netcracker.tss.web.servlet.customer.CustomerOrderTaxiEditDeleteServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//w  w w  .  j  av  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 {
    String action = request.getParameter("action");
    if (ACTION_EDIT_TAXI_ORDER.equals(action)) {
        taxiOrderId = Integer.parseInt(request.getParameter(TAXI_ORDER_ID));
        TaxiOrder taxiOrder = null;
        try {
            taxiOrder = new TaxiOrderDAO().get(taxiOrderId);
        } catch (NoSuchEntityException e) {
            e.printStackTrace();
        }
        request.getSession().setAttribute("taxiOrder", taxiOrder);
        redirectToEdit(request, response, null);
        return;
    }

    if (ACTION_DELETE_TAXI_ORDER.equals(action)) {
        TaxiOrderBeanLocal taxiOrderBeanLocal = BeansLocator.getInstance().getBean(TaxiOrderBeanLocal.class);
        taxiOrderId = Integer.parseInt(request.getParameter(TAXI_ORDER_ID));
        taxiOrderBeanLocal.refuseTaxiOrder(taxiOrderId);
        User user = UserUtils.findCurrentUser();
        if (taxiOrderBeanLocal.countOrdersByStatus(user, Status.REFUSED) >= 3) {
            UserBeanLocal userBeanLocal = BeansLocator.getInstance().getBean(UserBeanLocal.class);
            List<Roles> rs = new ArrayList<>();
            rs.add(Roles.BANNED);
            userBeanLocal.editRoles(user.getId(), rs);
            request.setAttribute("pageContent", "content/banned.jsp");
            request.getRequestDispatcher("/WEB-INF/views/customer/customer-template.jsp").forward(request,
                    response);

        } else {
            request.setAttribute("taxiOrderId", taxiOrderId);
            request.setAttribute("pageContent", "content/refuse.jsp");
            request.getRequestDispatcher("/WEB-INF/views/customer/customer-template.jsp").forward(request,
                    response);
        }
    }

}

From source file:controllers.ControladorFotoCoin.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w w w  . j a  v  a 2 s . c om*/
 * @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 {
    int idMatch = Integer.parseInt(request.getParameter("idMatch"));
    String userPath = "";
    String UPLOAD_DIRECTORY = "/Users/patriciacuevas/NetBeansProjects/PerfectMatchTis2/web/fotosUsuarios";
    if (ServletFileUpload.isMultipartContent(request)) {
        String pathFile = "";
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    pathFile = UPLOAD_DIRECTORY + File.separator + name;
                    item.write(new File(pathFile));

                }
            }

            PmtMatchDTO match = new PmtMatchDTO();
            match.setMatId(idMatch);

            PmtIntercambioFotosDTO intercambio = new PmtIntercambioFotosDTO();
            intercambio.setInfRutaUsuarioCoincidente(pathFile);
            intercambio.setMat(match);

            intercambio.guardar(intercambio);

            request.setAttribute("message", "Su foto fue enviada exitosamente");
            userPath = "cliente";

        } catch (Exception ex) {
            request.setAttribute("message", "Error al cargar el archivo");
            userPath = "enviarFotoCoincidente";
        }

        String url = "WEB-INF/view/" + userPath + ".jspf";
        RequestDispatcher rd = request.getRequestDispatcher(url);
        rd.forward(request, response);
    }
}

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

/**
 * The doPost method of the servlet. <br>
 * /*from   w w w.j  a v  a 2s .c o 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 {
    String deleteMessage = null;
    String messageType = null;
    HttpSession httpSession = request.getSession();

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

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

    String docid = request.getParameter("docid");
    if (docid != null) {
        String[] tokens = docid.split("\\.");
        if (tokens != null && tokens.length >= 2) {
            String scope = tokens[0];
            String identifierStr = tokens[1];
            Integer identifier = Integer.parseInt(identifierStr);

            if (uid.equals("public")) {
                messageType = "warning";
                request.setAttribute("message", LOGIN_WARNING);
            } else {
                try {
                    DataPackageManagerClient dpmc = new DataPackageManagerClient(uid);
                    dpmc.deleteReservation(scope, identifier);
                    deleteMessage = String.format(
                            "Reservation for data package identifier '<b>%s</b>' has been deleted.", docid);
                    messageType = "info";
                } catch (Exception e) {
                    handleDataPortalError(logger, e);
                }
            }
        }
    }

    request.setAttribute("deleteMessage", deleteMessage);
    request.setAttribute("messageType", messageType);

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

}