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:com.centurylink.mdw.hub.servlet.RestServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    CodeTimer timer = new CodeTimer("RestServlet.doPost()", true);

    if (request.getPathInfo() != null && request.getPathInfo().startsWith("/SOAP")) {
        // forward to SOAP servlet
        RequestDispatcher requestDispatcher = request.getRequestDispatcher(request.getPathInfo());
        requestDispatcher.forward(request, response);
        return;//  ww  w  .  j a v  a  2 s .  co  m
    }

    Map<String, String> metaInfo = buildMetaInfo(request);
    try {
        String responseString = handleRequest(request, response, metaInfo);
        response.getOutputStream().print(responseString);
    } catch (ServiceException ex) {
        logger.severeException(ex.getMessage(), ex);
        response.setStatus(ex.getCode());
        response.getWriter().println(createErrorResponseMessage(request, metaInfo, ex));
    } finally {
        timer.stopAndLogTiming("");
    }
}

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

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

    OntologyDao daoObj = vreq.getFullWebappDaoFactory().getOntologyDao();
    List<Ontology> ontologiesObj = daoObj.getAllOntologies();
    ArrayList<String> prefixList = new ArrayList<String>();

    if (ontologiesObj != null && ontologiesObj.size() > 0) {
        for (Ontology ont : ontologiesObj) {
            prefixList.add(ont.getPrefix() == null ? "(not yet specified)" : ont.getPrefix());
            prefixList.add(ont.getURI() == null ? "" : ont.getURI());
        }//from   w  w  w.  j a v  a 2 s .  com
    } else {
        prefixList.add("<strong>" + "No Ontologies added" + "</strong>");
        prefixList.add("<strong>" + "Load Ontologies" + "</strong>");
    }

    req.setAttribute("prefixList", prefixList);

    // nac26: 2009-09-25 - this was causing problems in safari on localhost installations because the href did not include the context.  The edit.css is not being used here anyway (or anywhere else for that matter)
    // req.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\""+portal.getThemeDir()+"css/edit.css\"/>");
    req.setAttribute("title", "SPARQL Query");
    req.setAttribute("bodyJsp", "/admin/sparqlquery/sparqlForm.jsp");

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

From source file:org.xine.marketplace.frontend.views.security.JsfLoginUrlAuthenticationEntryPoint.java

/**
 * Performs the redirect (or forward) to the login form URL.
 *///from  ww  w  .  ja v a2 s. co m
@Override
public void commence(final HttpServletRequest request, final HttpServletResponse response,
        final AuthenticationException authException) throws IOException, ServletException {

    String redirectUrl = null;

    if (this.useForward) {

        if (this.forceHttps && "http".equals(request.getScheme())) {
            // First redirect the current request to HTTPS.
            // When that request is received, the forward to the login page will be used.
            redirectUrl = buildHttpsRedirectUrlForRequest(request);
        }

        if (redirectUrl == null) {
            final String loginForm = determineUrlToUseForThisRequest(request, response, authException);

            if (logger.isDebugEnabled()) {
                logger.debug("Server side forward to: " + loginForm);
            }

            final RequestDispatcher dispatcher = request.getRequestDispatcher(loginForm);

            dispatcher.forward(request, response);

            return;
        }
    } else {
        // redirect to login page. Use https if forceHttps true

        redirectUrl = buildRedirectUrlToLoginPage(request, response, authException);

    }

    this.redirectStrategy.sendRedirect(request, response, redirectUrl);
}

From source file:Service.java

/**
 * When the servlet receives a GET request.
 *//*from  w ww  .j ava2s .  c  o  m*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //It always returns the service.jps page.
    RequestDispatcher view = request.getRequestDispatcher(SERVICE_JSP);
    view.forward(request, response);
}

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

/**
 * The doPost method of the servlet. <br>
 * /*from  ww  w .  j a va  2  s  .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 forward = "./searchResult.jsp";
    String html = "";
    TermsList termsList = null;
    String termsListHTML = "";
    String xml = null;

    HttpSession httpSession = request.getSession();

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

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

    String boundaryContained = request.getParameter("boundaryContained");
    String boundsChangedCount = request.getParameter("boundsChangedCount");
    String dateField = request.getParameter("dateField");
    String startDate = request.getParameter("startDate");
    String endDate = request.getParameter("endDate");
    String datesContained = request.getParameter("datesContained");
    String creatorOrganization = request.getParameter("creatorOrganization");
    String creatorName = request.getParameter("creatorName");
    String locationName = request.getParameter("locationName");
    String namedTimescale = request.getParameter("namedTimescale");
    String[] siteValues = request.getParameterValues("siteValues");
    String subjectField = request.getParameter("subjectField");
    String subjectValue = request.getParameter("subjectValue");
    String specific = request.getParameter("specific");
    String related = request.getParameter("related");
    String relatedSpecific = request.getParameter("relatedSpecific");
    String ecotrends = request.getParameter("ecotrends");
    String landsat5 = request.getParameter("landsat5");
    String taxon = request.getParameter("taxon");
    String identifier = request.getParameter("identifier");

    String northBound = request.getParameter("northBound");
    String southBound = request.getParameter("southBound");
    String eastBound = request.getParameter("eastBound");
    String westBound = request.getParameter("westBound");

    boolean isBoundaryContainedChecked = (boundaryContained != null);
    boolean isDatesContainedChecked = (datesContained != null);
    boolean isIncludeEcotrendsChecked = (ecotrends != null);
    boolean isIncludeLandsat5Checked = (landsat5 != null);
    boolean isSpecificChecked = (specific != null);
    boolean isRelatedChecked = (related != null);
    boolean isRelatedSpecificChecked = (relatedSpecific != null);

    SolrAdvancedSearch solrAdvancedSearch = new SolrAdvancedSearch(creatorName, creatorOrganization, dateField,
            startDate, endDate, namedTimescale, siteValues, subjectField, subjectValue,
            isIncludeEcotrendsChecked, isIncludeLandsat5Checked, isDatesContainedChecked, isSpecificChecked,
            isRelatedChecked, isRelatedSpecificChecked, taxon, identifier, isBoundaryContainedChecked,
            boundsChangedCount, northBound, southBound, eastBound, westBound, locationName);

    try {
        xml = solrAdvancedSearch.executeSearch(uid);
        String queryText = solrAdvancedSearch.getQueryString();
        httpSession.setAttribute("queryText", queryText);

        termsList = solrAdvancedSearch.getTermsList();
        if ((termsList != null) && (termsList.size() > 0)) {
            termsListHTML = termsList.toHTML();
            httpSession.setAttribute("termsListHTML", termsListHTML);
        }

        ResultSetUtility resultSetUtility = null;
        if (uid.equals("public")) {
            resultSetUtility = new ResultSetUtility(xml, Search.DEFAULT_SORT);
        } else {
            boolean isSavedDataPage = false;
            SavedData savedData = new SavedData(uid);
            resultSetUtility = new ResultSetUtility(xml, Search.DEFAULT_SORT, savedData, isSavedDataPage);
        }

        String mapButtonHTML = resultSetUtility.getMapButtonHTML();
        request.setAttribute("mapButtonHTML", mapButtonHTML);
        //String relevanceHTML = resultSetUtility.getRelevanceHTML();
        //request.setAttribute("relevanceHTML", relevanceHTML);
        html = resultSetUtility.xmlToHtmlTable(cwd + xslpath);
        request.setAttribute("searchresult", html);
        RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward);
        requestDispatcher.forward(request, response);
    } catch (Exception e) {
        handleDataPortalError(logger, e);
    }
}

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

private void prepareExportSelectionPage(VitroRequest vreq, HttpServletResponse response) {
    vreq.setAttribute("bodyJsp", Controllers.EXPORT_SELECTION_JSP);
    RequestDispatcher dispatcher = vreq.getRequestDispatcher(Controllers.BASIC_JSP);
    try {/*from  w  w w  . j  a v a2s . c  om*/
        dispatcher.forward(vreq, response);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:br.com.sg.security.SgLoginUrlAuthenticationEntryPoint.java

/**
 * Performs the redirect (or forward) to the login form URL.
 *//*from  w w  w . jav a  2s.co m*/
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String redirectUrl = null;

    if (useForward) {

        if (forceHttps && "http".equals(request.getScheme())) {
            // First redirect the current request to HTTPS.
            // When that request is received, the forward to the login page
            // will be used.
            redirectUrl = buildHttpsRedirectUrlForRequest(httpRequest);
        }

        if (redirectUrl == null) {
            String loginForm = determineUrlToUseForThisRequest(httpRequest, httpResponse, authException);

            if (logger.isDebugEnabled()) {
                logger.debug("Server side forward to: " + loginForm);
            }

            RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(loginForm);

            dispatcher.forward(request, response);

            return;
        }
    } else {
        // redirect to login page. Use https if forceHttps true
        redirectUrl = buildRedirectUrlToLoginPage(httpRequest, httpResponse, authException);
    }

    redirectStrategy.sendRedirect(httpRequest, httpResponse, redirectUrl);
}

From source file:com.google.step2.example.consumer.servlet.LoginServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    log.info("Login Servlet Post");

    // posted means they're sending us an OpenID4
    StringBuffer realmBuf = new StringBuffer(req.getScheme()).append("://").append(req.getServerName());

    if ((req.getScheme().equalsIgnoreCase("http") && req.getServerPort() != 80)
            || (req.getScheme().equalsIgnoreCase("https") && req.getServerPort() != 443)) {
        realmBuf.append(":").append(req.getServerPort());
    }// w  w  w  . java2  s .  c om

    String realm = realmBuf.toString();
    String returnToUrl = new StringBuffer(realm).append(req.getContextPath()).append(REDIRECT_PATH).toString();

    // this is magic - normally this would also fall out of the discovery:
    OAuthAccessor accessor = null;

    // Fetch an unauthorized OAuth request token to test authorizing
    if (YES_STRING.equals(req.getParameter("oauth"))) {
        try {
            accessor = providerStore.getOAuthAccessor("google");
            accessor = oauthConsumerUtil.getRequestToken(accessor);

            // TODO(sweis): Put this string contstant somewhere that makes sense
            String oauthTestEndpoint = (String) accessor.getProperty("oauthTestEndpoint");
            if (oauthTestEndpoint != null) {
                realm = oauthTestEndpoint;
                returnToUrl = oauthTestEndpoint;
            }
        } catch (ProviderInfoNotFoundException e) {
            throw new ServletException(e);
        } catch (OAuthException e) {
            throw new ServletException(e);
        } catch (URISyntaxException e) {
            throw new ServletException(e);
        }
    }

    // we assume that the user typed an identifier for an IdP, not for a user
    IdpIdentifier openId = new IdpIdentifier(req.getParameter("openid"));

    AuthRequestHelper helper = consumerHelper.getAuthRequestHelper(openId, returnToUrl.toString());

    helper.requestUxIcon(true);

    if (accessor != null) {
        log.debug("Requesting OAuth scope : " + (String) accessor.getProperty("scope"));
        helper.requestOauthAuthorization(accessor.consumer.consumerKey, (String) accessor.getProperty("scope"));
    }

    if (YES_STRING.equals(req.getParameter("email"))) {
        log.debug("Requesting AX email");
        helper.requestAxAttribute(Step2.AxSchema.EMAIL, true);
    }

    if (YES_STRING.equals(req.getParameter("country"))) {
        log.debug("Requesting AX country");
        helper.requestAxAttribute(Step2.AxSchema.COUNTRY, true);
    }

    if (YES_STRING.equals(req.getParameter("language"))) {
        log.debug("Requesting AX country");
        helper.requestAxAttribute(Step2.AxSchema.LANGUAGE, true);
    }

    if (YES_STRING.equals(req.getParameter("firstName"))) {
        log.debug("Requesting AX country");
        helper.requestAxAttribute(Step2.AxSchema.FIRST_NAME, true);
    }

    if (YES_STRING.equals(req.getParameter("lastName"))) {
        log.debug("Requesting AX country");
        helper.requestAxAttribute(Step2.AxSchema.LAST_NAME, true);
    }

    HttpSession session = req.getSession();
    AuthRequest authReq = null;
    try {
        authReq = helper.generateRequest();
        authReq.setRealm(realm);

        // add PAPE, if requested
        if (YES_STRING.equals(req.getParameter("reauth"))) {
            log.debug("Requesting PAPE reauth");
            PapeRequest pape = PapeRequest.createPapeRequest();
            pape.setMaxAuthAge(1);
            authReq.addExtension(pape);
        }

        session.setAttribute("discovered", helper.getDiscoveryInformation());
    } catch (DiscoveryException e) {
        StringBuffer errorMessage = new StringBuffer("Could not discover OpenID endpoint.");
        errorMessage.append("\n\n").append("Check if URL is valid: ");
        errorMessage.append(openId).append("\n\n");
        errorMessage.append("Stack Trace:\n");
        for (StackTraceElement s : e.getStackTrace()) {
            errorMessage.append(s.toString()).append('\n');
        }
        resp.sendError(400, errorMessage.toString());
        return;
    } catch (MessageException e) {
        throw new ServletException(e);
    } catch (ConsumerException e) {
        throw new ServletException(e);
    }
    if (YES_STRING.equals(req.getParameter("usePost"))) {
        // using POST
        req.setAttribute("message", authReq);
        RequestDispatcher d = req.getRequestDispatcher("/WEB-INF/formredirection.jsp");
        d.forward(req, resp);
    } else {
        // using GET
        resp.sendRedirect(authReq.getDestinationUrl(true));
    }
}

From source file:es.uma.inftel.blog.servlet.PerfilServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w w  w  .  j av  a  2s .  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 {

    request.setCharacterEncoding("UTF-8");

    BaseView baseView = new BaseView();
    BaseViewFacade<BaseView> baseViewFacade = new BaseViewFacade<>(postFacade);
    baseViewFacade.initView(baseView);

    RequestDispatcher requestDispatcher = request.getRequestDispatcher("perfil.jsp");
    String password = request.getParameter("password");
    if (password == null) {
        request.setAttribute("perfilView", baseView);
        requestDispatcher.forward(request, response);
    }

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

    Part filePart = request.getPart("avatar");
    byte[] avatar = null;
    if (!filePart.getSubmittedFileName().isEmpty()) {
        InputStream inputStream = filePart.getInputStream();
        avatar = IOUtils.toByteArray(inputStream);
    }

    HttpSession session = request.getSession();
    Usuario usuario = (Usuario) session.getAttribute("usuario");

    modificarUsuario(usuario, password, email, avatar);
    response.sendRedirect("perfil");

}

From source file:Control.Upload.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w  ww.  j  av a 2 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 doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    int k = 0;
    String userid = null;
    ArrayList<String> nameImage = new ArrayList<String>();
    String album = null;
    ArrayList<String> typeImage = new ArrayList<String>();
    ArrayList<Integer> priceImage = new ArrayList<Integer>();

    String tempPath = "/temp";
    String absoluteTempPath = this.getServletContext().getRealPath(tempPath);
    if (absoluteTempPath == null) {
        String serverContext = this.getServletContext().getRealPath("/");
        String createPath = serverContext + "temp";
        File tempfolder = new File(createPath);
        tempfolder.mkdir();
        absoluteTempPath = this.getServletContext().getRealPath(tempPath);
    }
    String absoluteFilePath = this.getServletContext().getRealPath("/data/Image");
    int maxFileSize = 50 * 1024;
    int maxMemSize = 4 * 1024;

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        File file = new File(absoluteTempPath);

        factory.setRepository(file);
        ServletFileUpload upload = new ServletFileUpload(factory);

        //upload.setProgressListener(new MyProgressListener(out));
        List<FileItem> items = upload.parseRequest(request);

        if (items.size() > 0) {
            for (int i = items.size() - 1; i >= 0; i--) {
                if (items.get(i).isFormField()) {
                    if (null != items.get(i).getFieldName())
                        switch (items.get(i).getFieldName()) {
                        case "userid":
                            userid = items.get(i).getString();
                            break;
                        case "nameImageUpload":
                            nameImage.add(items.get(i).getString());
                            break;
                        case "albumUpload":
                            album = items.get(i).getString();
                            break;
                        case "typeImageUpload":
                            typeImage.add(items.get(i).getString());
                            break;
                        case "priceImageUpload":
                            priceImage.add(parseInt(items.get(i).getString()));
                            break;
                        default:
                            break;
                        }
                } else if ("images".equals(items.get(i).getFieldName())) {
                    if (!"".equals(items.get(i).getName()) && !items.get(i).getName().isEmpty()) {
                        String extension = null;
                        String newLink;
                        Integer newIntIdImage = Image.listImg.size() + k;
                        String newIdImage = newIntIdImage.toString();
                        if (items.get(i).getName().endsWith("jpg")) {
                            newLink = "/Image/" + newIdImage + ".jpg";
                            file = new File(absoluteFilePath + "//" + newIdImage + ".jpg");
                        } else if (items.get(i).getName().endsWith("JPG")) {
                            newLink = "/Image/" + newIdImage + ".jpg";
                            file = new File(absoluteFilePath + "//" + newIdImage + ".jpg");
                        } else if (items.get(i).getName().endsWith("png")) {
                            newLink = "/Image/" + newIdImage + ".png";
                            file = new File(absoluteFilePath + "//" + newIdImage + ".png");
                        } else if (items.get(i).getName().endsWith("PNG")) {
                            newLink = "/Image/" + newIdImage + ".png";
                            file = new File(absoluteFilePath + "//" + newIdImage + ".png");
                        } else {
                            return;
                        }
                        boolean check = Image_DAL.addImage(newLink, userid, album, nameImage.get(0),
                                typeImage.get(0), priceImage.get(0));
                        nameImage.remove(0);
                        typeImage.remove(0);
                        priceImage.remove(0);
                        if (check) {
                            items.get(i).write(file);
                            k++;
                        }
                    }
                } else {
                }
            }
            request.setAttribute("user", userid);
            RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/index");
            dispatcher.forward(request, response);
            return;
        }
        for (int i = items.size() - 1; i >= 0; i--)
            if (items.get(i).isFormField())
                if ("userid".equals(items.get(i).getFieldName()))
                    userid = items.get(i).getString();

        request.setAttribute("error", "No file upload");
        RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/index");
        dispatcher.forward(request, response);
    } catch (Exception ex) {
        System.err.println(ex);
    }
}