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:controller.uploadPergunta4.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w  w  .j av  a 2  s .  c om
 *
 * @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 idEquacaoVolumePadrao = (String) request.getParameter("idEquacaoVolumePadrao");

    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");
    }

    RequestDispatcher view = getServletContext().getRequestDispatcher("/novoLocalPergunta4?id=" + idLocal
            + "&nomeArquivo=" + name + "&idEquacaoVolumePadrao=" + idEquacaoVolumePadrao);
    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:org.apache.stratos.redirector.servlet.ui.filters.AllPagesFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    if (!(servletRequest instanceof HttpServletRequest)) {
        // no filtering
        return;/* w  ww. j a va  2  s  . co  m*/
    }
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    String requestedURI = request.getRequestURI();

    String contextPath = request.getContextPath();
    if (contextPath == null || ("/").equals(contextPath)) {
        contextPath = "";
    }

    StringTokenizer tokenizer = new StringTokenizer(requestedURI.substring(contextPath.length() + 1), "/");
    String[] firstUriTokens = new String[2];
    int i = 0;
    while (tokenizer.hasMoreElements()) {
        firstUriTokens[i] = tokenizer.nextToken();
        i++;
        if (i > 1) {
            break;
        }
    }
    if (i > 1 && firstUriTokens[0].equals("t")) {
        if (requestedURI.startsWith("//")) {
            requestedURI = requestedURI.replaceFirst("//", "/");
        }
        String path = requestedURI
                .substring(contextPath.length() + firstUriTokens[0].length() + firstUriTokens[1].length() + 2);

        // need to validate the tenant exists
        String tenantDomain = firstUriTokens[1];
        boolean tenantExists = true;
        boolean tenantActive = true;

        if (tenantExistMap.get(tenantDomain) == null) {
            // we have to call the service :(
            RedirectorServletServiceClient client;
            try {
                client = new RedirectorServletServiceClient(context, request.getSession());
            } catch (Exception e) {
                String msg = "Error in constructing RedirectorServletServiceClient.";
                log.error(msg, e);
                throw new ServletException(msg, e);
            }

            try {
                String status = client.validateTenant(tenantDomain);
                tenantExists = !StratosConstants.INVALID_TENANT.equals(status);
                if (tenantExists && StratosConstants.ACTIVE_TENANT.equals(status)) {
                    //tenantExists = true;
                    tenantActive = true;
                }
            } catch (Exception e) {
                String msg = "Error in checking the existing of the tenant domain: " + tenantDomain + ".";
                log.error(msg, e);
                throw new ServletException(msg, e);
            }
        }
        // we have some backup stuff, if the tenant doesn't exists
        if (tenantExists) {
            if (tenantActive) {
                // we put this to hash only if the original tenant domain exist
                tenantExistMap.put(tenantDomain, true);
            } else {
                String errorPage = contextPath + "/carbon/admin/error.jsp?The Requested tenant domain: "
                        + tenantDomain + " is inactive.";
                RequestDispatcher requestDispatcher = request.getRequestDispatcher(errorPage);
                requestDispatcher.forward(request, servletResponse);
                return;
            }
        } else {
            String errorPage = contextPath + "/carbon/admin/error.jsp?The Requested tenant domain: "
                    + tenantDomain + " doesn't exist.";
            RequestDispatcher requestDispatcher = request.getRequestDispatcher(errorPage);
            requestDispatcher.forward(request, servletResponse);
            return;
        }
        request.setAttribute(MultitenantConstants.TENANT_DOMAIN, tenantDomain);
        //            if (path.indexOf("admin/login.jsp") >= 0) {
        //                // we are going to apply the login.jsp filter + tenant specif filter both in here
        //                path = path.replaceAll("admin/login.jsp",
        //                        "tenant-login/login_ajaxprocessor.jsp");
        //                request.setAttribute(StratosConstants.TENANT_SPECIFIC_URL_RESOLVED, "1");
        //            }
        if (path.indexOf("/admin/index.jsp") >= 0) {
            // we are going to apply the login.jsp filter + tenant specif filter both in here
            path = path.replaceAll("/admin/index.jsp", "/tenant-dashboard/index.jsp");
            request.setAttribute(StratosConstants.TENANT_SPECIFIC_URL_RESOLVED, "1");
        }
        if (path.indexOf("admin/docs/userguide.html") >= 0) {
            // we are going to apply the dasbhoard docs.jsp filter +
            // tenant specif filter both in here
            path = path.replaceAll("admin/docs/userguide.html", "tenant-dashboard/docs/userguide.html");
            request.setAttribute(StratosConstants.TENANT_SPECIFIC_URL_RESOLVED, "1");
        }
        if ("".equals(path) || "/".equals(path) || "/carbon".equals(path) || "/carbon/".equals(path)
                || "/carbon/admin".equals(path) || "/carbon/admin/".equals(path)) {
            // we have to redirect the root to the login page directly
            path = contextPath + "/carbon/admin/login.jsp";
            ((HttpServletResponse) servletResponse).sendRedirect(path);
            return;
        }
        RequestDispatcher requestDispatcher = request.getRequestDispatcher(path);
        requestDispatcher.forward(request, servletResponse);
        return;
    }
}

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

/**
 * The doPost method of the servlet. <br>
 * /*from  ww w  .ja  va 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 termsListHTML = "";
    String htmlTable = "";
    String mapButtonHTML = "";
    String relevanceHTML = "";
    HttpSession httpSession = request.getSession();
    ResultSetUtility resultSetUtility = null;

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

    String userInput = (String) request.getParameter("terms");
    String start = (String) request.getParameter("start");
    String rows = (String) request.getParameter("rows");
    String sort = (String) request.getParameter("sort");

    if (sort == null || sort.equals("")) {
        sort = Search.DEFAULT_SORT;
    }

    if (userInput == null || userInput.equals("")) {
        String queryText = null;
        String q = (String) request.getParameter("q");

        if (q == null || q.equals("")) {
            // if no q param was passed, look for query stored in the session
            queryText = (String) httpSession.getAttribute("queryText");
            termsListHTML = (String) httpSession.getAttribute("termsListHTML");
        } else {
            queryText = q;
        }

        if (queryText != null) {
            queryText = String.format("%s&start=%s&rows=%s&sort=%s", queryText, start, rows, sort);
            resultSetUtility = executeQuery(uid, queryText, sort);
            if (resultSetUtility != null) {
                mapButtonHTML = resultSetUtility.getMapButtonHTML();
                relevanceHTML = resultSetUtility.getRelevanceHTML();
                htmlTable = resultSetUtility.getHTMLTable();
            }
        }
    } else {
        SimpleSearch simpleSearch = new SimpleSearch();
        String queryText = simpleSearch.buildSolrQuery(userInput, false);
        TermsList termsList = simpleSearch.getTermsList();
        termsListHTML = termsList.toHTML();
        httpSession.setAttribute("termsListHTML", termsListHTML);
        httpSession.setAttribute("queryText", queryText);
        queryText = String.format("%s&start=%d&rows=%d&sort=%s", queryText, 0, Search.DEFAULT_ROWS, sort);
        resultSetUtility = executeQuery(uid, queryText, sort);
        if (resultSetUtility != null) {
            mapButtonHTML = resultSetUtility.getMapButtonHTML();
            //relevanceHTML = resultSetUtility.getRelevanceHTML();
            htmlTable = resultSetUtility.getHTMLTable();
        }
    }

    request.setAttribute("mapButtonHTML", mapButtonHTML);
    request.setAttribute("relevanceHTML", relevanceHTML);
    request.setAttribute("searchresult", htmlTable);
    RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward);
    requestDispatcher.forward(request, response);
}

From source file:com.jspxcms.core.setup.SetupServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    Integer step = (Integer) session.getAttribute("step");
    if (step == null) {
        step = 0;/* www . j a  va 2s .  c o  m*/
    }
    RequestDispatcher rd = request.getRequestDispatcher(STEP_MAP.get(step));
    rd.forward(request, response);
}

From source file:com.paladin.mvc.RequestContext.java

public void forward(String uri) {
    RequestDispatcher rd = context.getRequestDispatcher(uri);
    try {//from   www.  j a  v a  2  s  .  c o m
        rd.forward(request, response);
    } catch (ServletException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.plexus.crtvgHorarios.view.managedBeans.LoginBean.java

public void executeLogin(ActionEvent e) throws ServletException, IOException {

    /*//from  ww  w  .  jav a2 s  .  c o m
     * El siguiente cdigo es necesario para que el filtro de Spring-Security intercepte
     * la request del login ya que no funciona poner action="\j_spring_security_check" en la request del form
     * como se hara si fuese una pgina jsp en lugar de una xhtml de facelets.
     * 
     * La ventaja es que la pgina de login no est condicionada por spring-security
     */
    ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
    RequestDispatcher dispatcher = ((ServletRequest) context.getRequest()).getRequestDispatcher(
            "/j_spring_security_check?j_username=" + username + "&j_password=" + password);
    dispatcher.forward((ServletRequest) context.getRequest(), (ServletResponse) context.getResponse());
    FacesContext.getCurrentInstance().responseComplete();

    // Fija el locale a gl al logearse
    Locale locale = new Locale("gl", "");
    org.omnifaces.util.Faces.setLocale(locale);

    /**
    // Aade el item "Men principal" al breadCrumb.
    BreadCrumbBean breadCrumBean = FacesUtils.getManagedBean("breadCrumbBean", BreadCrumbBean.class);
            
    MenuItem item = new MenuItem();
            
    //MethodExpression methodExpression = FacesUtils.createMethodExpression("#{breadCrumbBean.goMenuPrincipal}"+"?faces-redirect=true", null, new Class<?>[0]);
            
    item.setId("menuPrincipalMenuItem");
    item.setValue("Men principal");
    item.setUrl("/pages/menuPrincipal.xhtml");
            
    //item.setActionExpression(methodExpression);
            
    breadCrumBean.addItem(item);
    **/

    // FIXME: Tras logearse se est perdiendo el locale si est est definido como gl

}

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

/**
 * Handles the following activities for <code>TwistInfo</code>
 * //from w  ww. jav  a  2s .  c  om
 */
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // ***********************
    // 1. If type is JSON, then respond with JSON
    // 2. Otherwise, dispatch to JSP
    // 3. Create/delete/update TwistInfo
    // ***********************

    // ***********************
    // INITIALIZAION
    // ***********************

    Long twistInfoId = null;
    TwistInfo twistInfo = null;
    try {
        twistInfoId = new Long(req.getParameter(PARAMETER_KEY_TWIST_ID));
        twistInfo = store.getTwistInfoById(twistInfoId);
    } catch (Exception e) {
        // Do nothing. If the value doesn't exist,
        // then we'll create a new TwistInfo
    }

    if (twistInfo == null) {
        twistInfo = new TwistInfo();
    }
    // ***********************
    // DATA HANDLING
    // ***********************
    String name = req.getParameter(PARAMETER_KEY_TWIST_NAME);

    if (name == null || name.trim().length() == 0) {
        name = "TwistInfo (auto-generated)";
    }
    String[] originationArguments = req.getParameterValues(PARAMETER_KEY_TWIST_ORIGINATION_LIST);
    String[] destinationArguments = req.getParameterValues(PARAMETER_KEY_TWIST_DESTINATION_LIST);
    // Remove any existing TwistInfo patterns.
    twistInfo.setPatternPairList(new ArrayList<PatternPair>());
    if ((originationArguments != null && destinationArguments != null)
            && (originationArguments.length == destinationArguments.length)) {
        for (int i = 0; i < originationArguments.length; i++) {
            twistInfo.addPatternPair(new PatternPair(originationArguments[i], destinationArguments[i]));
        }
    }

    twistInfo.setName(name);
    twistInfo = store.saveOrUpdateTwistInfo(twistInfo);

    // ***********************
    // RESPONSE - in JSON or JSP
    // ***********************
    String responseType = req.getParameter(PARAMETER_KEY_RESPONSE_TYPE);
    if (PARAMETER_KEY_RESPONSE_TYPE_VALUE_JSON.equalsIgnoreCase(responseType)) {
        // BUILD JSON response
        resp.setContentType("application/json");
        PrintWriter out = resp.getWriter();
        try {
            JSONObject jsonResponseObject = new JSONObject();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("success", "Twist updated");
            jsonObject.put("id", "" + twistInfo.getId());
            jsonObject.put("name", twistInfo.getName());

            jsonResponseObject.put("result", jsonObject);
            out.println(jsonResponseObject.toString());

        } catch (JSONException jsonException) {
            throw new ServletException(jsonException);
        }

        out.flush();
        out.close();
        return;
    } else {
        List<TwistInfo> twistInfoList = store.getTwistInfoList();
        req.setAttribute("twistInfoList", twistInfoList);
        req.setAttribute("twistInfoIdEnabled", store.getUniversalTwistInfoId());

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

}

From source file:Control.LoadImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// ww w  . j a va2 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 {
    String tempPath = "/temp";
    String 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);

        if (file == null) {
            // tao thu muc
        }

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

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

        if (items.size() > 0) {
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    if ("images".equals(item.getFieldName())) {
                        if (item.getName() != null && !item.getName().isEmpty()) {
                            String extension = null;
                            if (item.getName().endsWith("jpg")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".jpg";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".jpg");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            } else if (item.getName().endsWith("png")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".png";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".png");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            } else if (item.getName().endsWith("JPG")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".JPG";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".JPG");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            } else if (item.getName().endsWith("PNG")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".PNG";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".PNG");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            }
                        }
                    }
                } else {
                }
            }
            response.sendRedirect(request.getContextPath() + "/LoadImage.jsp");
            return;
        }

        List<Image> images = loadImages(request, response);

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

From source file:controller.editGames.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {

        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem fileItem = iter.next();
                if (fileItem.isFormField()) {
                    processFormField(fileItem);
                } else {
                    flItem = fileItem;//from   w  w  w . ja va 2s  .  co m
                }
            }
        }

        Check b = new Check();
        b.setMinCpu(MinCpu);
        b.setMinCpuLvl(MinCpuLvl);
        b.setMinGpu(MinGpu);
        b.setMinGpuLvl(MinGpuLvl);
        b.setMinRam(MinRam);

        b.setCode(Code);

        b.setRecCpuLvl(RecCpuLvl);
        b.setRecCpu(RecCpu);
        b.setRecGpu(RecGpu);
        b.setRecGpuLvl(RecGpuLvl);
        b.setRecRam(RecRam);

        int i = b.editGame();

        if (i > 0) {
            RequestDispatcher rd = request.getRequestDispatcher("viewGames.jsp");
            request.setAttribute("return", "Edit Item is Successful.");
            rd.forward(request, response);
        } else {
            RequestDispatcher rd = request.getRequestDispatcher("editGames.jsp");
            request.setAttribute("return", "Edit Item is Failed.");
            rd.forward(request, response);
        }

    } catch (Exception e) {
        System.out.println(e);

    }
}

From source file:br.com.flucianofeijao.security.JsfLoginUrlAuthenticationEntryPoint.java

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

    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(request);
        }

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

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

            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);

    }

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