Example usage for javax.servlet.http HttpServletRequest getRequestDispatcher

List of usage examples for javax.servlet.http HttpServletRequest getRequestDispatcher

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest 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:com.mycompany.memegenerator.FileUpload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w  w w.ja 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 {
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    byte[] byteImage = item.get();
                    uploadImage = ImageIO.read(new ByteArrayInputStream(byteImage));
                    //ImageIO.write(uploadImage, "jpg", new File("C:\\uploads","snap.jpg"));

                    // get session
                    HttpSession session = request.getSession();
                    session.setAttribute("byteImage", byteImage);
                    session.setAttribute("uploadImage", uploadImage);

                }
            }

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

    request.getRequestDispatcher("/index.jsp").forward(request, response);

}

From source file:com.parallax.server.blocklyprop.servlets.PublicProfileServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String idUserString = req.getParameter("id-user");
    Long idUser = null;//from  w  ww .j a  v  a2 s  . c  om
    try {
        if (Strings.isNullOrEmpty(idUserString)) {
            if (SecurityUtils.getSubject().isAuthenticated()) {
                idUser = SecurityServiceImpl.getSessionData().getIdUser();
            } else {
                log.info("Getting current user while not authenticated");
                resp.sendError(404);
            }
        } else {
            idUser = Long.parseLong(idUserString);
        }
    } catch (NumberFormatException nfe) {
        log.info("id-user is not a valid number: {}", idUserString);
        resp.sendError(500);
    }
    try {

        User user = userService.getUser(idUser);
        if (user == null) {
            log.info("Get public profile for user {} (Does not exist!)", idUser);
            resp.sendError(404);
            return;
        }

        log.info("Get public profile for user {}: Cloud-session user: {}", idUser, user.getIdcloudsession());
        com.parallax.client.cloudsession.objects.User cloudSessionUser = cloudSessionUserService
                .getUser(user.getIdcloudsession());

        req.setAttribute("screenname", cloudSessionUser.getScreenname());
        req.getRequestDispatcher("/WEB-INF/servlet/public-profile.jsp").forward(req, resp);
    } catch (UnknownUserIdException ex) {
        log.info("User not known in cloud-session");
        resp.sendError(404);
    } catch (ServerException ex) {
        log.error("Communication problem with Cloud-session", ex);
        resp.sendError(500);
    }

}

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

/**
 * The doPost method of the servlet. <br>
 * //from   w  ww . 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 xml = null;
    String filter = "";
    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);

            if (subscriptionId.isEmpty()) {
                xml = eventClient.readByFilter(filter);
            } else {
                xml = eventClient.readBySid(subscriptionId);
            }

            SubscriptionUtility subscriptionUtility = new SubscriptionUtility(xml);
            message = subscriptionUtility.xmlToHtml(cwd + xslpath);
            type = "info";
        } catch (Exception e) {
            handleDataPortalError(logger, e);
        }
    }

    request.setAttribute("reviewmessage", message);
    request.setAttribute("type", type);
    RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward);
    requestDispatcher.forward(request, response);
}

From source file:org.surfnet.oaaas.consent.FormUserConsentHandler.java

private void processInitial(HttpServletRequest request, ServletResponse response, FilterChain chain,
        String returnUri, String authStateValue, Client client) throws IOException, ServletException {
    AuthenticatedPrincipal principal = (AuthenticatedPrincipal) request
            .getAttribute(AbstractAuthenticator.PRINCIPAL);
    List<AccessToken> tokens = accessTokenRepository.findByResourceOwnerIdAndClient(principal.getName(),
            client);//from   w w w  . j a  v  a2  s .co  m
    if (!CollectionUtils.isEmpty(tokens)) {
        // If another token is already present for this resource owner and client, no new consent should be requested
        List<String> grantedScopes = tokens.get(0).getScopes(); // take the scopes of the first access token found.
        setGrantedScopes(request, grantedScopes.toArray(new String[grantedScopes.size()]));
        chain.doFilter(request, response);
    } else {
        AuthorizationRequest authorizationRequest = authorizationRequestRepository
                .findByAuthState(authStateValue);
        request.setAttribute("requestedScopes", authorizationRequest.getRequestedScopes());
        request.setAttribute("client", client);
        request.setAttribute(AUTH_STATE, authStateValue);
        request.setAttribute("actionUri", returnUri);
        ((HttpServletResponse) response).setHeader("X-Frame-Options", "SAMEORIGIN");
        request.getRequestDispatcher(getUserConsentUrl()).forward(request, response);
    }

}

From source file:com.atlassian.jira.web.dispatcher.JiraWebworkActionDispatcher.java

/**
 * Service a request. The request is first checked to see if it is a multi-part. If it is, then the request is
 * wrapped so WW will be able to work with the multi-part as if it was a normal request. Next, we will process all
 * actions until an action returns a non-action which is usually a view. For each action in a chain, the action's
 * context will be first set and then the action will be instantiated. Next, the previous action if this action
 * isn't the first in the chain will have its attributes copied to the current action.
 *
 * @param httpServletRequest HttpServletRequest
 * @param httpServletResponse HttpServletResponse
 *//* ww  w  . j a  va2 s .  c om*/
public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {
    Pair<HttpServletRequest, HttpServletResponse> wrap = wrap(httpServletRequest, httpServletResponse);

    httpServletRequest = wrap.first();
    httpServletResponse = wrap.second();

    // If the CLEANUP attribute is NOT set or is set to true - do the cleanup
    //
    // This is set into the request by ActionCleanupDelayFilter always!
    //
    boolean doCleanup = (httpServletRequest.getAttribute(CLEANUP) == null
            || httpServletRequest.getAttribute(CLEANUP).equals(Boolean.TRUE));

    GenericDispatcher gd = null;
    try {
        String actionName = getActionName(httpServletRequest);

        gd = prepareDispatcher(httpServletRequest, httpServletResponse, actionName);

        ActionResult ar = null;
        try {
            gd.executeAction();
            ar = gd.finish();
        } catch (XsrfFailureException e) {
            // if we fail the XSRF check then we use a servlet FORWARD to the session timeout page.
            httpServletRequest.getRequestDispatcher(XsrfErrorAction.FORWARD_PATH).forward(httpServletRequest,
                    httpServletResponse);
        } catch (WebSudoSessionException websudoException) {
            // We want websudo session for this action and we dont have it.
            ar = new ActionResult(Action.LOGIN,
                    "/secure/admin/WebSudoAuthenticate!default.jspa?webSudoDestination="
                            + getDestinationUrl(httpServletRequest),
                    Collections.EMPTY_LIST, null);
        } catch (ActionNotFoundException e) {
            log.debug("Action '{}' was not found, returning 404", e.getActionName());
            sendErrorImpl(httpServletResponse, 404, null);
        } catch (LookupAliasActionFactoryProxy.UnauthorisedActionException unauthorisedActionException) {
            httpServletRequest
                    .getRequestDispatcher("/login.jsp?permissionViolation=true&os_destination="
                            + getDestinationUrl(httpServletRequest))
                    .forward(httpServletRequest, httpServletResponse);
        } catch (Exception e) {
            onActionRecoverableThrowable(httpServletResponse, actionName, e);
        }

        if (ar != null && ar.getActionException() != null) {
            onActionException(actionName, ar);
        }

        // check if no view exists
        if (ar != null && ar.getResult() != null && ar.getView() == null
                && !ar.getResult().equals(Action.NONE)) {
            onNoViewDefined(httpServletResponse, actionName, ar);
        }

        if (ar != null && ar.getView() != null && ar.getActionException() == null) {
            viewDispatcher.dispatchView(httpServletRequest, httpServletResponse, doCleanup, ar, actionName);
        }
    } finally {
        performFinallyCleanup(httpServletRequest, doCleanup, gd);
    }
}

From source file:com.lrodriguez.SVNBrowser.java

private void doChangeUrl(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();

    logDebug("dispatching changeUrl");
    SVNHttpSession svnsession = (SVNHttpSession) session.getAttribute(SVNSESSION);
    if (svnsession == null) {
        request.setAttribute(ERROR,// w w  w . ja  v a  2s. co m
                "svnsession is null, try deleting your cookies and accessing SVNBrowser with no parameters");
        request.getRequestDispatcher(INDEX_JSP).forward(request, response);
        return;
    }

    String webappRoot = this.getServletContext().getRealPath("/") == null ? getInitParameter(WEBAPP_ROOT)
            : this.getServletContext().getRealPath("/");
    SVNHttpSession newSvnsession = new SVNHttpSession(request.getParameter(CHANGE_URL),
            getInitParameter(USER_NAME), getInitParameter("password"), webappRoot,
            getInitParameter(REPOSITORY_DIR));
    logDebug("initializing SVNRepository.\nrepositoryURL=" + newSvnsession.getRepositoryURL() + "\nuser="
            + newSvnsession.getUserName());
    try {
        newSvnsession.init();
    } catch (SVNException e) {
        e.printStackTrace();
        request.setAttribute(ERROR, e.getErrorMessage());
        request.getRequestDispatcher(INDEX_JSP).forward(request, response);
        return;
    }

    session.setAttribute(SVNSESSION, newSvnsession);
    List branches = getAllBranches(request);
    if (request.getAttribute(ERROR) != null) {
        session.setAttribute(SVNSESSION, newSvnsession);//revert to original session
        request.getRequestDispatcher(INDEX_JSP).forward(request, response);
        return;
    }
    session.setAttribute(BRANCHES, branches);

    logDebug("closing existing svnsession ");
    svnsession.getRepository().closeSession();

    session.setAttribute(REPOSITORY_URL, request.getParameter(CHANGE_URL));//set the new URL in the session (used by JSP)
    session.removeAttribute(CURRENT_BRANCH);
    //currentBranch = persistCurrentBranch(request);//set the current branch

    //List uniqueEntries = getUniqueEntries(request, startDate, endDate);
    //if(request.getAttribute(ERROR)!= null){
    //   request.getRequestDispatcher("index.jsp").forward(request, response);
    //   return;
    //}

    //uniqueEntries = filterListByCurrentBranch(uniqueEntries, currentBranch);

    //Collections.sort(uniqueEntries, comparator);

    session.setAttribute(UNIQUE_ENTRIES, null);

    request.getRequestDispatcher(INDEX_JSP).forward(request, response);
    return;
}

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

/**
 *
 * @param request servlet request/*from   w  ww.  java2  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 {
    EntityManager em = (EntityManager) request.getSession().getAttribute("em");

    String examId = request.getParameter("examid");
    String status = request.getParameter("status");
    Clock clk = (Clock) (request.getSession().getAttribute("clock"));
    User user = (User) (request.getSession().getAttribute("user"));

    Exam exam = em.find(Exam.class, examId);

    try {
        em.getTransaction().begin();
    } catch (Exception e) {
    }

    try {
        if (status.equals("approved")) {
            user.changeExamStatus(exam, ExamStatus.APPROVED);
            em.persist(exam);
            em.getTransaction().commit();
            request.setAttribute("msg", "Exam APPROVED");
        } else if (status.equals("denied")) {
            user.changeExamStatus(exam, ExamStatus.DENIED);
            em.persist(exam);
            em.getTransaction().commit();
            request.setAttribute("msg", "Exam Denied");
        } else {
            request.setAttribute("msg", "Invalid status");
        }
    } catch (Exception e) {
        em.getTransaction().rollback();
        request.setAttribute("msg", e.toString());
        throw e;
    }

    RequestDispatcher rd = request.getRequestDispatcher("/home.jsp");
    rd.forward(request, response);
}

From source file:fr.univlille2.ecm.platform.ui.web.auth.cas2.SecurityExceptionHandler.java

@Override
public void handleException(HttpServletRequest request, HttpServletResponse response, Throwable t)
        throws IOException, ServletException {

    @SuppressWarnings("deprecation")
    Throwable unwrappedException = unwrapException(t);
    log.debug("handleException#in");
    if (!ExceptionHelper.isSecurityError(unwrappedException)
            && !response.containsHeader(SSO_INITIAL_URL_REQUEST_KEY)) {
        super.handleException(request, response, t);
        return;//from   w  w  w.  java2 s .co  m
    }

    Principal principal = request.getUserPrincipal();
    NuxeoPrincipal nuxeoPrincipal = null;
    if (principal instanceof NuxeoPrincipal) {
        nuxeoPrincipal = (NuxeoPrincipal) principal;
        // redirect to login than to requested page
        if (nuxeoPrincipal.isAnonymous()) {
            response.resetBuffer();

            String urlToReach = getURLToReach(request);
            log.debug(String.format("handleException#urlToReach#%s", urlToReach));
            Cookie cookieUrlToReach = new Cookie(NXAuthConstants.SSO_INITIAL_URL_REQUEST_KEY, urlToReach);
            cookieUrlToReach.setPath("/");
            cookieUrlToReach.setMaxAge(60);
            response.addCookie(cookieUrlToReach);
            log.debug(String.format("handleException#cookieUrlToReach#%s", cookieUrlToReach.getName()));
            if (!response.isCommitted()) {
                request.getRequestDispatcher(CAS_REDIRECTION_URL).forward(request, response);
            }
            FacesContext.getCurrentInstance().responseComplete();
        }
    }
    // go back to default handler
    super.handleException(request, response, t);
}

From source file:com.lrodriguez.SVNBrowser.java

private void doDefaultRequest(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        Date startDate, Date endDate, Comparator comparator) throws ServletException, IOException {
    logDebug("dispatching default request");

    List branches = getAllBranches(request);
    if (request.getAttribute(ERROR) != null) {
        return;/*from   w  w  w .  ja va2  s.c  om*/
    }
    session.setAttribute(BRANCHES, branches);

    List uniqueEntries = getUniqueEntries(request, startDate, endDate);
    if (request.getAttribute(ERROR) != null) {
        request.getRequestDispatcher(INDEX_JSP).forward(request, response);
        return;
    }

    //uniqueEntries = filterListByCurrentBranch(uniqueEntries, currentBranch);

    Collections.sort(uniqueEntries, comparator);

    session.setAttribute(UNIQUE_ENTRIES, uniqueEntries);
    request.getRequestDispatcher(INDEX_JSP).forward(request, response);
    return;
}

From source file:com.ibm.bluemix.samples.UploadServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("Upload Servlet");

    try {/*from w  w w . jav  a  2s  .c  om*/
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                // item is the file (and not a field), read it in and add to List
                Scanner scanner = new Scanner(new InputStreamReader(item.getInputStream(), "UTF-8"));
                List<String> lines = new ArrayList<String>();
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine().trim();
                    if (line.length() > 0) {
                        lines.add(line);
                    }
                }
                scanner.close();

                // add lines to database
                int rows = db.addPosts(lines);
                String msg = "Added " + rows + " rows.";
                request.setAttribute("msg", msg);
                break;
            }
        }

        request.setAttribute("posts", db.getResults());
    } catch (Exception e) {
        request.setAttribute("msg", e.getMessage());
        e.printStackTrace(System.err);
    }

    response.setContentType("text/html");
    response.setStatus(200);
    request.getRequestDispatcher("/home.jsp").forward(request, response);
}