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.concursive.connect.web.modules.welcome.servlets.WelcomeServlet.java

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {//from ww  w  .  j a v  a2 s.c om
        request.setCharacterEncoding("UTF-8");
    } catch (Exception e) {
        LOG.warn("Unsupported encoding");
    }
    try {
        // Save the requestURI to be used downstream (it gets rewritten on forwards)
        String contextPath = request.getContextPath();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        String requestedURL = uri.substring(contextPath.length())
                + (queryString == null ? "" : "?" + queryString);
        if ("/index.shtml".equals(requestedURL)) {
            requestedURL = "";
        }
        request.setAttribute("requestedURL", requestedURL);
        // Configure the user's client
        ClientType clientType = (ClientType) request.getSession().getAttribute(Constants.SESSION_CLIENT_TYPE);
        if (clientType == null) {
            clientType = new ClientType();
            clientType.setParameters(request);
            request.getSession().setAttribute("clientType", clientType);
        }

        // Detect mobile
        if ("false".equals(request.getParameter("useMobile"))) {
            clientType.setMobile(false);
        }

        // Context startup initializes the prefs
        ApplicationPrefs applicationPrefs = (ApplicationPrefs) request.getSession().getServletContext()
                .getAttribute("applicationPrefs");
        if (!applicationPrefs.isConfigured()) {
            RequestDispatcher initialSetup = request.getRequestDispatcher("/Setup.do?command=Default");
            initialSetup.forward(request, response);
        } else if (ApplicationVersion.isOutOfDate(applicationPrefs)) {
            // If the site is setup, then check to see if this is an upgraded version of the app
            RequestDispatcher upgrade = getServletConfig().getServletContext()
                    .getRequestDispatcher("/Upgrade.do?command=Default&style=true");
            upgrade.forward(request, response);
        } else if ("true".equals(applicationPrefs.get("PORTAL"))) {
            // If the site supports a portal, go to the portal
            // @todo implement mobile pages then turn this back on
            //        if (clientType.getMobile()) {
            // If a mobile device is detected, offer a low-bandwidth option
            //          RequestDispatcher portal = request.getRequestDispatcher("/Login.do?command=DetectMobile");
            //          portal.forward(request, response);
            //        } else {
            String pathToUse = request.getRequestURI().substring(request.getContextPath().length());
            RequestDispatcher portal = request
                    .getRequestDispatcher(pathToUse + applicationPrefs.get("PORTAL.INDEX"));
            portal.forward(request, response);
            //        }
        } else {
            // Go to the user's home page if logged in
            User thisUser = (User) request.getSession().getAttribute(Constants.SESSION_USER);
            if (thisUser != null && thisUser.getId() > 0) {
                RequestDispatcher portal = request
                        .getRequestDispatcher("/ProjectManagement.do?command=Default");
                portal.forward(request, response);
            } else {
                RequestDispatcher portal = request.getRequestDispatcher("/Login.do?command=Default");
                portal.forward(request, response);
            }
        }
    } catch (Exception ex) {
        String msg = "Welcome failed";
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
    }
}

From source file:com.versatus.jwebshield.filter.SessionCheckFilter.java

/**
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 *///from   ww  w  . j  a  va2  s.  c  o m
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpReq = (HttpServletRequest) request;
    HttpServletResponse httpRes = (HttpServletResponse) response;
    String reqInfo = "J-WebShield Alert: Session check failed! request URL="
            + httpReq.getRequestURL().toString() + "| from IP address=" + httpReq.getRemoteAddr();

    logger.debug("doFilter: RequestURL=" + httpReq.getRequestURL().toString());

    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.SESSION_CHECK_URL_EXCL_LIST_ATTR_NAME);

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            logger.info("doFilter: request (" + httpReq.getRequestURL().toString()
                    + " matches exclusion pattern, skipping session check");
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {
        logger.error("doFilter", e);
    }

    HttpSession session = httpReq.getSession(false);
    logger.debug("doFilter: session=" + session);
    logger.debug("doFilter: session attr. " + attributeToCheck + "="
            + (session != null ? session.getAttribute(attributeToCheck) : ""));

    if (session == null || session.getAttribute(attributeToCheck) == null) {
        if (send401) {
            // TODO this is not working for regular requests, only for WS
            // calls
            httpRes.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            logger.info(reqInfo + " redirecting to " + redirectPage);

            RequestDispatcher rd = httpReq.getRequestDispatcher(redirectPage);
            if (rd != null) {
                rd.forward(request, response);
            }
            return;
        }

    }

    logger.info("doFilter: session check complete");

    // pass the request along the filter chain
    chain.doFilter(request, response);
}

From source file:edu.lternet.pasta.portal.IdentifierBrowseServlet.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 {

    HttpSession httpSession = request.getSession();

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

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

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

    String text = null;
    String html = null;
    Integer count = 0;

    if (scope != null && !(scope.isEmpty())) {

        try {

            DataPackageManagerClient dpmClient = new DataPackageManagerClient(uid);
            text = dpmClient.listDataPackageIdentifiers(scope);

            StrTokenizer tokens = new StrTokenizer(text);

            html = "<ol>\n";

            ArrayList<String> arrayList = new ArrayList<String>();

            // Add scope/identifier values to a sorted set
            while (tokens.hasNext()) {
                arrayList.add(tokens.nextToken());
                count++;
            }

            // Output sorted set of scope/identifier values
            for (String identifier : arrayList) {

                html += "<li><a class=\"searchsubcat\" href=\"./mapbrowse?scope=" + scope + "&identifier="
                        + identifier + "\">" + scope + "." + identifier + "</a></li>\n";

            }

            html += "</ol>\n";

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

    } else {
        html = "<p class=\"warning\"> Error: \"scope\" field empty</p>\n";
    }

    request.setAttribute("browsemessage", browseMessage);
    request.setAttribute("html", html);
    request.setAttribute("count", count.toString());
    RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward);
    requestDispatcher.forward(request, response);

}

From source file:com.googlesource.gerrit.plugins.github.wizard.VelocityControllerServlet.java

private void redirectToNextStep(HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException {
    String sourceUri = req.getRequestURI();
    int pathPos = sourceUri.lastIndexOf('/') + 1;
    String sourcePage = sourceUri.substring(pathPos);
    String sourcePath = sourceUri.substring(0, pathPos);
    int queryStringStart = sourcePage.indexOf('?');
    if (queryStringStart > 0) {
        sourcePage = sourcePage.substring(0, queryStringStart);
    }/*from  w  w w  .ja v a  2s .co m*/
    NextPage nextPage = githubConfig.getNextPage(sourcePage);
    if (nextPage != null) {
        if (nextPage.redirect) {
            resp.sendRedirect(nextPageURL(sourcePath, nextPage));
        } else {
            RequestDispatcher requestDispatcher = req.getRequestDispatcher(nextPageURL(sourcePath, nextPage));
            req.setAttribute("destUrl", nextPage);
            requestDispatcher.forward(req, resp);
        }
    }
}

From source file:Controller.ControllerProducts.java

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

        String action = request.getParameter("action");
        if (action.equals("FIND")) {
            String productname = request.getParameter("txtname");
            Products pr = new Products();
            List<Product> list = new ArrayList<Product>();
            list = pr.list(productname);
            request.setAttribute("listSP", list);
            request.setAttribute("proname", productname);
            RequestDispatcher rd = request.getRequestDispatcher("product.jsp");
            rd.forward(request, response);
        } else if (action.equals("Delete")) {
            String code = request.getParameter("txtcode");
            Products sp = new Products();
            sp.Delete(code);
            RequestDispatcher rd = request.getRequestDispatcher("ControllerProducts?action=Find&txtname=");
            rd.forward(request, response);

        } else if (action.equals("Edit")) {
            String code = request.getParameter("txtcode");
            String name = request.getParameter("txtname");
            String price = request.getParameter("txtprice");
            String image = request.getParameter("txtimage");
            Product sp = new Product(code, name, price, image);
            request.setAttribute("SP", sp);

            RequestDispatcher rd = request.getRequestDispatcher("editProduct.jsp");
            rd.forward(request, response);

        } else if (action.equals("Search")) {
            String productname = request.getParameter("txtname");
            Products pr = new Products();
            List<Product> list = new ArrayList<Product>();
            list = pr.list(productname);
            request.setAttribute("listSP", list);
            request.setAttribute("proname", productname);
            RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
            rd.forward(request, response);

        } else if (action.equals("Searchcus")) {
            String productname = request.getParameter("txtname");
            Products pr = new Products();
            List<Product> list = new ArrayList<Product>();
            list = pr.list(productname);
            request.setAttribute("listSP", list);
            request.setAttribute("proname", productname);
            RequestDispatcher rd = request.getRequestDispatcher("index_Cus1.jsp");
            rd.forward(request, response);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Controller.ControllerProducts.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  w ww  .  j a  va2 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 {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {

    } else {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();
        Hashtable params = new Hashtable();
        String fileName = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {

                try {
                    String itemName = item.getName();
                    fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                    System.out.println("path" + fileName);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    System.out.println("Rpath" + RealPath);
                    File savedFile = new File(RealPath);
                    item.write(savedFile);
                    //System.out.println("upload\\"+fileName);
                    //insert Product
                    String code = (String) params.get("txtcode");
                    String name = (String) params.get("txtname");
                    String price = (String) params.get("txtprice");
                    Products sp = new Products();
                    sp.InsertProduct(code, name, price, "upload\\" + fileName);
                    RequestDispatcher rd = request.getRequestDispatcher("product.jsp");
                    rd.forward(request, response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }
    //this.processRequest(request, response);
}

From source file:Index.LoginServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//www .j  a v a2  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");

    PrintWriter out = response.getWriter();

    try {
        String user, password, errorMessage;
        if (request.getParameter("user") != null && request.getParameter("password") != null) {

            user = request.getParameter("user");
            password = request.getParameter("password");

            if (user.equalsIgnoreCase("") || password.equalsIgnoreCase("")) {

                errorMessage = "Ingrese todos los datos.";
                request.setAttribute("error", errorMessage);
                request.setAttribute("funcionalidad", "Login");
                request.getRequestDispatcher("/Login.jsp").forward(request, response);

            } else {

                if (user.equals("admin") && password.equals("admin")) {

                    HttpSession session = request.getSession();
                    session.setAttribute("Admin", user);
                    request.removeAttribute("error");
                    request.removeAttribute("funcionalidad");
                    request.getRequestDispatcher("/Index.jsp").forward(request, response);
                } else {
                    QuickOrderWebService webService = new QuickOrderWebService();
                    ControllerInterface port = webService.getQuickOrderWebServicePort();
                    webservice.Cliente usr = port.infoCliente(user);

                    if (usr != null && usr.getNickname() != null) {

                        String encriptMD5 = DigestUtils.md5Hex(password);
                        password = "md5:" + encriptMD5;

                        if (usr.getPassword().equals(password)) {
                            HttpSession session = request.getSession();
                            session.setAttribute("Usuario", usr);

                            request.removeAttribute("error");
                            request.removeAttribute("funcionalidad");
                            request.getRequestDispatcher("/Index.jsp").forward(request, response);
                        } else {
                            errorMessage = "Credenciales invalidas";
                            request.setAttribute("error", errorMessage);
                            request.setAttribute("funcionalidad", "Login");
                            request.getRequestDispatcher("/Login.jsp").forward(request, response);
                        }
                    } else {
                        errorMessage = "Credenciales invalidas";
                        request.setAttribute("error", errorMessage);
                        request.setAttribute("funcionalidad", "Login");
                        request.getRequestDispatcher("/Login.jsp").forward(request, response);
                    }
                }
            }
        } else {
            errorMessage = "Error al realizar login.";
            request.setAttribute("error", errorMessage);
            request.setAttribute("funcionalidad", "Login");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Login.jsp");
            dispatcher.forward(request, response);
        }
    } catch (Exception ex) {
        out.println("Error en proceso de login: " + ex.getMessage());
    } finally {
        out.close();
    }

}

From source file:feedme.controller.HomePageServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*from  w  w  w. j  a  v a2s.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);
    HashMap<String, Integer> category = new HashMap<>();
    List<Restaurant> restaurants;

    DbHPOnLoad dbPageOnLoad = new DbHPOnLoad();//creating a DbHPOnLoad object

    List<Restaurant> allResturent = new DbAdminManagmentTools().getAllRestaurants();

    int page = 1;
    int recordsPerPage = 6;

    if (request.getParameter("page") != null) {
        page = Integer.parseInt(request.getParameter("page"));
    }

    int noOfRecords = allResturent.size();
    int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);

    category = dbPageOnLoad.getCategories();//getting a categories
    restaurants = new DbRestaurantsManagement()
            .getNextRecentRestaurantsByCatAndCity((page - 1) * recordsPerPage, recordsPerPage, 0, "Asd");//get the last 6 new restaurants

    if (isAjaxRequest(request)) {
        try {
            JSONObject restObj = new JSONObject();
            JSONArray restArray = new JSONArray();
            for (Restaurant rest : restaurants) {
                restArray.put(new JSONObject().put("resturent", rest.toJson()));
            }
            restObj.put("resturent", restArray);
            restObj.put("noOfPages", noOfPages);
            restObj.put("currentPage", page);
            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            writer.print(restObj);
            response.getWriter().flush();
            return;
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    List<String> cities = dbPageOnLoad.getCities();
    if (request.getSession().getAttribute("shoppingCart") == null) {
        request.getSession().setAttribute("shoppingCart", new Order());//crete a new shopping cart
    }

    List<RestaurantRanking> rankings = dbPageOnLoad.getRestRandomComments(5);//getting a random rankings from DB

    for (RestaurantRanking re : rankings) {//looping over the rankings
        re.setResturent(new DbRestaurantsManagement().getRestaurantById(re.getRestId()));
    }

    request.setAttribute("noOfPages", noOfPages);
    request.setAttribute("currentPage", page);
    request.setAttribute("category", category);//send the categories
    request.setAttribute("cities", cities);//send the cities
    request.setAttribute("restaurants", restaurants);//send the restaurants
    request.setAttribute("rankings", rankings);//send the rankings

    RequestDispatcher dispatcher = request.getRequestDispatcher("website/index.jsp");//send a ajsp file
    dispatcher.forward(request, response);
    return;
}

From source file:controllers.ServerController.java

public void logout(HttpServletRequest request, HttpServletResponse response)
        throws IOException, InterruptedException, ServletException {
    HttpSession session = request.getSession(false);
    session.invalidate();/*from   ww  w  .  java 2  s  . co m*/
    RequestDispatcher rd = request.getRequestDispatcher("index.html");
    rd.forward(request, response);
}

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

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {//from   w w w. j  a v a  2 s .c om
        Long serviceId = new Long(req.getParameter("serviceId"));
        Long scenarioId = null;
        scenarioId = new Long(req.getParameter("scenarioId"));
        Service service = store.getServiceById(serviceId);
        Scenario scenario = service.getScenario(scenarioId);
        req.setAttribute("service", service);
        req.setAttribute("scenario", scenario);
    } catch (Exception e) {
        logger.debug("Unable to retrieve a Service of ID: " + req.getParameter("serviceId"));
    }

    // Get the service.
    RequestDispatcher dispatch = req.getRequestDispatcher("/jsonschemavalidate.jsp");
    dispatch.forward(req, resp);
}