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.edgenius.wiki.security.acegi.CaptchaValidationProcessingFilter.java

private void processVerify(ServletRequest request, ServletResponse response, FilterChain chain, boolean valid)
        throws IOException, ServletException {

    if (valid) {/*from  w w  w  .  j av a2  s  .c  om*/
        //success
        chain.doFilter(request, response);
    } else {
        //failed
        if (((HttpServletRequest) request).getRequestURI().endsWith("j_spring_security_check")) {
            //as user login using Form submit style authentication rather than RPC's so that I have to do special handling here
            //code ugly, it could be changed to RPC authentication in future.
            response.getWriter()
                    .write(SharedConstants.FORM_RET_HEADER + SharedConstants.FORM_RET_HEADER_ERROR_CAPTCHA);
        } else {
            // Put exception into request scope (perhaps of use to a view)
            ((HttpServletRequest) request).setAttribute(ACEGI_SECURITY_CAPTCHA_VALID_FAILED, true);

            // Perform RequestDispatcher "forward"
            RequestDispatcher rd = request.getRequestDispatcher(errorPage);
            rd.forward(request, response);
        }
    }

}

From source file:com.huateng.ebank.framework.web.TransFilter.java

private boolean expiredSystem(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    String uriStr = StringUtils.substringAfterLast(req.getServletPath(), "/");
    if (StringUtils.indexOf(loginRef, uriStr) == -1) {
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0");
        resp.setDateHeader("Expires", 1);
        RequestDispatcher rd = (req).getRequestDispatcher(expiredPageName);
        rd.forward(req, resp);
        return true;
    }// ww  w .java 2  s  .c  o m
    return false;
}

From source file:org.ldp4j.apps.ldp4ro.servlets.Form2RDFServlet.java

/**
 * Upon receiving data from the RO creation form,
 * 1. parses the request to extract the form data
 * 2. converts them to RDF to generate a RO
 * 3. submit that RO to an LDP server that manages the RO
 *///from w ww . j  a  v a 2s  .  c  o m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String requestURL = request.getRequestURL().toString();
    logger.debug("Received a POST request on '{}'", requestURL);

    Map<String, String[]> parameterMap = request.getParameterMap();

    RoRDFModel ro = new RoRDFModel(parameterMap);

    Model model = ro.process();

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    model.write(os, "TURTLE");
    String roString = os.toString();

    logger.debug("Form data is converted to RDF ... \n{}", roString);

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost:8080/ldp4j/ldp-bc/");
    //HttpPost post = new HttpPost("http://linkeddata4.dia.fi.upm.es:8088/ldp4j/ldp-bc/");

    StringEntity body = new StringEntity(roString);
    body.setContentType("text/turtle");
    post.setEntity(body);

    HttpResponse ldpResponse = httpclient.execute(post);

    try {
        int statusCode = ldpResponse.getStatusLine().getStatusCode();
        logger.debug("LDP server responded with {} {}", statusCode,
                ldpResponse.getStatusLine().getReasonPhrase());

        if (statusCode == 201 && ldpResponse.getFirstHeader("Location") != null) {
            String location = ldpResponse.getFirstHeader("Location").getValue();
            logger.debug("URI of the newly created LDPR - {}", location);

            request.setAttribute("newURI", location);

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

        } else {
            logger.error("An error occurred while creating the RO. {} {}", statusCode,
                    ldpResponse.getStatusLine().getReasonPhrase());
        }

    } finally {
        post.releaseConnection();
    }

}

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

/**
 *
 * @param request servlet request//w w w  . ja 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 {
    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:org.broadleafcommerce.cms.web.PageURLProcessor.java

/**
 * Determines if the requestURI for the passed in request matches a custom content
 * managed page.   If so, the request is forwarded to the correct page template.
 *
 * The page object will be stored in the request attribute "BLC_PAGE".
 *
 * @param key The URI to process//from  w w w  .j ava2s  . co m
 *
 * @return false if the url could not be processed
 *
 * @throws java.io.IOException
 * @throws javax.servlet.ServletException
 */
public boolean processURL(String key) throws IOException, ServletException {
    BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();
    PageDTO p = (PageDTO) context.getRequest().getAttribute(PAGE_ATTRIBUTE_NAME);
    if (p == null) {
        p = pageService.findPageByURI(context.getLocale(), key, buildMvelParameters(context.getRequest()),
                context.isSecure());
    }

    if (p != null) {
        String templateJSPPath = p.getTemplatePath();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Forwarding to page: " + templateJSPPath);
        }
        context.getRequest().setAttribute(PAGE_ATTRIBUTE_NAME, p);

        RequestDispatcher rd = context.getRequest().getRequestDispatcher(templateJSPPath);
        rd.forward(context.getRequest(), context.getResponse());
        return true;
    }
    return false;
}

From source file:com.cabguru.servlet.AddDriverServlet.java

private void dispatch(HttpServletRequest request, HttpServletResponse response, String callerPage, String msg) {

    try {// ww w  .j  ava 2s  .co  m
        request.setAttribute("msg", msg);
        RequestDispatcher rd = request.getRequestDispatcher(callerPage);
        rd.forward(request, response);
    } catch (ServletException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:org.broadleafcommerce.profile.web.email.EmailOpenTrackingServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String url = request.getPathInfo();
    Long emailId = null;/*www . java 2  s .c  om*/
    String imageUrl = "";

    // Parse the URL for the Email ID and Image URL
    if (url != null) {
        String[] items = url.split("/");
        emailId = Long.valueOf(items[1]);
        StringBuffer sb = new StringBuffer();
        for (int j = 2; j < items.length; j++) {
            sb.append("/");
            sb.append(items[j]);
        }
        imageUrl = sb.toString();
    }

    // Record the open
    if (emailId != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("service() => Recording Open for Email[" + emailId + "]");
        }
        WebApplicationContext context = WebApplicationContextUtils
                .getWebApplicationContext(getServletContext());
        EmailTrackingManager emailTrackingManager = (EmailTrackingManager) context
                .getBean("blEmailTrackingManager");
        String userAgent = request.getHeader("USER-AGENT");
        Map<String, String> extraValues = new HashMap<String, String>();
        extraValues.put("userAgent", userAgent);
        emailTrackingManager.recordOpen(emailId, extraValues);
    }

    if ("".equals(imageUrl)) {
        response.setContentType("image/gif");
        BufferedInputStream bis = null;
        OutputStream out = response.getOutputStream();
        try {
            bis = new BufferedInputStream(EmailOpenTrackingServlet.class.getResourceAsStream("clear_dot.gif"));
            boolean eof = false;
            while (!eof) {
                int temp = bis.read();
                if (temp == -1) {
                    eof = true;
                } else {
                    out.write(temp);
                }
            }
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (Throwable e) {
                    LOG.error("Unable to close output stream in EmailOpenTrackingServlet", e);
                }
            }
            //Don't close the output stream controlled by the container. The container will
            //handle this.
        }
    } else {
        RequestDispatcher dispatcher = request.getRequestDispatcher(imageUrl);
        dispatcher.forward(request, response);
    }
}

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

/**
 * /*from   w w w .  j  a v a  2 s  .  c  o  m*/
 * 
 * @param req
 *            basic request
 * @param resp
 *            basic resp
 * @throws ServletException
 *             basic
 * @throws IOException
 *             basic
 */
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

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

From source file:org.archive.wayback.accesspoint.proxy.AuthProxyConfigSelector.java

public boolean selectConfigHandler(HttpServletRequest request, HttpServletResponse response,
        ProxyAccessPoint proxy) throws IOException {
    response.setStatus(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED); //407
    response.setHeader("Proxy-Authenticate", "Basic realm=\"" + authMsg + "\"");
    response.setContentType("text/html");

    //TODO: Better way to pass this to jsp?
    request.setAttribute("proxyAccessPoint", proxy);

    StringHttpServletResponseWrapper wrappedResponse = new StringHttpServletResponseWrapper(response);
    RequestDispatcher dispatcher = request.getRequestDispatcher(proxyInfoJsp);

    try {/*w  w  w  .j  a  v  a2  s  . c om*/
        dispatcher.forward(request, wrappedResponse);
    } catch (ServletException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    PrintWriter writer = response.getWriter();
    writer.println(wrappedResponse.getStringResponse());
    return true;
}

From source file:com.krawler.svnwebclient.authorization.impl.CredentialsManager.java

protected void forceCredentialsRequest(HttpServletRequest request, HttpServletResponse response) {
    request.getSession().setAttribute(CredentialsManager.CREDENTIALS, null);
    request.getSession().setAttribute(SystemInitializing.ID, null);
    try {//from   ww w. j a va2 s.  c om
        if (ConfigurationProvider.getInstance().isBasicAuth()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setHeader("WWW-Authenticate",
                    "BASIC realm=\"" + ConfigurationProvider.getInstance().getBasicRealm() + "\"");
            response.sendError(401);
        } else {
            RequestDispatcher dispatcher = request.getRequestDispatcher(Links.LOGIN);
            dispatcher.forward(request, response);
        }
    } catch (Exception e) {
        Logger.getLogger(this.getClass()).error(e, e);
    }
}