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:Controller.login.java

/**
 * Handles the HTTP <code>POST</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 doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String email = request.getParameter("inputEmail");
    String password = request.getParameter("inputPassword");
    String remember = request.getParameter("remember");

    System.out.println("remember ne mnow " + email);

    LoginImplementation loginCheckObject = new LoginImplementation();

    JSONObject userData = (loginCheckObject.loginNow(email, password, remember));
    System.out.println(userData);
    if (userData.has("error")) {
        RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
        request.setAttribute("loginError", "error");
        rd.include(request, response);

    } else {

        if ("yes".equals(remember)) {
            System.out.println("apples");
            HttpSession session = request.getSession();
            session.setAttribute("user", userData);
            //setting session to expiry in 30 mins
            session.setMaxInactiveInterval(30 * 60);
            Cookie userName = new Cookie("user", email);
            userName.setMaxAge(30 * 60);
            response.addCookie(userName);
        }
        request.setAttribute("userData", userData);
        RequestDispatcher rd = request.getRequestDispatcher("views/home.jsp");
        rd.forward(request, response);
        return;
    }

    out.close();
}

From source file:io.muic.ooc.webapp.servlet.UserAddServlet.java

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

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String firstname = request.getParameter("firstname");

    if (securityService.isAuthorized(request)) {

        if (!StringUtils.isBlank(username) && !StringUtils.isBlank(password)) {

            if (securityService.allowAdd(username)) {
                PrintWriter out = response.getWriter();
                new DatabaseService().insertDB(username, securityService.hashPassword(password), firstname);
                //                    new DatabaseService().insertDB(username,password,firstname);
                RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/home.jsp");
                rd.include(request, response);
                out.print("<p style=\"color:green\">Add User Successful</p>");
            } else {
                String error = "Username already exist";
                request.setAttribute("error", error);
                RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/adduser.jsp");
                rd.include(request, response);
            }//from  w w w .  j a  v  a 2  s.c o m
        } else {
            String error = "Username or password is missing.";
            request.setAttribute("error", error);
            RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/adduser.jsp");
            rd.include(request, response);
        }
    } else {
        response.sendRedirect("/");
    }
}

From source file:controllers.LoginController.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/* w w  w  . j av  a2 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 {
    response.setContentType("text/html;charset=UTF-8");
    User user = (User) request.getAttribute("user");
    if (user != null) {
        // User has been already registered
        response.sendRedirect(request.getContextPath() + "/home");
    } else {
        // Remove user's session
        HttpSession session = request.getSession(false);
        String error = null;
        if (session != null && (error = (String) session.getAttribute("error")) != null) {
            request.setAttribute("error", error);
            session.removeAttribute("error");
        }
        RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
        rd.forward(request, response);
    }
}

From source file:Ctrl.CtrlProducts.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w  w w. ja  va 2 s.  co  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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        String action = request.getParameter("action");

        if (action.equals("Tm Kim")) {
            String name = request.getParameter("txtTenSP");
            Products sp = new Products();
            List<Product> list = new ArrayList<Product>();
            list = sp.HienthiSPadmin(name);
            request.setAttribute("listSP", list);
            RequestDispatcher rd = request.getRequestDispatcher("Product.jsp");
            rd.forward(request, response);
        } else if (action.equals("Delete")) {
            String code = request.getParameter("txtcode");
            Products sp = new Products();
            sp.delete(code);
            String url = "Product.jsp";
            RequestDispatcher rd = request.getRequestDispatcher(url);
            rd.forward(request, response);
        } else if (action.equals("Edit")) {
            String code = request.getParameter("txtcode").trim();
            String name = request.getParameter("txtname");
            String pri = request.getParameter("txtprice");
            String manhinh = request.getParameter("txtmanhinh");
            String ram = request.getParameter("txtram");
            String hdd = request.getParameter("txthdd");
            String cpu = request.getParameter("txtcpu");
            String khuyenmai = request.getParameter("txtkhuyenmai");
            String baohanh = request.getParameter("txtbaohanh");
            String hinh = request.getParameter("txthinh");
            int nkhuyenmai = Integer.parseInt(khuyenmai);
            float fpri = Float.parseFloat(pri);
            Product sp = new Product(code, name, fpri, manhinh, ram, hdd, cpu, nkhuyenmai, baohanh, hinh);
            request.setAttribute("SP", sp);
            RequestDispatcher rd = request.getRequestDispatcher("chinhsuasp.jsp");
            rd.forward(request, response);

        } else if (action.equals("Update")) {

            String code = request.getParameter("txtcode");
            String name = request.getParameter("txtname");
            String pri = request.getParameter("txtprice");
            String manhinh = request.getParameter("txtmanhinh");
            String ram = request.getParameter("txtram");
            String hdd = request.getParameter("txthdd");
            String cpu = request.getParameter("txtcpu");
            String khuyenmai = request.getParameter("txtkhuyenmai");
            String baohanh = request.getParameter("txtbaohanh");
            String hinh = request.getParameter("txthinh");
            String ten = request.getParameter("txtTenSP");
            int nkhuyenmai = Integer.parseInt(khuyenmai);
            float fpri = Float.parseFloat(pri);
            String url = "Product.jsp";
            Products sp = new Products();
            sp.insert(name, fpri, manhinh, ram, hdd, cpu, nkhuyenmai, baohanh, hinh, code);
            RequestDispatcher rd = request.getRequestDispatcher(url);
            rd.forward(request, response);

        } else if (action.equals("Thm")) {
            String code = request.getParameter("txtcode");
            String name = request.getParameter("txtname");
            String pri = request.getParameter("txtprice");
            String manhinh = request.getParameter("txtmanhinh");
            String ram = request.getParameter("txtram");
            String hdd = request.getParameter("txthdd");
            String cpu = request.getParameter("txtcpu");
            String khuyenmai = request.getParameter("txtkhuyenmai");
            String baohanh = request.getParameter("txtbaohanh");
            String hinh = request.getParameter("txthinh");

            int nkhuyenmai = Integer.parseInt(khuyenmai);
            float fpri = Float.parseFloat(pri);
            Products sp = new Products();
            sp.newsp(code, name, fpri, manhinh, ram, hdd, cpu, nkhuyenmai, baohanh, hinh);
            RequestDispatcher rd = request.getRequestDispatcher("CtrlProducts?action=Tm+Kim&txtTenSP");
            rd.forward(request, response);

        } else if (action.equals("Thm Sn Phm")) {
            RequestDispatcher rd = request.getRequestDispatcher("newsp.jsp");
            rd.forward(request, response);
        } else if (action.equals("Qun l ti khon")) {
            RequestDispatcher rd = request.getRequestDispatcher("Quanliuser.jsp");
            rd.forward(request, response);
        }
        if (action.equals("Logout")) {
            HttpSession session = request.getSession(true);
            session.invalidate();
            RequestDispatcher rd = request.getRequestDispatcher("Trangchu.jsp");
            rd.forward(request, response);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:io.muic.ooc.servlet.LoginServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // do login post logic
    // extract username and password from request
    if (SecurityService.isAuthorized(request)) {
        response.sendRedirect("/home");
    } else {/*  w w w. ja  v  a 2s .  c  om*/
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (!StringUtils.isBlank(username) && !StringUtils.isBlank(password)) {
            if (SecurityService.authenticate(username, password, request)) {
                response.sendRedirect("home");
            } else {
                String error = "Wrong username or password.";
                request.setAttribute("error", error);
                RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/login.jsp");
                rd.include(request, response);
            }
        } else {
            String error = "Username or password is missing.";
            request.setAttribute("error", error);
            RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/login.jsp");
            rd.include(request, response);
        }
    }

}

From source file:com.alfaariss.oa.util.saml2.binding.artifact.JSPHTTPArtifactEncoder.java

private void postEncode(SAMLMessageContext<SAMLObject, SAMLObject, NameID> artifactContext,
        HTTPOutTransport outTransport) throws MessageEncodingException {
    InTransport inTransport = artifactContext.getInboundMessageTransport();
    HttpServletRequest request = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
    HttpServletResponse response = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();

    request.setAttribute("action", getEndpointURL(artifactContext));
    request.setAttribute("SAMLArt", buildArtifact(artifactContext).base64Encode());

    if (checkRelayState(artifactContext.getRelayState())) {
        request.setAttribute("RelayState", HTTPTransportUtils.urlEncode(artifactContext.getRelayState()));
    }//from  w  ww .j  a v a2 s.c  o m
    try {
        _logger.debug("Forward caller to JSP template");
        RequestDispatcher oDispatcher = request.getRequestDispatcher(_sTemplateLocation);

        oDispatcher.forward(request, response);
    } catch (ServletException e) {
        _logger.warn("Could not process forward to JSP due to Servlet Error", e);
        throw new MessageEncodingException("Could not process forward to JSP");
    } catch (IOException e) {
        _logger.warn("Could not process forward to JSP due to I/O Error", e);
        throw new MessageEncodingException("Could not process forward to JSP");
    }
}

From source file:com.googlesource.gerrit.plugins.github.wizard.VelocityControllerServlet.java

private void redirectToNextStep(HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException {
    String sourceUri = req.getRequestURI();
    int pathPos = sourceUri.lastIndexOf('/') + 1;
    String sourcePage = sourceUri.substring(pathPos);
    String sourcePath = sourceUri.substring(0, pathPos);
    int queryStringStart = sourcePage.indexOf('?');
    if (queryStringStart > 0) {
        sourcePage = sourcePage.substring(0, queryStringStart);
    }//  www .  ja va 2s.c  o m
    NextPage nextPage = githubConfig.getNextPage(sourcePage);
    if (nextPage != null) {
        if (nextPage.redirect) {
            resp.sendRedirect(nextPageURL(sourcePath, nextPage));
        } else {
            RequestDispatcher requestDispatcher = req.getRequestDispatcher(nextPageURL(sourcePath, nextPage));
            req.setAttribute("destUrl", nextPage);
            requestDispatcher.forward(req, resp);
        }
    }
}

From source file:Controllers.EditItem.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/* 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 {
    String id = request.getParameter("id");
    Item item = ItemRepository.getItemById(id);
    request.setAttribute("id", id);
    request.setAttribute("name", item.getName());
    request.setAttribute("price", item.getPrice());
    request.setAttribute("currentCategory", item.getCategory().getId());
    request.setAttribute("itemCode", item.getItemCode());
    request.setAttribute("quantity", item.getQuantity());
    request.setAttribute("image", item.getImage());

    ArrayList<Category> categories = ItemRepository.getCategories();

    request.setAttribute("categories", categories);

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

}

From source file:org.guanxi.idp.service.AuthHandler.java

/**
 * Looks for an existing GuanxiPrincipal referenced by a request cookie. When a cookie is created after
 * a successful authentication at the IdP, either via the login page or an application cookie handler,
 * the corresponding GuanxiPrincipal is stored in the servlet context against the cookie value.
 * The new GuanxiPrincipal that is created after successful authentication is stored in the servlet
 * context under GuanxiPrincipal.id//from   ww w . j  ava  2  s  .  com
 *
 * @param request Standard HttpServletRequest
 * @param response Standard HttpServletResponse
 * @param object handler
 * @return true 
 * @throws Exception if an error occurs
 */
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object)
        throws Exception {
    request.setCharacterEncoding("UTF-8");

    String missingParams = checkRequestParameters(request);
    if (missingParams != null) {
        logger.info("Missing param(s) : " + missingParams);
        request.setAttribute("message",
                messageSource.getMessage("missing.param", new Object[] { missingParams }, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    IdpDocument.Idp idpConfig = (IdpDocument.Idp) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_CONFIG);

    boolean spSupported = false;
    EntityFarm farm = (EntityFarm) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_ENTITY_FARM);
    EntityManager manager = farm.getEntityManagerForID(request.getParameter(spIDRequestParam));
    if (manager != null) {
        SPMetadata metadata = (SPMetadata) manager.getMetadata(request.getParameter(spIDRequestParam));
        // Apply the trust rules to the SP
        if (metadata != null) {
            if (manager.getTrustEngine().trustEntity(metadata, request.getParameter("shire"))) {
                spSupported = true;
            } else {
                logger.error("Trust failure for " + request.getParameter(spIDRequestParam) + " --> "
                        + request.getParameter("shire"));
            }
        } else {
            logger.error("No Metadata Manager found for " + request.getParameter(spIDRequestParam));
        }
    } else {
        logger.error("No Metadata Manager");
    }

    // Check the locally registered SPs
    if (!spSupported) {
        ServiceProvider[] spList = idpConfig.getServiceProviderArray();
        for (int c = 0; c < spList.length; c++) {
            if (spList[c].getName().equals(request.getParameter(spIDRequestParam))) {
                // If it's in here, we trust it explicitly
                spSupported = true;
            }
        }
    }

    // Did we find the service provider?
    if (!spSupported) {
        logger.error(
                "Service Provider providerId " + request.getParameter(spIDRequestParam) + " not supported");
        request.setAttribute("message", messageSource.getMessage("sp.not.supported",
                new Object[] { request.getParameter(spIDRequestParam) }, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    // Look for our cookie. This is after any application cookie handler has authenticated the user
    String cookieName = getCookieName();
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int c = 0; c < cookies.length; c++) {
            if (cookies[c].getName().equals(cookieName)) {
                // Retrieve the principal from the servlet context
                if (servletContext.getAttribute(cookies[c].getValue()) == null) {
                    // Out of date cookie value, so remove the cookie
                    cookies[c].setMaxAge(0);
                    response.addCookie(cookies[c]);
                } else {
                    // Found the principal from a previously established authentication
                    request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL,
                            (GuanxiPrincipal) servletContext.getAttribute(cookies[c].getValue()));
                    return true;
                }
            }
        }
    }

    // Are we getting an authentication request from the login page?
    if (request.getParameter("guanxi:mode") != null) {
        if (request.getParameter("guanxi:mode").equalsIgnoreCase("authenticate")) {
            // Get a new GuanxiPrincipal...
            GuanxiPrincipal principal = gxPrincipalFactory.createNewGuanxiPrincipal(request);
            if (authenticator.authenticate(principal, request.getParameter("userid"),
                    request.getParameter("password"))) {
                // ...associate it with a login name...
                if (principal.getName() == null) {
                    //The login name from the authenticator page
                    principal.setName(request.getParameter("userid"));
                }
                // ...store it in the request for the SSO to use...
                request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL, principal);
                // ...and store it in application scope for the rest of the profile to use
                servletContext.setAttribute(principal.getUniqueId(), principal);

                // Get a new cookie ready to reference the principal in the servlet context
                Cookie cookie = new Cookie(getCookieName(), principal.getUniqueId());
                cookie.setDomain((String) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_DOMAIN));
                cookie.setPath(idpConfig.getCookie().getPath());
                if (((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE)))
                        .intValue() != -1)
                    cookie.setMaxAge(
                            ((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE)))
                                    .intValue());
                response.addCookie(cookie);

                return true;
            } // if (authenticator.authenticate...
            else {
                logger.error("Authentication error : " + authenticator.getErrorMessage());
                request.setAttribute("message",
                        messageSource.getMessage("authentication.error", null, request.getLocale()));
                request.getRequestDispatcher(errorPage).forward(request, response);
                return false;
            }
        }
    }

    // No embedded cookie authentication or local auth, so show the login page
    String authPage = null;
    AuthPage[] authPages = idpConfig.getAuthenticatorPages().getAuthPageArray();
    for (int c = 0; c < authPages.length; c++) {
        // We'll use the default auth page if none is specified for this service provider
        if (authPages[c].getProviderId().equals(Guanxi.DEFAULT_AUTH_PAGE_MARKER)) {
            authPage = authPages[c].getUrl();
        }

        // Customised auth page for this service provider
        if (authPages[c].getProviderId().equals(request.getParameter(spIDRequestParam))) {
            authPage = authPages[c].getUrl();
        }
    }

    addRequiredParamsAsPrefixedAttributes(request);
    request.getRequestDispatcher(authPage).forward(request, response);

    return false;
}

From source file:com.arcadian.loginservlet.LecturesServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        lecturesService = new LecturesService();
        HttpSession session = request.getSession();
        username = (String) session.getAttribute("username");
        ArrayList alstClassName = lecturesService.getUserClass(username);
        request.setAttribute("alstClassName", alstClassName);

        ArrayList<LecturesBean> alstLectures = lecturesService.fetchlectures(username);
        request.setAttribute("alstLectures", alstLectures);

        RequestDispatcher dispatcher = request.getRequestDispatcher("dashboard/lectures.jsp");
        dispatcher.forward(request, response);
    }/*from  www  . j a  v  a 2  s. c  om*/
}