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

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {/*w ww  .j  a va2s.c o m*/
        /* TODO output your page here. You may use following sample code. */
        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem fileItem = iter.next();
                if (fileItem.isFormField()) {
                    processFormField(fileItem);
                } else {
                    flItem = fileItem;
                }
            }
            try {
                Photo = flItem.getName();
                File savedFile = new File(
                        "D:\\Latihan Java\\web\\AplikasiPMB\\web\\backend\\images_student\\" + Photo);
                flItem.write(savedFile);
            } catch (Exception e) {
                out.println(e);
                System.out.println(e.getMessage());
            }

            KoneksiDatabase obj_con = new KoneksiDatabase();

            Code b = new Code();
            b.setIdStudent(IdStudent);
            b.setFullname(Fullname);
            b.setIdMajor(IdMajor);
            b.setGender(Gender);
            b.setBirth(Birth);
            b.setSchool(School);
            b.setmajor(Major);
            b.setAddress(Address);
            b.setPhone(Phone);
            b.setEmail(Email);
            b.setGraduation(Grayear);
            b.setPhoto(Photo);

            int i = b.Registration();
            int g = b.doUpdate(IdMajor);
            if (i > 0) {
                RequestDispatcher rd = request.getRequestDispatcher("frontend/index.jsp");
                request.setAttribute("return", "Regristration Successfully!");
                rd.forward(request, response);
                //response.sendRedirect("frontend/index.jsp");
            } else {
                RequestDispatcher rd = request.getRequestDispatcher("frontend/index.jsp");
                request.setAttribute("return", "Registration Failed!");
                rd.forward(request, response);
            }
        }
    } catch (Exception ex) {
        out.println(ex.getCause());
        System.out.println(ex.getMessage());
    }
    /* TODO output your page here. You may use following sample code. */

}

From source file:optional.BasicFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    //extract actionname cut of ".do" results in /actionname
    String look = getActionMappingName(((HttpServletRequest) request).getServletPath());

    System.out.println(">>" + look);

    boolean isMultipart = ServletFileUpload.isMultipartContent((HttpServletRequest) request);

    try {//from  w  w  w  .  j  a  va  2  s . c  o m
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        List /* FileItem */ items = upload.parseRequest((HttpServletRequest) request);

    } catch (FileUploadException e) {

    }

    System.out.println(request.getParameterMap());

    ConfigWrapper config = (ConfigWrapper) actions.get(look);

    if (config == null) {
        return;
    }

    try {
        DirectInterface bean = (DirectInterface) config.getActionclass().newInstance();

        BeanUtils.populate(bean, request.getParameterMap());

        bean.doexecute((HttpServletRequest) request, (HttpServletResponse) response);

    } catch (Exception e) {
        System.out.println();
    }
    //chain.doFilter(request, response);

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

From source file:controller.compareGame.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  ww w  . ja  v  a2s  . 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 processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {

        //            String Name = (String)request.getParameter("combo_zone1");
        //            
        //            Connect obj_con = new Connect();
        //            Connection con = obj_con.Open();
        //            
        //            String sql = "select * from Application_Names where AppName = ?";
        //            PreparedStatement ps = con.prepareStatement(sql);
        //            ps.setString(1, Name);
        //            ResultSet rs = ps.executeQuery();
        //            rs.next();
        //            String Code = rs.getString(2);

        //            boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        //            if(isMultiPart)
        //            {
        //                FileItemFactory factory = new DiskFileItemFactory();
        //                ServletFileUpload upload = new ServletFileUpload(factory);
        //                List items = upload.parseRequest(request);
        //                Iterator<FileItem> iter = items.iterator();
        //                while(iter.hasNext())
        //                {
        //                    FileItem fileItem = iter.next();
        //                    if(fileItem.isFormField())
        //                    {
        //                        processFormField(fileItem);
        //                    }
        //                    else
        //                    {
        //                        flItem = fileItem;
        //                    }
        //                }
        //            }
        Connect obj_con = new Connect();
        Connection con = obj_con.Open();

        String Code = request.getParameter("Code");

        String sql = "delete from tempdata";
        String sql2 = "insert into tempdata(tempdata) values(?)";
        PreparedStatement mw = con.prepareStatement(sql);
        PreparedStatement sl = con.prepareStatement(sql2);
        sl.setString(1, Code);

        mw.executeUpdate();
        sl.executeUpdate();

        Check c = new Check();

        c.setCode(Code);
        int i = c.compareSpecs();

        if (i == 3) {
            RequestDispatcher rd = request.getRequestDispatcher("resultCompareRec.jsp");
            request.setAttribute("return", "Get Recommended Settings");
            rd.forward(request, response);
        } else if (i == 2) {
            RequestDispatcher rd = request.getRequestDispatcher("resultCompareMin.jsp");
            request.setAttribute("return", "Get Minimum Settings");
            rd.forward(request, response);
        } else if (i == 1) {
            RequestDispatcher rd = request.getRequestDispatcher("resultCompareNo.jsp");
            request.setAttribute("return", "Do Not Get Any Settings");
            rd.forward(request, response);
        } else {
            RequestDispatcher rd = request.getRequestDispatcher("compareGame.jsp");
            request.setAttribute("return", "Do Not Get Any Settings");
            rd.forward(request, response);
        }

        //            RequestDispatcher rd = request.getRequestDispatcher("resultCompareRec.jsp");
        //                request.setAttribute("return", "Get Recommended Settings");
        //                rd.forward(request, response);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:controller.uploadPergunta9ArquivoAjuste.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w  ww  .j  a  v  a 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 {

    String idLocal = (String) request.getParameter("idLocal");
    String expressaoModelo = (String) request.getParameter("expressaoModelo");
    String nomeAutorModelo = (String) request.getParameter("nomeAutorModelo");

    String name = "";
    //process only if its multipart content
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    name = new File(item.getName()).getName();
                    //                        item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                    item.write(new File(AbsolutePath + File.separator + name));
                }
            }

            //File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }
    expressaoModelo = expressaoModelo.replace("+", "%2B");
    RequestDispatcher view = getServletContext()
            .getRequestDispatcher("/novoLocalPergunta9?id=" + idLocal + "&nomeArquivoAjuste=" + name
                    + "&expressaoModelo=" + expressaoModelo + "&nomeAutorModelo=" + nomeAutorModelo);
    view.forward(request, response);

    //        request.getRequestDispatcher("/novoLocalPergunta3?id="+idLocal+"&fupload=1&nomeArquivo="+name).forward(request, response);
    // request.getRequestDispatcher("/novoLocalPergunta4?id="+idLocal+"&nomeArquivo="+name).forward(request, response);

}

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

/**
 * Gets the groups and workflow infos from myExperiment
 *///from w  w  w.  j  a va2 s. co m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // to find out own userID
    String urlStringWhoami = "http://www.myexperiment.org/whoami.xml";

    if (request.getParameter("myexp_user") != null && request.getParameter("myexp_password") != null) {

        HttpSession session = request.getSession(true);

        String user = request.getParameter("myexp_user");
        String password = request.getParameter("myexp_password");

        // WorkflowParser also needs the credentials
        session.setAttribute("user", user);
        session.setAttribute("password", password);

        // session.setAttribute("selectedGroupName", null);

        // the client will be used to query myexperiment's REST api
        HttpClient client = Helper.createAuthenticatingClient("www.myexperiment.org", user, password);

        // GET method for retrieving the xml with the userID
        GetMethod get = new GetMethod(urlStringWhoami);
        // api needs basic authentication
        get.setDoAuthentication(true);

        try {
            int status = client.executeMethod(get);

            if (status == 200) {
                session.setAttribute("logged_in", "true");
                request.setAttribute("login_error", null);

                InputStream xmlResponse = get.getResponseBodyAsStream();

                // get the user uri which contains the userID,
                // userID does not need to be extracted,
                // the uri can be used directly to query the api for infos
                // about the user
                Attribute attr = (Attribute) Helper.applyXPathSingleNode(xmlResponse, "//user/@uri");
                String userUri = attr.getValue();

                // GET method to retrieve all groups of the user
                get = new GetMethod(userUri + "&elements=groups");
                client.executeMethod(get);
                xmlResponse = get.getResponseBodyAsStream();
                // get all groups from received xml
                List<Element> groupElements = Helper.applyXPathSeveralNodes(xmlResponse, "//group");

                // will be used in the jsp to construct selection lists
                Map<String, List<WorkflowInfo>> allWfInfos = new LinkedHashMap<String, List<WorkflowInfo>>();

                // if the user is in the impact group, then it will be the
                // default selection in the jsp, or else it will be the
                // first group
                boolean isFirstGroup = true;

                for (Element group : groupElements) {
                    String groupUri = group.getAttributeValue("uri");
                    String groupName = group.getTextTrim();

                    // set the default selection
                    if (isFirstGroup || groupName.startsWith("IMPACT")) {
                        session.setAttribute("selectedGroupName0", groupName);
                        session.setAttribute("selectedGroupName1", groupName);
                        isFirstGroup = false;
                    }

                    // GET method for retrieving all workflow infos of a
                    // group
                    get = new GetMethod(groupUri + "&elements=shared-items");
                    client.executeMethod(get);
                    xmlResponse = get.getResponseBodyAsStream();

                    // extract the necessary information from received xml
                    List<WorkflowInfo> wfInfos = createWfInfos(xmlResponse);

                    // map for jsp
                    allWfInfos.put(groupName, wfInfos);

                }

                // GET method for retrieving all workflow infos of the user
                get = new GetMethod(userUri + "&elements=workflows");
                client.executeMethod(get);
                xmlResponse = get.getResponseBodyAsStream();

                // extract the necessary information from received xml
                List<WorkflowInfo> wfInfosUser = createWfInfos(xmlResponse);

                if (wfInfosUser != null && wfInfosUser.size() > 0) {
                    // the select will show this under the other groups
                    allWfInfos.put("Own workflows", wfInfosUser);
                }
                session.setAttribute("allWfInfos", allWfInfos);
                session.setAttribute("currentTab0", "remote");
                session.setAttribute("currentTab1", "remote");
            } else {
                session.setAttribute("logged_in", "false");
                request.setAttribute("login_error", "Login error");
                session.setAttribute("currentTab0", "local");
                session.setAttribute("currentTab1", "local");
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JDOMException e) {
            e.printStackTrace();
        } finally {
            // release any connection resources used by the method
            get.releaseConnection();
        }
    }
    RequestDispatcher rd = getServletContext().getRequestDispatcher(redirect);
    rd.forward(request, response);
}

From source file:edu.lternet.pasta.portal.MetadataViewerServlet.java

/**
 * The doPost method of the servlet. <br>
 * /*w  w w . j ava2s  .c o  m*/
 * This method is called when a form has its tag value method equals to post.
 * 
 * @param request
 *          the request send by the client to the server
 * @param response
 *          the response send by the server to the client
 * @throws ServletException
 *           if an error occurred
 * @throws IOException
 *           if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession httpSession = request.getSession();
    String uid = (String) httpSession.getAttribute("uid");
    if (uid == null || uid.isEmpty())
        uid = "public";
    String message = null;
    String metadataStr = null;

    /*
     * The packageId may be set by either a post parameter or by a query
     * parameter using a URL string
     */
    String packageId = request.getParameter("packageid");
    String url = request.getParameter("url");

    String contentType = request.getParameter("contentType");
    if (contentType == null || contentType.isEmpty()) {
        contentType = "text/html"; // Reset to default content type
    }

    boolean isValidPackageId = false;
    String[] tokens = null;
    String scope = null;
    Integer identifier = null;
    String revision = null;

    try {
        if (packageId != null && !packageId.isEmpty()) {

            tokens = packageId.split("\\.");

            if (tokens.length == 3) {
                isValidPackageId = true;
                scope = tokens[0];
                identifier = Integer.valueOf(tokens[1]);
                revision = tokens[2];
            } else {
                message = String.format(
                        "packageId '%s' is not in the correct form of 'scope.identifier.revision' (e.g., 'knb-lter-lno.1.1').",
                        packageId);
                throw new UserErrorException(message);
            }
        } else if (url != null && !(url.isEmpty())) {
            tokens = url.split("/");

            if (tokens.length >= 3) {
                isValidPackageId = true;
                scope = tokens[tokens.length - 3];
                identifier = Integer.valueOf(tokens[tokens.length - 2]);
                revision = tokens[tokens.length - 1];
                packageId = scope + "." + identifier.toString() + "." + revision;
            }

        } else {
            message = "A packageId or metadata URL was not found.";
            throw new ResourceNotFoundException(message);
        }

        if (isValidPackageId) {

            String dataPackageDOI = null;
            String xml = null;
            DataPackageManagerClient dpmClient = new DataPackageManagerClient(uid);
            xml = dpmClient.readMetadata(scope, identifier, revision);

            if (contentType.equals("application/xml")) {
                metadataStr = xml;
                response.setContentType("application/xml");
                response.setCharacterEncoding("UTF-8");
                PrintWriter out = response.getWriter();
                out.print(metadataStr);
                out.flush();
                out.close();
            } else {
                EmlUtility emlUtility = new EmlUtility(xml);
                HashMap<String, String> parameterMap = new HashMap<String, String>();
                String pastUriHead = dpmClient.getPastaUriHead();
                String resourceId = packageIdToResourceId(pastUriHead, packageId);
                // Pass the resourceId as a parameter to the XSLT
                if (resourceId != null && !resourceId.equals("")) {
                    parameterMap.put("resourceId", resourceId);
                }
                // Pass the data package DOI as a parameter to the XSLT
                try {
                    dataPackageDOI = dpmClient.readDataPackageDoi(scope, identifier, revision);
                    if (dataPackageDOI != null && !dataPackageDOI.equals("")) {
                        parameterMap.put("dataPackageDOI", dataPackageDOI);
                    }
                } catch (Exception e) {
                    // No DOI was read. Just continue on.
                }
                metadataStr = emlUtility.xmlToHtmlSaxon(cwd + xslpath, parameterMap);

                request.setAttribute("metadataHtml", metadataStr);
                request.setAttribute("packageId", packageId);
                RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward);
                requestDispatcher.forward(request, response);
            }
        }

    } catch (Exception e) {
        handleDataPortalError(logger, e);
    }

}

From source file:org.apache.brooklyn.rest.filter.BrooklynPropertiesSecurityFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    String uri = httpRequest.getRequestURI();

    if (provider == null) {
        log.warn("No security provider available: disallowing web access to brooklyn");
        httpResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;//from w w w . j a  v a  2  s .  co m
    }

    if (originalRequest.get() != null) {
        // clear the entitlement context before setting to avoid warnings
        Entitlements.clearEntitlementContext();
    } else {
        originalRequest.set(uri);
    }

    boolean authenticated = provider.isAuthenticated(httpRequest.getSession());
    if ("/logout".equals(uri) || "/v1/logout".equals(uri)) {
        httpResponse.setHeader("WWW-Authenticate", "Basic realm=\"brooklyn\"");
        if (authenticated && httpRequest.getSession().getAttributeNames().hasMoreElements()) {
            logout(httpRequest);
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            RequestDispatcher dispatcher = httpRequest.getRequestDispatcher("/");
            log.debug("Not authenticated, forwarding request for {} to {}", uri, dispatcher);
            dispatcher.forward(httpRequest, httpResponse);
        }
        return;
    }

    if (!(httpRequest.getSession().getAttributeNames().hasMoreElements()
            && provider.isAuthenticated(httpRequest.getSession())) || "/logout".equals(originalRequest.get())) {
        authenticated = authenticate(httpRequest);
    }

    if (!authenticated) {
        httpResponse.setHeader("WWW-Authenticate", "Basic realm=\"brooklyn\"");
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    // Note that the attribute AUTHENTICATED_USER_SESSION_ATTRIBUTE is only set in the call to authenticate(httpRequest),
    // so must not try to get the user until that is done.
    String uid = RequestTaggingFilter.getTag();
    String user = Strings.toString(httpRequest.getSession().getAttribute(AUTHENTICATED_USER_SESSION_ATTRIBUTE));
    try {
        WebEntitlementContext entitlementContext = new WebEntitlementContext(user, httpRequest.getRemoteAddr(),
                uri, uid);
        Entitlements.setEntitlementContext(entitlementContext);

        chain.doFilter(request, response);
    } catch (Throwable e) {
        if (!response.isCommitted()) {
            httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } finally {
        originalRequest.remove();
        Entitlements.clearEntitlementContext();
    }
}

From source file:org.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint.java

public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    String scheme = request.getScheme();
    String serverName = request.getServerName();
    int serverPort = portResolver.getServerPort(request);
    String contextPath = req.getContextPath();

    boolean inHttp = "http".equals(scheme.toLowerCase());
    boolean inHttps = "https".equals(scheme.toLowerCase());

    boolean includePort = true;

    String redirectUrl = null;//  w  ww .  j ava 2  s  .  co m
    boolean doForceHttps = false;
    Integer httpsPort = null;

    if (inHttp && (serverPort == 80)) {
        includePort = false;
    } else if (inHttps && (serverPort == 443)) {
        includePort = false;
    }

    if (forceHttps && inHttp) {
        httpsPort = (Integer) portMapper.lookupHttpsPort(new Integer(serverPort));

        if (httpsPort != null) {
            doForceHttps = true;
            if (httpsPort.intValue() == 443) {
                includePort = false;
            } else {
                includePort = true;
            }
        }

    }

    String loginForm = determineUrlToUseForThisRequest(req, resp, authException);

    if (serverSideRedirect) {

        if (doForceHttps) {

            // before doing server side redirect, we need to do client
            // redirect to https.

            String servletPath = req.getServletPath();
            String pathInfo = req.getPathInfo();
            String query = req.getQueryString();

            redirectUrl = "https://" + serverName + ((includePort) ? (":" + httpsPort) : "") + contextPath
                    + servletPath + (pathInfo == null ? "" : pathInfo) + (query == null ? "" : "?" + query);

        } else {

            if (logger.isDebugEnabled()) {
                logger.debug("Server side forward to: " + loginForm);
            }

            RequestDispatcher dispatcher = req.getRequestDispatcher(loginForm);

            dispatcher.forward(request, response);

            return;

        }

    } else {

        if (doForceHttps) {

            redirectUrl = "https://" + serverName + ((includePort) ? (":" + httpsPort) : "") + contextPath
                    + loginForm;

        } else {

            redirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "") + contextPath
                    + loginForm;

        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Redirecting to: " + redirectUrl);
    }

    ((HttpServletResponse) response)
            .sendRedirect(((HttpServletResponse) response).encodeRedirectURL(redirectUrl));
}

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

@Override
public void doPost(HttpServletRequest req, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(req, response, SimplePermission.EDIT_ONTOLOGY.ACTION)) {
        return;/*  ww  w. ja  va2s.  c  o m*/
    }

    // create an EditProcessObject for this and put it in the session
    EditProcessObject epo = super.createEpo(req);

    // Populate it.
    EpoPopulator populator = new EpoPopulator(req, epo);
    populator.populate();

    req.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp");
    req.setAttribute("colspan", "5");
    req.setAttribute("formJsp", "/templates/edit/specific/fauxProperty_retry.jsp");
    req.setAttribute("scripts", "/templates/edit/formBasic.js");
    req.setAttribute("title", "Faux Property Editing Form");
    req.setAttribute("_action", epo.getAction());
    setRequestAttributes(req, epo);

    try {
        RequestDispatcher rd = req.getRequestDispatcher(Controllers.BASIC_JSP);
        rd.forward(req, response);
    } catch (Exception e) {
        log.error("Could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

}

From source file:com.oncloud6.atd.invoices.InvoicesShowServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from   ww w.  java2s.  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 {
    SessionFactory factory = new HibernateConnector().getSessionFactory();
    Session hibernateSession = factory.openSession();
    Transaction tx = null;

    boolean idSet = false;
    if (request.getParameter("id") == null || request.getParameter("id").equals("")) {
        response.sendRedirect("invoices");
    } else {
        try {
            Factuur gekozenFactuur = new Factuur();
            gekozenFactuur = (Factuur) hibernateSession.get(Factuur.class,
                    Integer.parseInt(request.getParameter("id")));
            if (gekozenFactuur == null) {
                response.sendRedirect("invoices");
            } else {
                HttpSession session = request.getSession(true);
                RequestDispatcher rd = null;
                if (!RightsControl.checkGroup("invoices_show", "own", session,
                        gekozenFactuur.getDeKlant().getGebruiker().getId())) {
                    rd = request.getRequestDispatcher("error/403error.jsp");
                    rd.forward(request, response);
                    return;
                }

                response.addHeader("Content-Disposition",
                        "attachment; filename=fac" + gekozenFactuur.getFactuurNummer() + ".pdf");
                Process process = Runtime.getRuntime().exec(
                        "c:\\rotativa\\wkhtmltopdf.exe -q -n --disable-smart-shrinking http://localhost:8080/Themaproject/invoicessource?id="
                                + request.getParameter("id") + "&secret=" + gekozenFactuur.getSecret() + " -");
                response.setContentType("application/pdf");
                try {
                    IOUtils.copy(process.getInputStream(), response.getOutputStream());
                } finally {
                    process.getInputStream().close();
                    response.getOutputStream().close();
                }
            }
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            hibernateSession.close();
        }
    }

}