Example usage for javax.servlet ServletContext getRequestDispatcher

List of usage examples for javax.servlet ServletContext getRequestDispatcher

Introduction

In this page you can find the example usage for javax.servlet ServletContext getRequestDispatcher.

Prototype

public RequestDispatcher getRequestDispatcher(String path);

Source Link

Document

Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.

Usage

From source file:org.apache.hadoop.hdfsproxy.ProxyForwardServlet.java

/** {@inheritDoc} */
public void forwardRequest(HttpServletRequest request, HttpServletResponse response, ServletContext context,
        String pathInfo) throws IOException, ServletException {
    String path = buildForwardPath(request, pathInfo);
    RequestDispatcher dispatcher = context.getRequestDispatcher(path);
    if (dispatcher == null) {
        LOG.info("There was no such dispatcher: " + path);
        response.sendError(HttpServletResponse.SC_NO_CONTENT);
        return;/*w ww  . j  a va2 s . co m*/
    }
    dispatcher.forward(request, response);
}

From source file:com.openkm.servlet.admin.LogCatServlet.java

/**
 * List logs/*from   w  ww  .j  ava 2s  .c o  m*/
 */
private void list(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("list({}, {})", request, response);
    ServletContext sc = getServletContext();
    sc.setAttribute("files", FileUtils.listFiles(logFolder, null, false));
    sc.getRequestDispatcher("/admin/logcat.jsp").forward(request, response);

    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_LOGCAT_LIST", null, null, logFolder.getPath());

    log.debug("list: void");
}

From source file:org.nuxeo.wss.servlet.WSSFilter.java

protected void doForward(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
        FilterBindingConfig config) throws Exception {
    // To forward to the backend filter, we need to change context
    // but on some App Server (ex: Tomcat 6) default config prohibit this
    ServletContext targetContext = ctx.getContext(getRootFilterTarget());
    if (targetContext != null) {
        targetContext.getRequestDispatcher(httpRequest.getRequestURI()).forward(httpRequest, httpResponse);
    } else {//from   w  w w  . j a  v a2s .c om
        String newTarget = getRootFilterTarget() + httpRequest.getRequestURI() + "?"
                + httpRequest.getQueryString();
        if ("VtiHandler".equals(config.getTargetService())
                || "SHtmlHandler".equals(config.getTargetService())) {
            handleWSSCall(httpRequest, httpResponse, config);
        } else {
            // try to redirect, but this won't work for all cases
            // since MS http libs don't seem to handle redirect
            // transparently
            httpResponse.sendRedirect(newTarget);
        }
    }
}

From source file:com.openkm.servlet.admin.LogCatServlet.java

/**
 * Purge log//from  w  w  w  . j  av  a  2  s .c  o m
 */
@SuppressWarnings("unchecked")
private void purge(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("purge({}, {})", request, response);
    for (File lf : (Collection<File>) FileUtils.listFiles(logFolder, null, false)) {
        if (lf.getName().matches(".+[0-9][0-9]-[0-9][0-9]-[0-9][0-9].*")) {
            lf.delete();
        }
    }

    ServletContext sc = getServletContext();
    sc.setAttribute("files", FileUtils.listFiles(logFolder, null, false));
    sc.getRequestDispatcher("/admin/logcat.jsp").forward(request, response);

    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_LOGCAT_PURGE", null, null, null);

    log.debug("view: void");
}

From source file:nu.kelvin.jfileshare.servlets.AboutServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext app = getServletContext();
    RequestDispatcher disp;/*from  ww  w .j  a v a 2 s  .co m*/
    req.setAttribute("tab", "About");
    disp = app.getRequestDispatcher("/templates/About.jsp");
    HttpSession session = req.getSession();
    Conf conf = (Conf) app.getAttribute("conf");

    req.setAttribute("daysLogRetention", conf.getDaysLogRetention());

    if (session.getAttribute("user") != null) {
        Connection dbConn = null;
        PreparedStatement st = null;
        try {
            long bytesStoreAvailable = FileSystemUtils.freeSpaceKb(conf.getPathStore()) * 1024;
            req.setAttribute("bytesStoreAvailable", FileItem.humanReadable(bytesStoreAvailable));

            dbConn = ds.getConnection();
            st = dbConn.prepareStatement(
                    "select cast(count(1) as char) as logins, cast(count(distinct payload) as char) as uniqueLogins from Logs where action=\"login\" and date > (now() - INTERVAL ? DAY)");
            st.setInt(1, conf.getDaysLogRetention());
            ResultSet rs = st.executeQuery();
            if (rs.first()) {
                req.setAttribute("logins", rs.getString("logins"));
                req.setAttribute("uniqueLogins", rs.getString("uniqueLogins"));
            }

            st = dbConn.prepareStatement(
                    "select cast(count(1) as char) as downloads, sum(cast(payload as unsigned)) as bytesDownloads from Logs where action=\"download\" and date > (now() - INTERVAL ? DAY)");
            st.setInt(1, conf.getDaysLogRetention());
            rs = st.executeQuery();
            if (rs.first()) {
                req.setAttribute("downloads", rs.getString("downloads"));
                req.setAttribute("bytesDownloads", FileItem.humanReadable(rs.getLong("bytesDownloads")));
            }

            st = dbConn.prepareStatement(
                    "select cast(count(1) as char) as uploads, sum(cast(payload as unsigned)) as bytesUploads from Logs where action=\"upload\" and date > (now() - INTERVAL ? DAY)");
            st.setInt(1, conf.getDaysLogRetention());
            rs = st.executeQuery();
            if (rs.first()) {
                req.setAttribute("uploads", rs.getString("uploads"));
                req.setAttribute("bytesUploads", FileItem.humanReadable(rs.getLong("bytesUploads")));
            }
            st.close();
        } catch (SQLException e) {
            logger.severe(e.toString());
        } finally {
            if (dbConn != null) {
                try {
                    dbConn.close();
                } catch (SQLException ignore) {
                }
            }
        }
    }
    disp.forward(req, resp);
}

From source file:org.apache.struts.chain.commands.servlet.PerformForward.java

private void handleAsForward(String uri, ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    RequestDispatcher rd = servletContext.getRequestDispatcher(uri);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Forwarding to " + uri);
    }/*w w w  .  jav  a 2 s  . co  m*/

    rd.forward(request, response);
}

From source file:org.apache.struts.chain.commands.servlet.PerformForward.java

private void handleAsInclude(String uri, ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    RequestDispatcher rd = servletContext.getRequestDispatcher(uri);

    if (rd == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Error getting RequestDispatcher for " + uri);
        return;//from w w w. jav  a2 s  . c  om
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Including " + uri);
    }

    rd.include(request, response);
}

From source file:myClass_Main.java

/**
 *
 * @param request//w w  w. ja v a 2 s. c om
 * @param response
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    int option = Integer.parseInt(request.getParameter("optionValue"));
    String url;
    // do some processing here...
    // get response writer
    switch (option) {
    case 1: {
        int userValue = Integer.parseInt(request.getParameter("userValue"));
        String htmlres = "";
        // build HTML code
        for (int i = 0; i < userValue; i++) {
            htmlres = htmlres
                    + "<input type=\"text\" id=\"inputValue\" name=\"inputValue\" class=\"form-group form-control\" placeholder=\"Nombre de Pais "
                    + (i + 1) + "\" required autofocus>";
        }
        request.setAttribute("htmlres", htmlres);
        url = "/myPage_core.jsp";
        ServletContext sc = getServletContext();
        RequestDispatcher rd = sc.getRequestDispatcher(url);
        rd.forward(request, response);
    }
        break;
    case 2: {
        String[] input = request.getParameterValues("inputValue");
        String sourceURL = "http://api.myjson.com/bins/vcv1"; //just a string
        // Connect to the URL using java's native library
        URL urlobject = new URL(sourceURL);
        HttpURLConnection conection = (HttpURLConnection) urlobject.openConnection();
        conection.connect();
        // Convert to a JSON object to print data
        String[][] contry_values = new String[10][input.length];
        String zipcode = null;
        JSONParser jp = new JSONParser(); //from gson
        JSONObject root = null;
        JSONArray root_array = null;
        try {
            root = (JSONObject) jp.parse(new InputStreamReader(conection.getInputStream())); //Convert the input stream to a json element
        } catch (ParseException ex) {
            Logger.getLogger(myClass_Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        boolean firstName = (boolean) root.containsKey("countries");
        root = (JSONObject) root.get("countries");
        root_array = (JSONArray) root.get("country");
        //Iterator j = root_array.iterator();
        for (int i = 0; i < input.length; i++) {
            Iterator j = root_array.iterator();
            while (j.hasNext()) {
                JSONObject inner = (JSONObject) j.next();
                if (inner.containsValue(input[i])) {
                    contry_values[0][i] = (String) inner.get("isoNumeric");
                    contry_values[1][i] = (String) inner.get("countryName");
                    contry_values[2][i] = (String) inner.get("continentName");
                    contry_values[3][i] = (String) inner.get("capital");
                    contry_values[4][i] = (String) inner.get("languages");
                    if (contry_values[4][i].length() > 11) {
                        String strOut = contry_values[4][i];
                        String trimedstring = strOut.substring(0, 10) + "...";// count start in 0 and 8 is excluded
                        contry_values[4][i] = trimedstring;
                    }
                    contry_values[5][i] = (String) inner.get("population");
                    contry_values[6][i] = (String) inner.get("areaInSqKm");
                    contry_values[7][i] = (String) inner.get("countryCode");
                    contry_values[8][i] = "https://es.wikipedia.org/wiki/"
                            + ((String) inner.get("countryName"));
                }
            }
        }
        System.out.println("The first name is: " + zipcode);
        request.setAttribute("firstname", zipcode);
        String htmlres = "<table class=\"table\">\n" + "<caption>Datos de Paises</caption>\n" + "<thead>\n"
                + "<tr>\n" + "<th>COD INT.</th>\n" + "<th>AVB.</th>\n" + "<th>Nombre</th>\n"
                + "<th>Continente</th>\n" + "<th>Capital</th>\n" + "<th>Idioma</th>\n" + "<th>Poblacion</th>\n"
                + "<th>Area km2</th>\n" + "<th>Wiki URL</th>\n" + "</tr>\n" + "</thead>\n" + "<tbody>";
        // build HTML code
        for (int h = 0; h < input.length; h++) {
            if ((contry_values[0][h]) != null) {
                htmlres = htmlres + "<tr><th scope=\"row\">" + contry_values[0][h] + "</th>";
                for (int g = 0; g < 9; g++) {
                    if (g != 8) {
                        htmlres = htmlres + "<td>" + contry_values[g][h] + "</td>";
                    } else {
                        htmlres = htmlres + "<td>" + "<a href=\"" + contry_values[g][h]
                                + "\" class=\"btn btn-info\" role=\"button\">" + contry_values[7][h] + "</a>"
                                + "</td>";
                    }
                }
                htmlres = htmlres + "</tr>";
            } else {
                htmlres = htmlres + "<tr><th scope=\"row\">" + "#Er." + h + "</th>";
                htmlres = htmlres + "<td colspan=\"9\">" + "El pais \"" + input[h]
                        + "\" no esta en la BD, verifique que el nombre esta en ingls, e intente de nuevo"
                        + "</td>";
            }
        }
        htmlres = htmlres + "<tr>";
        htmlres = htmlres + "</tbody>\n" + "</table>";
        request.setAttribute("htmlres", htmlres);
        url = "/myPage_res.jsp";
        ServletContext sc = getServletContext();
        RequestDispatcher rd = sc.getRequestDispatcher(url);
        rd.forward(request, response);
    }
        break;
    case 3: {
        url = "/index.jsp";
        ServletContext sc = getServletContext();
        RequestDispatcher rd = sc.getRequestDispatcher(url);
        rd.forward(request, response);
    }
        break;
    default: {
        url = "/index.jsp";
        ServletContext sc = getServletContext();
        RequestDispatcher rd = sc.getRequestDispatcher(url);
        rd.forward(request, response);
    }
        break;
    }
}

From source file:controllers.ControllerServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*  w  ww  . j a v a 2 s  .c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String userPath = request.getServletPath();

    // if cart page is requested
    if (userPath.equals("/workers")) {
        ArrayList<Worker> accounts = new ArrayList(UFNS.getInstance().getAllWorkers());
        //               if(accounts.isEmpty()) {
        //                   try {
        //                       UFNS.getInstance().readFromJSON("/Users/ivan/Desktop/ufns.json");
        //                       accounts = new ArrayList(UFNS.getInstance().getAllWorkers());
        //                   } catch (WrongNumberValueException ex) {
        //                       
        //                   }
        //               }
        ServletContext sc = getServletContext();
        RequestDispatcher rd = sc.getRequestDispatcher(userPath);
        request.setAttribute("accountList", accounts);
    } else if (userPath.equals("/contracts")) {
        String id;
        id = request.getQueryString();
        id = id.replaceAll("id=", "");
        ArrayList<AbstractContract> contracts;
        try {
            contracts = new ArrayList(UFNS.getInstance().getAllContractsForWorkerWithId(Long.parseLong(id)));
            Worker w = UFNS.getInstance().getWorkerWithId(Long.parseLong(id));
            ServletContext sc = getServletContext();
            RequestDispatcher rd = sc.getRequestDispatcher(userPath);
            request.setAttribute("contractsList", contracts);
            request.setAttribute("workerId", id);
            request.setAttribute("name", w.getWorkerName());
            request.setAttribute("surname", w.getWorkerSurName());
            request.setAttribute("lastname", w.getWorkerLastName());
        } catch (WrongNumberValueException ex) {
            Logger.getLogger(ControllerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    // use RequestDispatcher to forward request internally
    String url = "/WEB-INF/pages" + userPath + ".jsp";

    try {
        request.getRequestDispatcher(url).forward(request, response);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.ikon.servlet.admin.CssServlet.java

/**
 * List CSS/* w ww .  j a  v a2  s  .  c om*/
 */
private void list(String userId, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("list({}, {}, {})", new Object[] { userId, request, response });
    ServletContext sc = getServletContext();
    sc.setAttribute("cssList", CssDAO.getInstance().findAll());
    sc.getRequestDispatcher("/admin/css_list.jsp").forward(request, response);
    log.debug("list: void");
}