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.cruz.sec.config.ItemBasedAuthenticationFailureHandler.java

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {
    UsernamePasswordAuthenticationToken user = (UsernamePasswordAuthenticationToken) exception
            .getAuthentication();//from w  w  w  .  j av  a  2  s.co m
    System.out.println("Mensaje del error: " + exception.getMessage());
    //        PrincipalsessionInformaction user = request.getUserPrincipal();
    System.out.println("-----------------------------INTENTO FALLIDO-----------------------------");

    //Causas de la autenticacin fallida
    if (exception.getClass().isAssignableFrom(UsernameNotFoundException.class)) {
        System.out.println("INTENTO FALLIDO: El usuario no est registrado en la base de datos ");
        request.setAttribute("ERRORSESSION", "Usuario no registrado, verifique con el administrador");
        request.getRequestDispatcher("/login").forward(request, response);
        //response.sendRedirect("login?err=1");
    } else if (exception.getClass().isAssignableFrom(BadCredentialsException.class)) {
        System.out.println("INTENTO FALLIDO: Creedenciales erroneas");
        request.setAttribute("ERRORSESSION", "Contrasea incorrecta, intente nuevamente");
        request.getRequestDispatcher("/login").forward(request, response);
    } else if (exception.getClass().isAssignableFrom(DisabledException.class)) {
        System.out.println("INTENTO FALLIDO: Usuario desabilitado");
        request.setAttribute("ERRORSESSION", "Usuario deshabilitado, verifique con el administrador");
        request.getRequestDispatcher("/login").forward(request, response);
    } else if (exception.getClass().isAssignableFrom(SessionAuthenticationException.class)) {
        System.out.println("INTENTO FALLIDO: Usuario ya logeado");
        request.setAttribute("ERRORSESSION", "Ya existe una sesión abierta con este usuario");
        request.getRequestDispatcher("/login").forward(request, response);
    } else {
        System.out.println("INTENTO FALLIDO: NO SE QUE PASO");
        request.setAttribute("ERRORSESSION", "No ha sido posible iniciar sesión");
        request.getRequestDispatcher("/login").forward(request, response);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.jena.JenaXMLFileUpload.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!isAuthorizedToDisplayPage(request, response, SimplePermission.USE_ADVANCED_DATA_TOOLS_PAGES.ACTION)) {
        return;//from  www  .ja va2  s.  c  o  m
    }

    VitroRequest vreq = new VitroRequest(request);

    //make a form for uploading a file
    request.setAttribute("title", "Upload file and convert to RDF");
    request.setAttribute("bodyJsp", "/jenaIngest/xmlFileUpload.jsp");

    request.setAttribute("modelNames", getModelMaker(vreq).listModels().toList());
    request.setAttribute("models", null);

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\""
            + vreq.getAppBean().getThemeDir() + "css/edit.css\"/>");

    try {
        rd.forward(request, response);
    } catch (Exception e) {
        System.out.println(this.getClass().getName() + " could not forward to view.");
        System.out.println(e.getMessage());
        System.out.println(e.getStackTrace());
    }

}

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

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

    try {
        // Create a new file upload handler
        DiskFileUpload upload = new DiskFileUpload();

        // Parse the request
        List<FileItem> items = upload.parseRequest(req);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {

                byte[] data = item.get();

                // Hmm...parse images?
                Util.saveSuccessMessage("Service definitions uploaded.", req);

            }
        }
    } catch (Exception e) {
        Util.saveErrorMessage("Unable to upload or parse file.", req);
    }

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

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.RefactorOperationController.java

private String doFixDataTypes(HttpServletRequest request, HttpServletResponse response) {
    try {//from www.java 2 s .c  o m
        super.doGet(request, response);
    } catch (Exception e) {
        log.error(this.getClass().getName() + " caught exception calling doGet()");
    }
    VitroRequest vreq = new VitroRequest(request);

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("bodyJsp", Controllers.CHECK_DATATYPE_PROPERTIES);
    request.setAttribute("title", "Check Datatype Properties");
    request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\""
            + vreq.getAppBean().getThemeDir() + "css/edit.css\"/>");

    OntModel ontModel = ModelAccess.on(getServletContext()).getOntModel(FULL_ASSERTIONS);
    ontModel.enterCriticalSection(Lock.WRITE);
    ArrayList<String> results = new ArrayList<String>();

    try {
        ExtendedIterator dataProperties = ontModel.listDatatypeProperties();
        int hasRange = 0;
        int consistent = 0;
        int inconsistent = 0;
        int total = 0;
        int fixed = 0;
        while (dataProperties.hasNext()) // Iterate through all datatype properties
        {
            total++;
            DatatypeProperty p = (DatatypeProperty) dataProperties.next();
            OntResource range = p.getRange();
            if (range != null)
                hasRange++;
            NodeIterator n = ontModel.listObjectsOfProperty(p);
            //if(!n.hasNext()) results.add(p.getLocalName()+" is not in any statements");
            while (n.hasNext()) // Iterate through all objects of all datatype properties
            {
                RDFNode node = n.nextNode();
                if (node.isLiteral()) {
                    if (range != null) // If a literal has a predicate with a defined range, check and fix the literal's datatype
                    {
                        Literal l = (Literal) node;
                        StmtIterator usingPandL = ontModel.listStatements(null, p, l);
                        int size = 0;
                        results.add("Statements using property " + p.getLocalName() + " and literal "
                                + l.getLexicalForm() + ":");
                        while (usingPandL.hasNext()) {
                            Statement st = usingPandL.nextStatement();
                            results.add("    " + st.getSubject().getLocalName() + " " + p.getLocalName() + " "
                                    + l.getLexicalForm());
                            size++;
                        }
                        usingPandL.close();
                        boolean valid = range.getURI().equals(l.getDatatypeURI());
                        if (valid)
                            consistent += size;
                        else {
                            results.add(p.getLocalName() + " has object " + l.getLexicalForm() + " of type "
                                    + l.getDatatypeURI() + " which is inconsistent");
                            String typeName = "";
                            if (range.getURI().contains(XSDDatatype.XSD))
                                typeName = range.getURI().substring(XSDDatatype.XSD.length() + 1);
                            else
                                results.add("ERROR: " + p.getLocalName()
                                        + " has a range which does not contain the XSD namespace");
                            Literal newLiteral = null;
                            try {
                                newLiteral = ontModel.createTypedLiteral(l.getLexicalForm(),
                                        new XSDDatatype(typeName));
                            } catch (NullPointerException e) {
                                results.add(
                                        "ERROR: Can't create XSDDatatype for literal " + l.getLexicalForm());
                            }
                            StmtIterator badStatements = ontModel.listStatements(null, p, l);
                            StmtIterator toRemove = ontModel.listStatements(null, p, l);
                            ArrayList<Statement> queue = new ArrayList<Statement>();
                            while (badStatements.hasNext()) {
                                Statement badState = badStatements.nextStatement();
                                Statement goodState = ontModel.createStatement(badState.getSubject(), p,
                                        newLiteral);
                                queue.add(goodState);
                                results.add("    Replacing: " + badState.toString());
                                results.add("    With:      " + goodState.toString());
                                fixed++;
                            }
                            for (int i = 0; i < queue.size(); i++) {
                                ontModel.add(queue.get(i));
                            }
                            ontModel.remove(toRemove);
                            badStatements.close();
                            toRemove.close();
                        }
                        if (valid)
                            results.add("Literal " + l.getLexicalForm() + " is in the range of property "
                                    + p.getLocalName());
                        results.add("--------------");
                    }
                } else
                    results.add("ERROR: " + node.toString() + " is not a literal");

            }
            n.close();
        }
        dataProperties.close();

        results.add(hasRange + " of " + total + " datatype properties have defined ranges.");
        results.add("Of the statements that contain datatype properties with defined ranges, " + consistent
                + " are consistent and " + fixed + " are inconsistent.");
        results.add(fixed + " statements have been fixed.");
        //for(int i=0; i<results.size(); i++) System.out.println(results.get(i));

    } finally {
        ontModel.leaveCriticalSection();
    }
    request.setAttribute("results", results);
    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error(this.getClass().getName() + " could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

    return "";
}

From source file:com.jsmartframework.web.manager.ServletControl.java

private void sendRedirect(String path, HttpServletRequest request, HttpServletResponse response,
        boolean authNeeded) throws IOException, ServletException {
    if (request.getServletPath().equals(path)) {
        String url = HANDLER.getForwardPath(path);
        if (url == null) {
            LOGGER.log(Level.SEVERE, "Could not find JSP page for path [" + path + "]");
            return;
        }//from w w  w.jav a 2s  . c  o  m

        // Generate web security token to prevent CSRF attack
        HANDLER.generateWebSecurityToken(request, response);

        // Use Forward request internally case is the same page
        request.getRequestDispatcher(url).forward(request, response);

    } else {
        // Use Redirect response case page had changed (Do not use status 302 once cookies are not set)
        response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
        response.setHeader("Location", getRedirectPath(path, request, authNeeded));
    }
}

From source file:com.wibidata.shopping.servlet.CreateUserServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    final Kiji kiji = (Kiji) getServletContext().getAttribute(KijiContextListener.KIJI_ATTRIBUTE);

    request.setCharacterEncoding("UTF-8");

    final String name = request.getParameter("name");
    final String login = request.getParameter("login");
    final String password = request.getParameter("password");

    if (null == name || name.isEmpty() || null == login || login.isEmpty() || null == password
            || password.isEmpty()) {//from  w w w .ja v a 2 s .  com
        request.setAttribute("name", name);
        request.setAttribute("login", login);
        request.setAttribute("password", password);
        request.setAttribute("error", "All fields are required.");
        request.getRequestDispatcher("/WEB-INF/view/CreateUser.jsp").forward(request, response);
        return;
    }

    final KijiTable userTable = kiji.openTable("kiji_shopping_user");
    final EntityId entityId = userTable.getEntityId(login);
    final KijiTableReader reader = userTable.openTableReader();
    try {
        try {
            // Check if the user already exists first.
            KijiDataRequestBuilder drBuilder = KijiDataRequest.builder();
            drBuilder.newColumnsDef().add("info", "login");
            KijiDataRequest dataRequest = drBuilder.build();

            KijiRowData row = reader.get(entityId, dataRequest);
            if (row.containsColumn("info", "login")) {
                request.setAttribute("name", name);
                request.setAttribute("login", login);
                request.setAttribute("password", password);
                request.setAttribute("error", "That login is already in use, please choose another.");
                request.getRequestDispatcher("/WEB-INF/view/CreateUser.jsp").forward(request, response);
                return;
            }
        } catch (KijiDataRequestException e) {
            throw new IOException(e);
        } finally {
            IOUtils.closeQuietly(reader);
        }

        KijiTableWriter writer = userTable.openTableWriter();
        try {
            // Create the user.
            writer.put(entityId, "info", "name", name);
            writer.put(entityId, "info", "login", login);
            writer.put(entityId, "info", "password", BCrypt.hashpw(password, BCrypt.gensalt()));
        } finally {
            IOUtils.closeQuietly(writer);
        }
    } finally {
        ResourceUtils.releaseOrLog(userTable);
    }

    // Set the login cookie for the user.
    request.getSession().setAttribute("login", login);
    request.getRequestDispatcher("/WEB-INF/view/UserCreated.jsp").forward(request, response);
}

From source file:cn.vlabs.umt.ui.servlet.AuthorizationCodeServlet.java

private void forwordUserInfoPage(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String theme = request.getParameter("theme");
    if ("full".equals(theme)) {
        request.getRequestDispatcher("/oauth/login_full.jsp").forward(request, response);
    } else if ("simple".equals(theme)) {
        request.getRequestDispatcher("/oauth/login_simple.jsp").forward(request, response);
    } else if ("embed".equals(theme)) {
        request.getRequestDispatcher("/oauth/login_embed.jsp").forward(request, response);
    } else if ("coremail".equals(theme)) {
        request.getRequestDispatcher("/oauth/login_coremail.jsp").forward(request, response);
    } else if ("coremail_mobile".equals(theme)) {
        request.getRequestDispatcher("/oauth/login_coremail_mobile.jsp").forward(request, response);
    } else if ("coremail_mobile_ipad".equals(theme)) {
        request.setAttribute("ipadFlag", true);
        request.getRequestDispatcher("/oauth/login_coremail_mobile.jsp").forward(request, response);
    } else if ("cstnet_wifi".equals(theme)) {
        request.getRequestDispatcher("/oauth/login_cstnet_wifi.jsp").forward(request, response);
    } else {/*  w  w  w  . ja  v a 2 s .c  o  m*/
        request.getRequestDispatcher("/oauth/login_full.jsp").forward(request, response);
    }
}

From source file:com.sbu.controller.Feed_Personal_Employer_View_Controller.java

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

    Employer employer = new Employer();
    Employer user;//from   ww w  .j av  a2  s  .c  o  m
    List<Project> projects = new ArrayList();
    List<Skills> skills = new ArrayList();
    request.setCharacterEncoding("UTF-8");
    HttpSession session = request.getSession();
    //finding the user
    int id = Integer.parseInt(request.getParameter("id"));
    user = employerService.getEmployer(id);

    skills = skillsService.getSkillByEmployerId(user.getIdEmployer());
    projects = projectService.getProjectByEmployerId(user.getIdEmployer());

    session.setAttribute("User", user);
    session.setAttribute("projects", projects);
    session.setAttribute("skills", skills);
    //session.setAttribute("allEmployers", employerService.getAllEmployers());

    request.getRequestDispatcher("Personal_Employer.jsp").forward(request, response);

}

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

/**
 * /*from w ww . j  ava2s . 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 {
    Long serviceId = null;
    try {
        serviceId = new Long(req.getParameter("serviceId"));
    } catch (Exception e) {
        // Do nothing
    }
    Service service = null;

    if (serviceId != null) {
        service = store.getServiceById(serviceId);
    }
    if (service == null) {
        service = new Service();
    }

    req.setAttribute("mockservice", service);

    req.setAttribute("requestInspectorList", PluginStore.getInstance().getRequestInspectorImplClassList());
    RequestDispatcher dispatch = req.getRequestDispatcher("/service_setup.jsp");
    dispatch.forward(req, resp);
}

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

/**
 * Redirect based on the mapping in config/server/.node.xml
 * @param request HttpServletRequest/*from  ww  w.  j  av  a2s  .c om*/
 * @param response HttpServletResponse
 * @return <code>true</code> if request has been redirected, <code>false</code> otherwise
 */
private boolean redirect(HttpServletRequest request, HttpServletResponse response) {
    String uri = this.getURIMap(request);
    if (StringUtils.isNotEmpty(uri)) {
        if (!response.isCommitted()) {

            if (uri.startsWith("redirect:")) {
                try {
                    response.sendRedirect(
                            request.getContextPath() + StringUtils.substringAfter(uri, "redirect:"));
                } catch (IOException e) {
                    log.error("Failed to redirect to {}:{}", //$NON-NLS-1$
                            new Object[] { uri, e.getMessage() });
                }
            } else {

                try {
                    request.getRequestDispatcher(uri).forward(request, response);
                } catch (Exception e) {
                    log.error("Failed to forward to {} - {}:{}", //$NON-NLS-1$
                            new Object[] { uri, ClassUtils.getShortClassName(e.getClass()), e.getMessage() });
                }
            }
        } else {
            log.warn("Response is already committed, cannot forward to {} (original URI was {})", //$NON-NLS-1$
                    uri, request.getRequestURI());
        }

        return true;
    }
    return false;
}