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:edu.harvard.hul.ois.pds.ws.PDSWebService.java

public static void printError(HttpServletRequest req, HttpServletResponse res, String message, Throwable e) {
    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(req);
    wrapper.setAttribute("message", message);
    wrapper.setAttribute("pdsUrl", req.getContextPath());
    wrapper.setAttribute("exception", e);
    wrapper.setAttribute("req", req);
    RequestDispatcher rd = req.getRequestDispatcher("/api-error.jsp?");
    try {//from  w w  w . j a v a  2s.c  o  m
        rd.forward(req, res);
    } catch (Exception e1) {
        e1.printStackTrace();
    }
}

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

/**
 * The doPost method of the servlet. <br>
 * /* ww  w .j a  v a2  s .  c om*/
 * 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 xml = null;

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

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

    String subscriptionId = request.getParameter("subscriptionid");

    String message = null;
    String type = null;

    if (uid.equals("public")) {

        message = LOGIN_WARNING;
        type = "warning";

    } else {

        try {
            EventSubscriptionClient eventClient = new EventSubscriptionClient(uid);
            eventClient.testSubscription(subscriptionId);
            xml = eventClient.readBySid(subscriptionId);
            message = "Event subscription with identifier '<b>" + subscriptionId
                    + "</b>' has been tested by posting to the Target URL.</strong>";
            type = "info";
        } catch (Exception e) {
            handleDataPortalError(logger, e);
        }

    }

    request.setAttribute("testmessage", message);
    request.setAttribute("type", type);

    RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward);
    requestDispatcher.forward(request, response);

}

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

/**
 * The doPost method of the servlet. <br>
 * /*from ww w  .j  a v  a  2  s  .  co  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 deleteMessage = null;
    String messageType = null;
    HttpSession httpSession = request.getSession();

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

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

    String docid = request.getParameter("docid");
    if (docid != null) {
        String[] tokens = docid.split("\\.");
        if (tokens != null && tokens.length >= 2) {
            String scope = tokens[0];
            String identifierStr = tokens[1];
            Integer identifier = Integer.parseInt(identifierStr);

            if (uid.equals("public")) {
                messageType = "warning";
                request.setAttribute("message", LOGIN_WARNING);
            } else {
                try {
                    DataPackageManagerClient dpmc = new DataPackageManagerClient(uid);
                    dpmc.deleteReservation(scope, identifier);
                    deleteMessage = String.format(
                            "Reservation for data package identifier '<b>%s</b>' has been deleted.", docid);
                    messageType = "info";
                } catch (Exception e) {
                    handleDataPortalError(logger, e);
                }
            }
        }
    }

    request.setAttribute("deleteMessage", deleteMessage);
    request.setAttribute("messageType", messageType);

    RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward);
    requestDispatcher.forward(request, response);

}

From source file:com.playright.servlet.ChartServlet.java

private void forwardToPage(final HttpServletRequest request, final HttpServletResponse response, String url)
        throws IOException, ServletException {
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
    dispatcher.forward(request, response);
}

From source file:feedme.controller.SearchRestServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*from  w w w.ja  v  a  2  s . c  om*/
 * @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);
    request.setCharacterEncoding("UTF-8");

    String city = request.getParameter("where");//get the city
    int category = Integer.parseInt(request.getParameter("what"));//get the category

    int page = 1;
    int recordsPerPage = 6;

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

    List<Restaurant> restaurants = new DbRestaurantsManagement().getNextRecentRestaurantsByCatAndCity(0,
            recordsPerPage, category, city);//getting a list of restaurants by category and cities
    int noOfRecords = restaurants.size();

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

    if (isAjaxRequest(request)) {
        try {
            restaurants = new DbRestaurantsManagement().getNextRecentRestaurantsByCatAndCity(
                    (page - 1) * recordsPerPage, recordsPerPage, category, city);//getting a list of restaurants by category and cities
            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();
        }
    }
    request.setAttribute("noOfPages", noOfPages);
    request.setAttribute("currentPage", page);
    request.setAttribute("restaurants", restaurants);//return the restaurants to the client

    RequestDispatcher dispatcher = request.getRequestDispatcher("website/search_rest.jsp");
    dispatcher.forward(request, response);

}

From source file:ch.entwine.weblounge.kernel.http.WelcomeFileFilterServlet.java

/**
 * {@inheritDoc}//from  w w w. j a v  a2  s.  c om
 *
 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    if (req.getPathInfo() != null && "/".equals(req.getPathInfo())) {
        if (!welcomeFileList.isEmpty()) {
            // use the first one for now:
            for (String welcomeFile : welcomeFileList) {
                String file = welcomeFile;
                if (welcomeFile.startsWith("/"))
                    file = welcomeFile.substring(1);
                RequestDispatcher dispatcher = req.getRequestDispatcher(file);
                // TODO: check if resource exists before forwarding
                dispatcher.forward(req, res);
                return;
            }
        } else {
            req.getRequestDispatcher(req.getServletPath() + "/resources/index.html").forward(req, res);
            // Tomcat also defaults to index.jsp
            return;
        }
    } else {
        // no welcome file, trying to forward to remapped resource:
        // /resources"+req.getPathInfo()
        req.getRequestDispatcher(req.getServletPath() + "/resources" + req.getPathInfo()).forward(req, res);
    }
}

From source file:com.orangeandbronze.jblubble.sample.UploadServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        pathInfo = "/";
    }/*  w  w w . j ava2s  . c  o  m*/
    LOGGER.debug("GET {}{}", PATH, pathInfo);
    if ("/create".equals(pathInfo)) {
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/views/uploads/create.jsp");
        requestDispatcher.forward(request, response);
    } else if (pathInfo.length() > 1) {
        BlobKey blobKey = new BlobKey(pathInfo.substring(1));
        BlobInfo blobInfo = blobstoreService.getBlobInfo(blobKey);
        response.setContentType(blobInfo.getContentType());
        // In Servlet API 3.1, use #setContentLengthLong(long)
        response.setContentLength((int) blobInfo.getSize());
        response.setDateHeader("Last-Modified", blobInfo.getDateCreated().getTime());
        blobstoreService.serveBlob(blobKey, response.getOutputStream());
    } else {
        // else show links to blobs that were previously uploaded (if any)
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/views/uploads/index.jsp");
        List<BlobInfo> blobInfos = new LinkedList<>();
        for (BlobKey blobKey : blobKeys) {
            blobInfos.add(blobstoreService.getBlobInfo(blobKey));
        }
        request.setAttribute("blobstoreService", blobstoreService);
        request.setAttribute("blobKeys", blobKeys);
        request.setAttribute("blobInfos", blobInfos);
        requestDispatcher.forward(request, response);
    }
}

From source file:eu.eidas.springsecu.EidasAccessDeniedHandler.java

@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
        AccessDeniedException accessDeniedException) throws IOException, ServletException {
    logger.debug("Arrive dans handle error");
    EIDASAuthnResponse authnResponse = null;
    SAMLResponse = request.getParameter("SAMLresponse");
    if (SAMLResponse == null) {
        throw new IOException("Saml Response is null");
    }/*from ww w.  j ava 2s  .co m*/
    if (SAMLResponse.isEmpty()) {
        throw new IOException("Saml Response is empty");
    }
    //Decodes SAML Response
    byte[] decSamlToken = EIDASUtil.decodeSAMLToken(SAMLResponse);

    //Get SAMLEngine instance

    try {
        EIDASSAMLEngine engine = SPUtil.createSAMLEngine(Constants.SP_CONF);
        //validate SAML Token
        authnResponse = engine.validateEIDASAuthnResponse(decSamlToken, request.getRemoteHost(), 0);

    } catch (EIDASSAMLEngineException e) {
        logger.error(e.getMessage());
        if (StringUtils.isEmpty(e.getErrorDetail())) {
            throw new IOException(SAML_VALIDATION_ERROR, e);
        } else {
            throw new IOException(SAML_VALIDATION_ERROR, e);
        }
    }

    if (authnResponse.isFail()) {
        throw new IOException("Saml Response is fail" + authnResponse.getMessage());
    } else {
        request.setAttribute("assertions", authnResponse.getAsserts());
        RequestDispatcher dispatch;
        dispatch = request.getRequestDispatcher("/saml");
        logger.debug("Avant forward vers saml");
        dispatch.forward(request, response);
    }

}

From source file:com.gigglinggnus.controllers.StudentMakeAppointmentController.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    EntityManager em = (EntityManager) request.getSession().getAttribute("em");

    Clock clk = (Clock) (request.getSession().getAttribute("clock"));

    List<Term> terms = Term.getFutureTerms(em, Instant.now(clk));
    List<Exam> exams = terms.stream().flatMap(term -> term.getExams().stream())
            .filter(exam -> exam.getStatus() == ExamStatus.PENDING).collect(Collectors.toList());

    request.setAttribute("exams", exams);

    RequestDispatcher rd = request.getRequestDispatcher("/student/make-apmt.jsp");
    rd.forward(request, response);
}

From source file:com.happyuno.controller.StartGame.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *//*from  w  w  w  .j a  va  2s  .c  om*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/html;charset=utf-8");
    request.setCharacterEncoding("utf-8");

    //?tableId
    String tableId = (String) request.getParameter("tableId");

    System.out.println(tableId);
    //?userId
    String userId = (String) request.getSession().getAttribute("userId");

    //
    ServletContext application = request.getSession().getServletContext();
    HashMap<Integer, GameTable> gameTableMap = (HashMap<Integer, GameTable>) application
            .getAttribute("gameTableMap");

    String resultMessage = "??";

    //User??Player
    ArrayList<Player> players = new ArrayList<Player>();

    int tindex = Integer.parseInt(tableId);
    GameTable gt = gameTableMap.get(tindex);
    ArrayList<User> userList = gt.getUserList();

    resultMessage = "??";
    //????
    gt.setStateStart(true);
    System.out.println(userList.size() + "changdu");
    for (int i = 0; i < userList.size(); i++) {
        //Playerid,nameUser?
        System.out.println(i + "position");
        String curUserId = ((User) userList.get(i)).getId();
        System.out.println("UserId" + curUserId);
        int cUserId = Integer.parseInt(curUserId);
        String curUserName = ((User) userList.get(i)).getName();
        Player curPlayer = new Player(cUserId, curUserName);
        players.add(curPlayer);
    }
    gt.getCurrentGame().initGame(players);

    HttpSession session = request.getSession();
    session.setAttribute("tableId", tindex);
    session.setAttribute("players", players);
    session.setAttribute("curPlayerId", Integer.parseInt(userId));

    //
    application.setAttribute("gameTableMap", gameTableMap);

    //tableMap?
    application.setAttribute("tatoNum", gameTableMap.size());

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/table.jsp");
    dispatcher.forward(request, response);

}