Example usage for javax.servlet RequestDispatcher forward

List of usage examples for javax.servlet RequestDispatcher forward

Introduction

In this page you can find the example usage for javax.servlet RequestDispatcher forward.

Prototype

public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException;

Source Link

Document

Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.

Usage

From source file:dbaccess.servlets.ModifyServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  www . j a  va2 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 {

    // extract request parameters to a book data bean using
    // apache BeanUtils
    BookData bookData = new BookData();
    try {
        BeanUtils.populate(bookData, request.getParameterMap());
        String nextPage = null;

        // set up the bean as request parameter
        request.setAttribute("bookData", bookData);

        // ADD A BOOK
        if (request.getParameter("add") != null) {
            if (bookData.isComplete()) {
                if (DBHelper.addBook(em, utx, bookData)) {
                    nextPage = "/index.jsp";
                } else {
                    nextPage = "/failedAdd.jsp";
                }
            } else {
                nextPage = "/failedAdd.jsp";
            }
        }
        // DELETE A BOOK
        else if (request.getParameter("delete") != null) {
            if (DBHelper.deleteBook(em, utx, bookData)) {
                nextPage = "/index.jsp";
            } else {
                nextPage = "/failedDelete.jsp";
            }

        }
        // GO TO KIDS PAGE
        else if (request.getParameter("kidspage") != null) {
            if (DBHelper.getAllKidsBookIDS(em) != null) {
                nextPage = "/KidsBooksPage";
            } else {
                nextPage = "/emptyDatabaseError.jsp";
            }
        }

        // GO TO TECH PAGE
        else if (request.getParameter("techpage") != null) {
            if (DBHelper.getAllTechBookIDS(em) != null) {
                nextPage = "/TechBooksPage";
            } else {
                nextPage = "/emptyDatabaseError.jsp";
            }
        }

        // SHOW RESULTS in table, if any
        fillTable(em, request, nextPage);

        RequestDispatcher dispatcher = request.getRequestDispatcher(nextPage);
        dispatcher.forward(request, response);
    } catch (IllegalAccessException | InvocationTargetException | ServletException | IOException ex) {
    }

}

From source file:eu.eidas.node.service.ServiceExceptionHandlerServlet.java

/**
 * Prepares exception redirection, or if no information is available to redirect, prepares the exception to be
 * displayed. Also, clears the current session object, if not needed.
 *
 * @return {ERROR} if there is no URL to return to, {SUCCESS} otherwise.
 *///from   w  w w . jav  a  2 s.  c  o m
private void handleError(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    /*
      Current exception.
     */
    AbstractEIDASException exception;
    /*
      URL to redirect the citizen to.
     */
    String errorRedirectUrl;

    String retVal = NodeViewNames.INTERNAL_ERROR.toString();
    try {
        // Prevent cookies from being accessed through client-side script.
        setHTTPOnlyHeaderToSession(false, request, response);

        //Set the Exception
        exception = (AbstractEIDASException) request.getAttribute("javax.servlet.error.exception");
        prepareErrorMessage(exception, request);
        errorRedirectUrl = prepareSession(exception, request);
        request.setAttribute(NodeParameterNames.EXCEPTION.toString(), exception);

        if (!StringUtils.isBlank(exception.getSamlTokenFail()) && null != errorRedirectUrl) {
            retVal = NodeViewNames.SUBMIT_ERROR.toString();
        } else if (exception instanceof EidasNodeException || exception instanceof EIDASServiceException) {
            retVal = NodeViewNames.PRESENT_ERROR.toString();
        } else if (exception instanceof InternalErrorEIDASException) {
            LOG.debug("BUSINESS EXCEPTION - null redirectUrl or SAML response");
            retVal = NodeViewNames.INTERNAL_ERROR.toString();
        } else {
            LOG.warn("exception not recognized so internal error page shown", exception);
            retVal = NodeViewNames.INTERNAL_ERROR.toString();
        }

    } catch (Exception e) {
        LOG.info("BUSINESS EXCEPTION: in exception handler: " + e, e);
    }
    //Forward to error page
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(retVal);
    response.setStatus(HttpServletResponse.SC_OK);
    dispatcher.forward(request, response);
}

From source file:mx.org.cedn.avisosconagua.engine.processors.Init.java

@Override
public void invokeForm(HttpServletRequest request, HttpServletResponse response, BasicDBObject data,
        String parts[]) throws ServletException, IOException {
    HashMap<String, String> datos = new HashMap<>();
    String prevIssue = null;/*from  w  ww .jav  a  2s.  com*/

    if (null != data) {
        for (String key : data.keySet()) {
            datos.put(key, data.getString(key));
        }
    }

    //Put nhcLinks in map and get advisory for tracking
    BasicDBObject advice = mi.getAdvice((String) request.getSession(true).getAttribute("internalId"));
    if (null != advice) {
        //Get nhcLinks
        BasicDBObject section = (BasicDBObject) advice.get("precapture");
        if (null != section) {
            datos.put("nhcForecastLink", section.getString("nhcForecastLink"));
            datos.put("nhcPublicLink", section.getString("nhcPublicLink"));
            prevIssue = section.getString("previousIssue");
        }
    }

    //Advice without init saved and for tracking
    if (advice != null && advice.get("init") == null) {
        if (prevIssue != null) {
            BasicDBObject previous = mi.getAdvice(prevIssue);
            if (previous != null) {
                //System.out.println("Putting previous data from "+prevIssue);
                BasicDBObject initSection = (BasicDBObject) previous.get("init");
                if (initSection != null) {
                    //Set current values to previous values
                    datos.put("eventDescriptionHTML", initSection.getString("eventDescriptionHTML", ""));
                    datos.put("areaDescription", initSection.getString("areaDescription", ""));
                    datos.put("eventRisk", initSection.getString("eventRisk", ""));
                    datos.put("eventComments", initSection.getString("eventComments", ""));
                }
            }
        }
    }

    request.setAttribute("data", datos);
    request.setAttribute("bulletinType", parts[2]);
    String url = "/jsp/init.jsp";
    if (parts[2].endsWith("dp")) {
        url = "/jsp/initdp.jsp";
    }
    RequestDispatcher rd = request.getRequestDispatcher(url);
    rd.forward(request, response);
}

From source file:com.alfaariss.oa.util.saml2.binding.post.JSPHTTPPostEncoder.java

private void postEncode(SAMLMessageContext messageContext, String endpointURL) throws MessageEncodingException {

    InTransport inTransport = messageContext.getInboundMessageTransport();
    HttpServletRequest request = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
    OutTransport outTransport = messageContext.getOutboundMessageTransport();
    HttpServletResponse response = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();

    HTTPOutTransport out = (HTTPOutTransport) messageContext.getOutboundMessageTransport();
    HTTPTransportUtils.addNoCacheHeaders(out);
    HTTPTransportUtils.setUTF8Encoding(out);

    request.setAttribute("action", endpointURL);

    if (messageContext.getOutboundSAMLMessage().getDOM() == null) {
        marshallMessage(messageContext.getOutboundSAMLMessage());
    }//from  w  w  w  . j  a  v  a2 s  .  c om
    String messageXML = XMLHelper.nodeToString(messageContext.getOutboundSAMLMessage().getDOM());

    try {
        String encodedMessage = Base64.encodeBytes(messageXML.getBytes(SAML2Constants.CHARSET),
                Base64.DONT_BREAK_LINES);

        if (messageContext.getOutboundSAMLMessage() instanceof RequestAbstractType) {
            request.setAttribute("SAMLRequest", encodedMessage);
        } else if (messageContext.getOutboundSAMLMessage() instanceof StatusResponseType) {
            request.setAttribute("SAMLResponse", encodedMessage);
        } else {
            _logger.warn("Invalid outbound message, not a RequestAbstractType or StatusResponseType");
            throw new MessageEncodingException("Invalid outbound message");
        }

        String relayState = messageContext.getRelayState();
        if (checkRelayState(relayState)) {
            request.setAttribute("RelayState", relayState);
        }

        RequestDispatcher oDispatcher = request.getRequestDispatcher(_sTemplateLocation);
        oDispatcher.forward(request, response);
    } catch (UnsupportedEncodingException e) {
        _logger.warn("Could not encode message, charset: " + SAML2Constants.CHARSET, e);
        throw new MessageEncodingException("Could not encode message", e);
    } catch (ServletException e) {
        _logger.warn("Could not process forward to JSP due to Servlet Error", e);
        throw new MessageEncodingException("Could not process forward to JSP");
    } catch (IOException e) {
        _logger.warn("Could not process forward to JSP due to I/O Error", e);
        throw new MessageEncodingException("Could not process forward to JSP");
    }
}

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

private void doNotFound(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    VitroRequest vreq = new VitroRequest(req);

    ApplicationBean appBean = vreq.getAppBean();

    //set title before we do the highlighting so we don't get markup in it.
    req.setAttribute("title", "not found");
    res.setStatus(HttpServletResponse.SC_NOT_FOUND);

    String css = "<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"" + appBean.getThemeDir()
            + "css/entity.css\"/>"
            + "<script language='JavaScript' type='text/javascript' src='js/toggle.js'></script>";
    req.setAttribute("css", css);

    req.setAttribute("bodyJsp", "/" + Controllers.ENTITY_NOT_FOUND_JSP);

    RequestDispatcher rd = req.getRequestDispatcher(Controllers.BASIC_JSP);
    rd.forward(req, res);
}

From source file:Controller.CreateTemplate.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w w  w.ja va 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 doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("Form Create Container");
    String contHostname = request.getParameter("contFinalHostname");
    int vmId = data.GetVmIdByHostname(contHostname);
    int idCont = data.GetContIdByHostname(contHostname);
    int version = data.GetLastContTempVersion(idCont);
    boolean created = false;

    /********Create the template with ssh command******/
    String myCommand = "vzctl set " + vmId + " --ipdel all --save;vzctl stop " + vmId
            + ";cd /var/lib/vz/private/" + vmId + ";tar -czvf /var/lib/vz/template/cache/" + contHostname + "_"
            + version + ".tar.gz .";
    System.out.println("Commande Template : " + myCommand);
    JSch jsch = new JSch();
    Session session;
    try {
        session = jsch.getSession("root", "149.202.70.57", 22);

        session.setPassword("***"); //Set the true Password

        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();

        ChannelExec channel = (ChannelExec) session.openChannel("exec");
        BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
        channel.setCommand(myCommand);
        channel.connect();
        String msg = null;
        while ((msg = in.readLine()) != null) {
            System.out.println(msg);
        }

        channel.disconnect();
        session.disconnect();
        System.out.println("** Template Created !! **");
        created = true;
    } catch (JSchException ex) {
        Logger.getLogger(FormCreatContenaire.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("**Error cration Template !!**");
    }

    if (created) {
        String name = contHostname + "_" + version + ".tar.gz";
        /* Rcupration de la session depuis la requte */
        HttpSession webSession = request.getSession();
        String user = (String) webSession.getAttribute(ATT_SESSION_EMAIL);
        System.out.println("***************USER : " + user);
        int idUser = data.GetIdByEmail(user);
        String insert = data.AddCustomTemplate(idCont, version, name, idUser);
        System.out.println(insert);

        /*Remise de l'adresse IP*/
        Iaas iaas;
        try {
            iaas = new Iaas();
            Container cont = iaas.getContainer(vmId);
            cont.setVmid(Integer.toString(vmId));
            System.out.println("after create Template id VM : " + vmId);
            System.out.println("after create Template getIdcont : " + cont.getVmid());
            String adress = data.GetIpAdressByVMId(vmId);
            cont.setIp_address(adress);
            iaas.UpdateContainer(cont);
            System.out.println("after create Template adress cont : " + cont.getIp_address());
        } catch (JSONException ex) {
            Logger.getLogger(CreateTemplate.class.getName()).log(Level.SEVERE, null, ex);
        } catch (LoginException ex) {
            Logger.getLogger(CreateTemplate.class.getName()).log(Level.SEVERE, null, ex);
        }

        RequestDispatcher rd = request.getRequestDispatcher("ListTemplates");
        rd.forward(request, response);
    } else {
        request.getRequestDispatcher("errorTemplate.jsp").forward(request, response);
    }
}

From source file:controller.uploadPergunta6.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w w  w .java  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 {

    String idLocal = (String) request.getParameter("idLocal");

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

    String name = "";
    //process only if its multipart content
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

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

            //File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    expressao = expressao.replace("+", "%2B");
    RequestDispatcher view = getServletContext().getRequestDispatcher(
            "/novoLocalPergunta6?id=" + idLocal + "&nomeArquivo=" + name + "&expressao=" + expressao);
    view.forward(request, response);

    //        request.getRequestDispatcher("/novoLocalPergunta3?id="+idLocal+"&fupload=1&nomeArquivo="+name).forward(request, response);
    // request.getRequestDispatcher("/novoLocalPergunta4?id="+idLocal+"&nomeArquivo="+name).forward(request, response);

}

From source file:com.sun.portal.portletcontainer.driver.admin.UploadServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Initialize DesktopMessages' Resource Bundle
    DesktopMessages.init(getLanguage(request));
    try {/* w  ww  .  j  av a2  s .  c o  m*/
        uploadFile(request, response);
    } catch (PortletRegistryException pre) {
        logger.log(Level.SEVERE, "PSPCD_CSPPD0029", pre);
    } catch (FileUploadException e) {
        logger.log(Level.SEVERE, "PSPCD_CSPPD0029", e);
    } finally {
        RequestDispatcher reqd = context.getRequestDispatcher("/portlet/jsp/jsr/deployer.jsp");
        reqd.forward(request, response);
    }
}

From source file:org.apache.tiles.servlet.context.ServletTilesRequestContext.java

/**
 * Forwards to a path.//  w ww .  jav  a2 s  .  co  m
 *
 * @param path The path to forward to.
 * @throws IOException If something goes wrong during the operation.
 */
private void forward(String path) throws IOException {
    RequestDispatcher rd = request.getRequestDispatcher(path);
    try {
        rd.forward(request, response);
    } catch (ServletException ex) {
        LOG.error("Servlet Exception while including path", ex);
        throw new IOException("Error including path '" + path + "'. " + ex.getMessage());
    }
}

From source file:com.mockey.ui.UploadConfigurationServlet.java

/**
 * //from w w  w . ja v  a2s.  c  o m
 * 
 * @param req
 *            basic request
 * @param resp
 *            basic resp
 * @throws ServletException
 *             basic
 * @throws IOException
 *             basic
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String url = null;
    String definitionsAsString = null;
    String taglistValue = "";

    // ***********************************
    // STEP #1 - READ DATA
    // ***********************************
    if (req.getParameter("viaUrl") != null) {
        url = req.getParameter("url");
        taglistValue = req.getParameter("taglist");
        try {
            InputStream fstream = new URL(url).openStream();
            if (fstream != null) {

                BufferedReader br = new BufferedReader(
                        new InputStreamReader(fstream, Charset.forName(HTTP.UTF_8)));
                StringBuffer inputString = new StringBuffer();
                // Read File Line By Line
                String strLine = null;
                // READ FIRST
                while ((strLine = br.readLine()) != null) {
                    // Print the content on the console
                    inputString.append(new String(strLine.getBytes(HTTP.UTF_8)));
                }
                definitionsAsString = inputString.toString();
            }
        } catch (Exception e) {
            logger.error("Unable to reach url: " + url, e);
            Util.saveErrorMessage("Unable to reach url: " + url, req);
        }
    } else {
        byte[] data = null;
        try {
            // STEP 1. GATHER UPLOADED ITEMS
            // Create a new file upload handler
            DiskFileUpload upload = new DiskFileUpload();

            // Parse the request
            List<FileItem> items = upload.parseRequest(req);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (!item.isFormField()) {

                    data = item.get();

                } else {

                    String name = item.getFieldName();
                    if ("taglist".equals(name)) {
                        taglistValue = item.getString();
                    }

                }
            }
            if (data != null && data.length > 0) {
                definitionsAsString = new String(data);
            }
        } catch (Exception e) {
            logger.error("Unable to read or parse file: ", e);
            Util.saveErrorMessage("Unable to upload or parse file.", req);
        }
    }

    // ***********************************
    // STEP #2 - PERSIST DATA
    // ***********************************
    try {

        if (definitionsAsString != null) {
            MockeyXmlFileManager configurationReader = new MockeyXmlFileManager();
            ServiceMergeResults results = configurationReader.loadConfigurationWithXmlDef(definitionsAsString,
                    taglistValue);

            Util.saveSuccessMessage("Service definitions uploaded.", req);
            req.setAttribute("conflicts", results.getConflictMsgs());
            req.setAttribute("additions", results.getAdditionMessages());
        } else {
            Util.saveErrorMessage("Unable to upload or parse empty file.", req);
        }
    } catch (Exception e) {
        Util.saveErrorMessage("Unable to upload or parse file.", req);
    }

    RequestDispatcher dispatch = req.getRequestDispatcher("/upload.jsp");
    dispatch.forward(req, resp);
}