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:de.highbyte_le.weberknecht.request.view.WebActionProcessor.java

protected void processJsp(HttpServletRequest request, HttpServletResponse response, View view,
        Map<String, Object> modelMap, Object action) throws ServletException, IOException {
    if (log.isDebugEnabled())
        log.debug("processJsp() - forward the request to the given view: " + view.getJspFileName());

    //add models to request
    if (modelMap != null) {
        ModelHelper modelHelper = new ModelHelper(request, servletContext);
        for (Entry<String, Object> e : modelMap.entrySet()) {
            modelHelper.set(e.getKey(), e.getValue());
        }//from w  ww  .  ja v  a 2  s .c  o m
    }

    //forward the request to the given view
    RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/" + view.getJspFileName());
    dispatcher.forward(request, response);
}

From source file:ForwardException.java

/** Called in response to a GET request (data encoded in the URL) */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ServletContext application = getServletContext();

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

    try {//from   w  w w  .  j a va  2  s .c om
        // to do: logic code and main HTML goes here.

        // simulate an error condition happening at run time.
        if (this instanceof Servlet)
            throw new RuntimeException("Test exception");

        out.println("<!DOCTYPE html PUBLIC " + "\"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"
                + "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"\n" + ">");
        out.println("<html>");
        out.println("<head><title>Servlet Output</title></head>");
        out.println("<body>");

        // BOILERPLATE ending
        out.println("</body>");
        out.println("</html>");
        out.close();

    } catch (Exception exc) {

        // dispatch to JSP to display the error.
        RequestDispatcher rd = application.getRequestDispatcher("/oops.jsp");
        request.setAttribute("javax.servlet.jsp.jspException", exc);
        rd.forward(request, response);
    }
}

From source file:Functions.UploadFileServlet.java

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

    String houseId = "";
    String owner = (String) request.getSession().getAttribute("username");
    String url = "/errorPage.jsp";
    String message = "fgd";
    //System.out.println("houseId= "+houseId);
    //System.out.println("owner= "+owner);
    response.setContentType("text/html");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {//from  ww  w  .j  a va2s  .c  o  m
            FileItemIterator itr = upload.getItemIterator(request);
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    //do something
                    String fieldName = item.getFieldName();
                    InputStream is = item.openStream();
                    byte b[] = new byte[is.available()];
                    is.read(b);
                    String value = new String(b);
                    if ("houseIddd".equals(fieldName)) {
                        houseId = value;
                    }
                    response.getWriter().println(fieldName + ":" + value + "<br/>");
                } else {
                    System.out.println("MPHKE STO ELSE GIA NA BALEI SPITIA");
                    //upload file
                    String path = getServletContext().getRealPath("/");
                    //String path = getServletContext().getContextPath()+"/";

                    if (FileUpload.processFile(path, item, houseId, owner)) {
                        System.out.println("MPHKE STO processfile!");
                        //response.getWriter().println("file uploaded successfully");
                        message = "file uploaded successfully";

                        url = "/Estateprofile.jsp?houseId=" + houseId + "&houseOwner=" + owner + "&message="
                                + message;

                    } else {
                        message = "file uploading failed";
                        url = "/Estateprofile.jsp?houseId=" + houseId + "&houseOwner=" + owner + "&message="
                                + message;

                        //response.getWriter().println("file uploading failed");
                    }
                }
            }
        } catch (FileUploadException ex) {
            ex.printStackTrace();
            //Logger.getLogger(UploadFileServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }
}

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

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    EntityManager em = (EntityManager) request.getSession().getAttribute("em");

    RequestDispatcher rd = request.getRequestDispatcher("/admin/check-in-student.jsp");
    rd.forward(request, response);
}

From source file:algorithm.laddress.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w  w  w . j a  va  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 doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    // Create path components to save the file
    final String path = "C:\\Users\\Rads\\Documents\\NetBeansProjects\\capstone\\src\\java\\algorithm\\";
    final Part filePart = request.getPart("file");
    final String fileName = getFileName(filePart);

    OutputStream out = null;
    InputStream filecontent = null;
    final PrintWriter writer = response.getWriter();

    try {
        out = new FileOutputStream(new File(path + File.separator + fileName));
        filecontent = filePart.getInputStream();

        int read = 0;
        final byte[] bytes = new byte[1024];

        while ((read = filecontent.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        // writer.println("New file " + fileName + " created at " + path);
        LOGGER.log(Level.INFO, "File{0}being uploaded to {1}", new Object[] { fileName, path });
    } catch (FileNotFoundException fne) {
        writer.println("You either did not specify a file to upload or are "
                + "trying to upload a file to a protected or nonexistent " + "location.");
        writer.println("<br/> ERROR: " + fne.getMessage());

        LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}", new Object[] { fne.getMessage() });
    }

    Scanner s = null;
    String listOfAddresses = "";
    try {
        String address = fileName;
        String dname = "C:\\Users\\Rads\\Documents\\NetBeansProjects\\capstone\\src\\java\\algorithm\\"
                + address;
        File f = new File(dname);
        s = new Scanner(f);
        //s.useDelimiter(",");   //Use the normal expression and exclude data we imagine they are not "WORDS"
    } catch (FileNotFoundException e) {

    }
    while (s.hasNextLine()) {
        String[] curr = s.nextLine().split(",");
        listOfAddresses = listOfAddresses + "<br/>" + curr[1];
    }
    String nextView = "user.jsp";
    request.setAttribute("Address", listOfAddresses);
    RequestDispatcher view = request.getRequestDispatcher(nextView);
    view.forward(request, response);
}

From source file:eu.impact_project.iif.t2.client.InfoGenerator.java

/**
 * Gets information about a workflow./*from  w w w .j  a  v  a 2s .  c  om*/
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession(true);
    String wfId = request.getParameter("id");
    String urlString = "http://www.myexperiment.org/workflow.xml?id=" + wfId;

    String user = (String) session.getAttribute("user");
    String password = (String) session.getAttribute("password");

    // prepare httpclient for basic authentication
    HttpClient client = new HttpClient();
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(new AuthScope("www.myexperiment.org", 80),
            new UsernamePasswordCredentials(user, password));

    GetMethod get = new GetMethod(urlString);
    get.setDoAuthentication(true);

    client.executeMethod(get);
    InputStream responseBody = get.getResponseBodyAsStream();

    try {

        SAXBuilder builder = new SAXBuilder();

        Document doc = builder.build(responseBody);

        WorkflowDetails details = new WorkflowDetails();

        Element root = doc.getRootElement();
        details.setTitle(root.getChild("title").getTextTrim());
        details.setDescription(root.getChild("description").getTextTrim());
        details.setImageUrl(root.getChild("preview").getTextTrim());

        session.setAttribute("wfDetails", details);

    } catch (JDOMException e) {
        e.printStackTrace();
    }

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

From source file:org.beangle.security.web.auth.LoginUrlEntryPoint.java

/**
 * Performs the redirect (or forward) to the login form URL.
 *///from   w  ww.j a  v  a 2s  . c  o  m
public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String redirectUrl = null;
    if (serverSideRedirect) {
        String loginForm = determineUrlToUseForThisRequest(httpRequest, httpResponse, authException);
        logger.debug("Server side forward to: {}", loginForm);
        RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(loginForm);
        dispatcher.forward(request, response);
        return;
    } else {
        // redirect to login page. Use https if forceHttps true
        redirectUrl = determineUrlToUseForThisRequest(httpRequest, httpResponse, authException);
    }
    if (!("XMLHttpRequest".equals(httpRequest.getHeader("x-requested-with"))
            || StringUtils.isNotEmpty(httpRequest.getParameter("x-requested-with")))) {
        String backurl = new UrlBuilder(httpRequest.getContextPath()).scheme(request.getScheme())
                .serverName(request.getServerName()).port(request.getServerPort())
                .servletPath(httpRequest.getServletPath()).queryString(httpRequest.getQueryString()).buildUrl();
        redirectUrl += "?backurl=" + URLEncoder.encode(backurl);
    }
    //      httpRequest.getSession().setAttribute("backurl", backurl);
    //      httpRequest.getSession().setAttribute("backurltime", System.currentTimeMillis());
    RedirectUtils.sendRedirect(httpRequest, httpResponse, redirectUrl);
}

From source file:com.adobe.acs.commons.wcm.vanity.impl.VanityURLServiceImpl.java

public boolean dispatch(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException, RepositoryException {
    if (request.getAttribute(VANITY_DISPATCH_CHECK_ATTR) != null) {
        log.trace("Processing a previously vanity dispatched request. Skipping...");
        return false;
    }/*from w ww.ja v  a 2  s  .  c o  m*/

    request.setAttribute(VANITY_DISPATCH_CHECK_ATTR, true);

    final String requestURI = request.getRequestURI();
    final RequestPathInfo mappedPathInfo = new PathInfo(request.getResourceResolver(), requestURI);
    final String candidateVanity = mappedPathInfo.getResourcePath();
    final String pathScope = StringUtils.removeEnd(requestURI, candidateVanity);

    log.debug("Candidate vanity URL to check and dispatch: [ {} ]", candidateVanity);

    // Check if...
    // 1) the candidateVanity and the requestURI are the same; If they are it means the request has already
    // gone through resource resolution and failed so there is no sense in sending it through again.
    // 2) the candidate is in at least 1 sling:vanityPath under /content
    if (!StringUtils.equals(candidateVanity, requestURI) && isVanityPath(pathScope, candidateVanity, request)) {
        log.debug("Forwarding request to vanity resource [ {} ]", candidateVanity);

        final RequestDispatcher requestDispatcher = request.getRequestDispatcher(candidateVanity);
        requestDispatcher.forward(new ExtensionlessRequestWrapper(request), response);
        return true;
    }

    return false;
}

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

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        assignmentService = new ViewAssignmentService();
        HttpSession session = request.getSession();
        username = (String) session.getAttribute("username");
        System.out.println("hello");
        ArrayList alstAssignments = assignmentService.getAssignments(username);
        request.setAttribute("alstAssignmentNotice", alstAssignments);

        RequestDispatcher dispatcher = request.getRequestDispatcher("dashboard/viewassignment.jsp");
        dispatcher.forward(request, response);
    }/*from   w ww .  ja  va  2 s . co m*/
}

From source file:forumbox.PostingnewpostServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssms");
    Date date = new Date();
    String id = dateFormat.format(date);
    //response.addHeader("Access-Control-Allow-Origin", "*");
    PrintWriter out = response.getWriter();

    String typed = request.getParameter("userInput"); //getting the parameter which was sent by the client

    String[] data = new String[3];
    data = typed.split("/");
    // out.print(data[0]);

    String username = data[0];/*from   ww  w . j  a  v a 2 s . c o m*/
    String title = data[1];
    String description = data[2];
    filewrite("/home/dinalidabarera/NetBeansProjects/NewFolder/forum4/admin01/post/", username, title,
            description, response, id);

    //ompare each name in the names array with the user input pattern and when a matching name is found send that in the response
    ServletContext sc = getServletContext();
    RequestDispatcher view = sc.getRequestDispatcher("/addPost.jsp");
    view.forward(request, response);

}