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:it.volaconnoi.servlet.BookingServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/* ww w .j a va2s.  com*/
 * @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();

    session = request.getSession(true);

    if (userPath.equals("/booking")) {
        String route_id = request.getParameter("id");

        session.setAttribute("route", routeManagerBean.getRouteById(route_id));

        if (request.getUserPrincipal() != null) {
            UserCredential user = userManagerBean.getUserByUsername(request.getUserPrincipal().getName());

            session.setAttribute("user", user);
        }

        request.setAttribute("CountriesList", countryFacade.findAll());

        request.setAttribute("tax", PricerBeanInterface.TAX);

        request.getRequestDispatcher("/WEB-INF/view/booking/booking.jsp").forward(request, response);
    }
}

From source file:org.guanxi.sp.engine.security.shibboleth.IdPVerifier.java

/**
 * Blocks access to an Engine's REST web service based on resident Engine metadata which defines what
 * entities can access that service.// ww  w. j  av a2 s.c o m
 *
 * @param request Standard HttpServletRequest
 * @param response Standard HttpServletResponse
 * @param object handler
 * @return true if the caller is authorised to use the service
 * @throws Exception if an error occurs
 */
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object)
        throws Exception {
    String idpProviderID = null;
    ResponseDocument responseDocument = null;
    ResponseType samlResponse = null;

    try {
        if (request.getParameter("SAMLResponse") == null) {
            logger.error("Could not process the AuthenticatonStatement from the IdP as there isn't one!");
            request.setAttribute("error",
                    messages.getMessage("engine.error.cannot.parse.authnstmnt", null, request.getLocale()));
            request.setAttribute("message",
                    messages.getMessage("engine.error.no.authn.stmnt", null, request.getLocale()));
            request.getRequestDispatcher(errorPage).forward(request, response);
            return false;
        }

        // Parse the SAML Response containing the AuthenticationStatement coming from the IdP
        responseDocument = ResponseDocument.Factory
                .parse(new StringReader(Utils.decodeBase64(request.getParameter("SAMLResponse"))));

        dumpSAML(responseDocument);

        samlResponse = responseDocument.getResponse();
        AssertionType assertion = samlResponse.getAssertionArray()[0];
        idpProviderID = assertion.getIssuer();
        AuthenticationStatementType authStatement = assertion.getAuthenticationStatementArray()[0];

        request.setAttribute(Config.REQUEST_ATTRIBUTE_SAML_RESPONSE, samlResponse);
        request.setAttribute(Config.REQUEST_ATTRIBUTE_IDP_PROVIDER_ID, idpProviderID);
        request.setAttribute(Config.REQUEST_ATTRIBUTE_IDP_NAME_IDENTIFIER,
                authStatement.getSubject().getNameIdentifier().getStringValue());
    } catch (Exception e) {
        logger.error("Could not process the AuthenticatonStatement from the IdP", e);
        request.setAttribute("error",
                messages.getMessage("engine.error.cannot.parse.authnstmnt", null, request.getLocale()));
        request.setAttribute("message", e.getMessage());
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    /* Find the IdP's metadata from our store. This is based on it's providerId, which is matched
     * against the entityID in the IdP's EntityDescriptor file.
     */
    EntityFarm farm = (EntityFarm) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_ENGINE_ENTITY_FARM);
    EntityManager manager = farm.getEntityManagerForID(idpProviderID);
    if (manager == null) {
        logger.error("Could not find manager for IdP '" + idpProviderID + "' in the metadata repository");
        request.setAttribute("error",
                messages.getMessage("engine.error.no.idp.metadata", null, request.getLocale()));
        request.setAttribute("message", idpProviderID);
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }
    if (manager.getMetadata(idpProviderID) != null) {
        // Apply the trust rules to the entity
        if (manager.getTrustEngine() != null) {
            if (manager.getTrustEngine().trustEntity(manager.getMetadata(idpProviderID), responseDocument)) {
                request.setAttribute(Config.REQUEST_ATTRIBUTE_IDP_METADATA, manager.getMetadata(idpProviderID));
            } else {
                logger.error("Trust failed for the IdP");
                request.setAttribute("error", messages.getMessage("engine.error.idp.sig.failed.verification",
                        null, request.getLocale()));
                request.setAttribute("message", idpProviderID);
                request.getRequestDispatcher(errorPage).forward(request, response);
                return false;
            }
        }
    } else {
        logger.error("Could not get IdP '" + idpProviderID + "' from the manager");
        request.setAttribute("error",
                messages.getMessage("engine.error.no.idp.metadata", null, request.getLocale()));
        request.setAttribute("message", idpProviderID);
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    return true;
}

From source file:com.colegiocefas.cefasrrhh.servlets.subirImagen.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w  w w  . j  ava 2s.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 {
    String ajaxUpdateResult = "Error";
    try {
        List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
            } else {
                Date fecha = Calendar.getInstance().getTime();
                SimpleDateFormat formato = new SimpleDateFormat("yyyyMMdd-hhmmss-");
                String nombreImagen = formato.format(fecha);
                HttpSession sesionOk = request.getSession();
                String usuario = (String) sesionOk.getAttribute("usuario");
                if (usuario == null) {
                    request.getRequestDispatcher("index.jsp").forward(request, response);
                    return;
                }
                nombreImagen += usuario;
                //String fileName = item.getName();
                response.setContentType("text/plain");
                response.setCharacterEncoding("UTF-8");
                String realPath = request.getSession().getServletContext().getRealPath("/");
                File fichero = new File(realPath + "img/fotos/", nombreImagen + ".png");
                item.write(fichero);
                ajaxUpdateResult = "img/fotos/" + fichero.getName();
            }
        }
    } catch (Exception e) {
        ajaxUpdateResult = "ErrorException";
        throw new ServletException("Parsing file upload failed.", e);
    }
    response.getWriter().print(ajaxUpdateResult);
}

From source file:com.berwickheights.spring.svc.GenEmailMsgSvcImpl.java

public String genEmailMsgFromJSP(HttpServletRequest request, HttpServletResponse response, String jspPagePath,
        Map<String, Object> extraPageArgs) throws IOException, ServletException {
    Map<String, Object> args = new HashMap<String, Object>();

    // Add extra arguments if provided
    if (extraPageArgs != null) {
        for (String key : extraPageArgs.keySet()) {
            args.put(key, extraPageArgs.get(key));
        }/*  w  ww.  jav a 2  s.c  om*/
    }

    // Set up data for jsp/jstl template
    request.setAttribute("args", args);

    // Create an output stream
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Create the "dummy" response object
    RedirectingServletResponse dummyResponse;
    dummyResponse = new RedirectingServletResponse(response, baos);

    // Get a request dispatcher for the email msg body to load
    RequestDispatcher rd = request.getRequestDispatcher(jspPagePath);

    // Execute JSP
    rd.include(request, dummyResponse);

    //
    // Get email message body
    // NB: JSP page must have "out.flush()" at end of file to flush Tomcat buffers
    // so that ByteArrayOutputStream (baos) will contain the mail message text
    //
    dummyResponse.flushBuffer();
    String emailText = baos.toString();
    baos.close();

    if (logger.isDebugEnabled()) {
        logger.debug("Generated message: " + emailText);
    }

    return emailText;
}

From source file:Index.LoginServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  ww.j a  va2s .  c om*/
 *
 * @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:com.bdnc.ecommercebdnc.command.CadastraProduto.java

@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = null;
        try {/*  w w  w.  j  a v a  2  s .  c  o m*/
            items = (List<FileItem>) upload.parseRequest(request);

            Produto produto = new Produto();
            produto.setFoto(items.get(0).get());
            produto.setDescricao(items.get(1).getString("UTF-8"));
            produto.setValor(Double.parseDouble(items.get(2).getString("UTF-8")));

            LojaService lojaService = new LojaService();
            lojaService.salvarProduto(produto);

            request.getSession().setAttribute("produtos", lojaService.listarProdutos());

            RequestDispatcher dispather = request.getRequestDispatcher("cadastroproduto.jsp");
            dispather.forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:info.magnolia.cms.security.SecurityFilter.java

/**
 * Authenticate on basic headers.//from   ww  w.  ja v a 2 s . c  o m
 * @param request HttpServletRequest
 * @param response HttpServletResponst
 * @return <code>true</code> if the user is authenticated
 */
private boolean authenticate(HttpServletRequest request, HttpServletResponse response) {
    try {
        if (Path.getURI(request).startsWith(this.filterConfig.getInitParameter(UNSECURED_URI))) {
            return true;
        }
        if (!Authenticator.authenticate(request)) {
            // invalidate previous session

            HttpSession httpsession = request.getSession(false);
            if (httpsession != null) {
                httpsession.invalidate();
            }
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            if (StringUtils.equalsIgnoreCase(this.filterConfig.getInitParameter(AUTH_TYPE), AUTH_TYPE_BASIC)) {
                response.setHeader("WWW-Authenticate", "BASIC realm=\"" + Server.getBasicRealm() + "\"");
            } else {
                request.getRequestDispatcher(this.filterConfig.getInitParameter(LOGIN_FORM)).include(request,
                        response);
            }
            return false;
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return false;
    }

    return true;
}

From source file:atd.backend.Login.java

/**
 * Vangt het POST request van de login.jsp en controlleerd deze met de
 * database/* ww  w .  j av a2  s  .  c  o  m*/
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String username = req.getParameter("username").toLowerCase();

    try {
        Class.forName("org.apache.commons.codec.digest.DigestUtils");
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String pass = org.apache.commons.codec.digest.DigestUtils.sha256Hex(req.getParameter("password"));
    RequestDispatcher rd = null;

    if (UsersDAO.authUser(username, pass)
            || (username.equals(adminUser)) && req.getParameter("password").equals(adminPwd)) {
        // Controlleer of het filter een redirect gezet heeft
        if (req.getAttribute("redirect") == null || req.getAttribute("redirect").equals("")) {
            rd = req.getRequestDispatcher("/index.jsp");
        } else {
            rd = req.getRequestDispatcher((String) req.getAttribute("redirect"));
            req.removeAttribute("redirect");
        }

        req.getSession().setAttribute("username", UsersDAO.searchUser(username));
        resp.addCookie(new Cookie("username", username));
        java.util.Date dt = new java.util.Date();
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(dt);
        LogDAO.setLog(req.getRemoteAddr(), currentTime, UsersDAO.searchUser(username), null);
        rd.forward(req, resp);
    } else if (KlantenDAO.authKlant(username, pass)) {
        if (req.getAttribute("redirect") == null || req.getAttribute("redirect").equals("")) {
            rd = req.getRequestDispatcher("/index.jsp");
        } else {
            rd = req.getRequestDispatcher((String) req.getAttribute("redirect"));
            req.removeAttribute("redirect");
        }
        req.getSession().setAttribute("username", KlantenDAO.searchKlant(username));
        System.out.println("klant setten");

        resp.addCookie(new Cookie("username", username));

        java.util.Date dt = new java.util.Date();
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(dt);

        LogDAO.setLog(req.getRemoteAddr(), currentTime, null, KlantenDAO.searchKlant(username));
        rd.forward(req, resp);
    } else {
        rd = req.getRequestDispatcher("/login/login.jsp");
        req.setAttribute("error",
                "<div class=\"alert alert-danger\" role=\"alert\"> <span class=\"sr-only\">Error:</span> ongeldige inlog gegevens </div>");
        rd.forward(req, resp);
    }
}

From source file:info.magnolia.cms.servlets.UUIDRequestDispatcher.java

/**
 * @param request//from ww w. j  a  va2  s.  c  om
 * @param response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String repositoryName = request.getParameter(ATTRIBUTE_REPOSITRY_NAME);
    String workspaceName = request.getParameter(ATTRIBUTE_WORKSPACE_NAME);
    String uuid = request.getParameter(ATTRIBUTE_UUID);
    String extension = Path.getExtension(request);
    if (StringUtils.isEmpty(repositoryName)) {
        repositoryName = ContentRepository.WEBSITE;
    }
    if (StringUtils.isEmpty(workspaceName)) {
        workspaceName = ContentRepository.getDefaultWorkspace(repositoryName);
    }
    try {
        String handle = ContentRepository.getHierarchyManager(repositoryName, workspaceName)
                .getContentByUUID(uuid).getHandle();
        handle = (handle + "." + extension);
        RequestDispatcher dispatcher = request.getRequestDispatcher(handle);
        dispatcher.forward(request, response);
    } catch (Exception e) {
        log.error("Failed to retrieve content for UUID : " + uuid + " , " + e.getMessage());
        if (log.isDebugEnabled())
            log.debug("Exception caught", e);
    }

}

From source file:net.sourceforge.hunterj.javadocViewer.JavadocViewerServlet.java

/**
 * //from   w ww  . ja v  a 2  s .  c  o  m
 * @param request
 * @param response
 * @throws IOException 
 * @throws ServletException 
 */
private void dispatchToView(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    request.setAttribute(JVConst.DOCHOME_ATTR.value, session.getAttribute(JVConst.DOCHOME_ATTR.value));
    String docHomeOpts = (String) request.getSession().getAttribute(JVConst.DOCHOME_OPTS.value);
    if (docHomeOpts == null) {
        docHomeOpts = this.getJavadocHomeOpts(Paths.get(this.saveFilePathStr));
        session.setAttribute(JVConst.DOCHOME_OPTS.value, docHomeOpts);
    }
    request.setAttribute(JVConst.DOCHOME_OPTS.value, docHomeOpts);
    RequestDispatcher dispatch = request.getRequestDispatcher(response.encodeURL(JVConst.MAIN_JSP.value));
    dispatch.forward(request, response);
}