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.ControllerImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  w ww  . ja va 2s. 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 {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {

    } else {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();
        Hashtable params = new Hashtable();
        String fileName = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {

                try {
                    String itemName = item.getName();
                    fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    String code = (String) params.get("txtCode");
                    String name = (String) params.get("txtName");
                    String price = (String) params.get("txtPrice");
                    int a = Integer.parseInt(price);
                    String image = (String) params.get("txtImage");
                    //Update  product
                    if (fileName.equals("")) {

                        Products sp = new Products();
                        sp.Update(code, name, price, image);
                        RequestDispatcher rd = request.getRequestDispatcher("product.jsp");
                        rd.forward(request, response);

                    } else {
                        // bat dau ghi file
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                        //ket thuc ghi
                        Products sp = new Products();
                        sp.Update(code, name, price, "upload\\" + fileName);

                        RequestDispatcher rd = request.getRequestDispatcher("product.jsp");
                        rd.forward(request, response);
                    }

                } catch (Exception e) {
                    RequestDispatcher rd = request.getRequestDispatcher("InformationError.jsp");
                    rd.forward(request, response);
                }
            }

        }
    }

    this.processRequest(request, response);

}

From source file:com.kesdip.license.web.servlet.UpdateServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *///from   w  ww  .  ja  v a  2s . co m
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    // make sure this is not a browser
    String userAgent = req.getHeader("user-agent");
    if (!userAgent.startsWith("Java")) {
        if (logger.isDebugEnabled()) {
            logger.debug("'" + userAgent + "' forbidden");
        }
        res.sendError(HttpServletResponse.SC_FORBIDDEN, FORBIDDEN_MESSAGE);
        return;
    }
    // get the customer UUID
    String uuid = req.getRemoteUser();
    if (StringUtils.isEmpty(uuid)) {
        logger.debug("Empty customer uuid");
        res.sendError(HttpServletResponse.SC_FORBIDDEN, FORBIDDEN_MESSAGE);
        return;
    }
    // if requesting site.xml or the root (Eclipse does both), check the DB
    String uri = req.getRequestURI();
    String servletPath = req.getServletPath();
    if (uri.endsWith(servletPath) || uri.endsWith(SITE_XML)) {
        if (!supportEnabled(uuid)) {
            logger.warn("Update denied for '" + uuid + "'");
            res.sendError(HttpServletResponse.SC_FORBIDDEN, FORBIDDEN_MESSAGE);
            return;
        }
    }
    // if requesting site.xml, log the request
    if (uri.endsWith(SITE_XML)) {
        logUpdateRequest(uuid, req.getRemoteAddr(), userAgent);
    }
    // all OK, forward to the actual file
    String translatedUri = uri.substring(req.getContextPath().length()).replace(servletPath, actualUpdateRoot);
    if (logger.isTraceEnabled()) {
        logger.trace("Forwarding to '" + translatedUri + "'");
    }
    RequestDispatcher rd = servletContext.getRequestDispatcher(translatedUri);
    rd.forward(req, res);
}

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

/**
 * Handles the following activities for <code>TwistInfo</code>
 * /*from  w w  w.  j  a v  a  2s  .  c o m*/
 */
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String responseType = req.getParameter("response-type");
    // If type is JSON, then respond with JSON
    // Otherwise, direct to JSP

    Long twistInfoId = null;
    TwistInfo twistInfo = null;
    String coachingMessage = null;
    JSONObject jsonObject = new JSONObject();

    try {
        twistInfoId = new Long(req.getParameter(PARAMETER_KEY_TWIST_ID));
        boolean enable = Boolean.parseBoolean(req.getParameter(PARAMETER_KEY_TWIST_ENABLE));
        twistInfo = store.getTwistInfoById(twistInfoId);
        if (enable) {
            store.setUniversalTwistInfoId(twistInfo.getId());
            if (twistInfo != null) {
                jsonObject.put(PARAMETER_KEY_TWIST_ID, "" + twistInfo.getId());
                jsonObject.put(PARAMETER_KEY_TWIST_NAME, "" + twistInfo.getName());
                coachingMessage = "Twist configuration on";
            }

        } else if (store.getUniversalTwistInfoId() != null
                && store.getUniversalTwistInfoId().equals(twistInfoId)) {
            // Disable
            // The only way to DISABLE _all_ twist configurations, both ENABLE (false) and TWIST-ID value (equal 
            // to the current universal twist-id have to be passed in. 
            // Why? To prevent random 'ENABLE=false' arguments past to this service from users 
            // clicking OFF/disable when things are already disabled. 
            // 
            store.setUniversalTwistInfoId(null);
            coachingMessage = "Twist configuration off";
        }

    } catch (Exception e) {
        logger.error("Unable to properly set Twist configuration.", e);
    }

    if (PARAMETER_KEY_RESPONSE_TYPE_VALUE_JSON.equalsIgnoreCase(responseType)) {
        // ***********************
        // BEGIN - JSON response
        // ***********************
        resp.setContentType("application/json");
        PrintWriter out = resp.getWriter();
        try {
            JSONObject jsonResponseObject = new JSONObject();
            if (twistInfo != null) {
                jsonObject.put("success", coachingMessage);

            } else {
                jsonObject.put("fail", "Unable to set twist configuration.");

            }
            jsonResponseObject.put("result", jsonObject);
            out.println(jsonResponseObject.toString());

        } catch (JSONException jsonException) {
            throw new ServletException(jsonException);
        }

        out.flush();
        out.close();
        return;
        // ***********************
        // END - JSON response
        // ***********************

    } else {
        List<TwistInfo> twistInfoList = store.getTwistInfoList();
        Util.saveSuccessMessage("Twist configuration updated", req);
        req.setAttribute("twistInfoList", twistInfoList);
        req.setAttribute("twistInfoIdEnabled", store.getUniversalTwistInfoId());
        RequestDispatcher dispatch = req.getRequestDispatcher("/twistinfo_setup.jsp");
        dispatch.forward(req, resp);
        return;
    }

}

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

/**
 * The doPost method of the servlet. <br>
 * /*from   w  w  w .ja  v a2s. 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");
    String distinguishedName = (String) httpSession.getAttribute("uid");
    String forward = null;
    String browseMessage = "View a data package you have uploaded.";

    if (uid == null || uid.isEmpty() || uid.equals("public") || distinguishedName == null
            || distinguishedName.isEmpty()) {
        String message = LOGIN_WARNING;
        forward = "./login.jsp";
        request.setAttribute("message", message);
        request.setAttribute("from", "userBrowseServlet");
    } else {
        forward = "./dataPackageBrowser.jsp";

        String text = null;
        String html = null;
        Integer count = 0;

        try {

            DataPackageManagerClient dpmClient = new DataPackageManagerClient(uid);
            text = dpmClient.listUserDataPackages(distinguishedName);
            StrTokenizer tokens = new StrTokenizer(text);
            html = "<ol>\n";
            EmlPackageIdFormat epif = new EmlPackageIdFormat();

            while (tokens.hasNext()) {
                String packageId = tokens.nextToken();
                EmlPackageId epid = epif.parse(packageId);
                String scope = epid.getScope();
                Integer identifier = epid.getIdentifier();
                Integer revision = epid.getRevision();
                html += String.format(
                        "<li><a class=\"searchsubcat\" href=\"./mapbrowse?scope=%s&identifier=%d&revision=%d\">%s</a></li>\n",
                        scope, identifier, revision, packageId);
                count++;
            }

            html += "</ol>\n";
            request.setAttribute("html", html);
            request.setAttribute("count", count.toString());
            if (count < 1) {
                browseMessage = String.format("No data packages have been uploaded by user '%s'.",
                        distinguishedName);
            }
            request.setAttribute("browsemessage", browseMessage);
        } catch (Exception e) {
            handleDataPortalError(logger, e);
        }
    }

    RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward);
    requestDispatcher.forward(request, response);
}

From source file:com.camel.action.base.LoginAction.java

public String doLogOut() throws IOException, ServletException {
    ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();

    RequestDispatcher dispatcher = ((ServletRequest) context.getRequest())
            .getRequestDispatcher("/j_spring_security_logout");

    dispatcher.forward((ServletRequest) context.getRequest(), (ServletResponse) context.getResponse());

    FacesContext.getCurrentInstance().responseComplete();
    return null;//from w  w w.  j av a  2  s .c  o  m
}

From source file:controller.uploadPergunta3.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   www.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 {

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

    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");
    }

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

    RequestDispatcher view = getServletContext()
            .getRequestDispatcher("/novoLocalPergunta3?id=" + idLocal + "&nomeArquivo=" + name);
    view.forward(request, response);

}

From source file:gov.nih.nci.ncicb.cadsr.common.security.LogoutServlet.java

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

    //unlock all forms locked by this session
    HttpSession session = request.getSession();
    String logTjsp = getServletConfig().getInitParameter("LogthroughJSP");
    if (logTjsp != null && !logTjsp.equals(""))
        LOGTHROUGH_JSP = logTjsp;/* w  ww  . ja v  a 2 s.com*/

    String lojsp = getServletConfig().getInitParameter("LogoutJSP");
    if (lojsp != null && !lojsp.equals(""))
        LOGOUT_JSP = lojsp;
    String authjsp = getServletConfig().getInitParameter("ErrorJSP");
    if (authjsp != null && !authjsp.equals(""))
        AUTHORIZATION_ERROR_JSP = authjsp;

    if (!request.getContextPath().contains("CDEBrowser")) {
        getApplicationServiceLocator(session.getServletContext()).findLockingService()
                .unlockFormByUser(request.getRemoteUser());
    }
    synchronized (SessionUtils.sessionObjectCache) {
        log.error("LogoutServlet.doPost at start:" + TimeUtils.getEasternTime());
        String error = request.getParameter("authorizationError");
        String forwardUrl;
        //// GF29128 Begin. D.An, 20130729. 
        String un = (String) session.getAttribute("myUsername");
        ;
        ////   if (un == null)
        ////      un = "viewer";
        System.out.println("logoutServlet: " + session.getAttribute("myUsername"));
        if (error == null) {
            if (un.equals("viewer"))
                forwardUrl = LOGTHROUGH_JSP;
            //// GF29128  end.      
            else
                forwardUrl = LOGOUT_JSP;
        } else {
            forwardUrl = AUTHORIZATION_ERROR_JSP;
        }

        if ((session != null) && isLoggedIn(request)) {
            for (int i = 0; i < logoutKeys.length; i++) {
                session.removeAttribute(logoutKeys[i]);
            }

            //remove formbuilder specific objects
            //TODO has to be moved to an action
            Collection keys = (Collection) session.getAttribute(FormBuilderConstants.CLEAR_SESSION_KEYS);
            if (keys != null) {
                Iterator it = keys.iterator();
                while (it.hasNext()) {
                    session.removeAttribute((String) it.next());
                }
            }
            HashMap allMap = new HashMap();
            allMap.put(CaDSRConstants.GLOBAL_SESSION_KEYS, copyAllsessionKeys(session));
            allMap.put(CaDSRConstants.GLOBAL_SESSION_MAP, copyAllsessionObjects(session));
            SessionUtils.addToSessionCache(session.getId(), allMap);
            forwardUrl = forwardUrl + "?" + CaDSRConstants.PREVIOUS_SESSION_ID + "=" + session.getId();
            session.invalidate();
        }

        RequestDispatcher dispacher = request.getRequestDispatcher(forwardUrl);
        dispacher.forward(request, response);
        log.error("LogoutServlet.doPost at end:" + TimeUtils.getEasternTime());
    }
}

From source file:com.mkmeier.quickerbooks.LoadAccounts.java

/**
 * Redirect to the Load Accounts form./*w w  w  .  j  a  v  a 2  s  .co m*/
 *
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
private void redirect(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    RequestDispatcher rd = request.getRequestDispatcher("LoadAccounts.jsp");
    rd.forward(request, response);
}

From source file:com.squid.kraken.v4.auth.ChangePasswordServlet.java

/**
 * Perform the action via API calls./* ww  w  . jav a2 s. c  o  m*/
 *
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
private void proceed(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, URISyntaxException {
    try {
        User user = getUser(request);
        user.setPassword(request.getParameter("password"));

        // create a POST method to execute the change password request
        URIBuilder builder = new URIBuilder(privateServerURL + "/rs/users/");
        String token = request.getParameter("access_token");
        builder.addParameter("access_token", token);

        // execute the request
        HttpPost req = new HttpPost(builder.build());
        Gson gson = new Gson();
        String json = gson.toJson(user);
        StringEntity stringEntity = new StringEntity(json);
        stringEntity.setContentType("application/json");
        req.setEntity(stringEntity);
        user = RequestHelper.processRequest(User.class, request, req);
        request.setAttribute("message", "Password updated");
        request.setAttribute("user", user);
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/password.jsp");
        rd.forward(request, response);
    } catch (ServerUnavailableException e1) {
        logger.error(e1.getLocalizedMessage());
        request.setAttribute(KRAKEN_UNAVAILABLE, Boolean.TRUE);
        show(request, response);
    } catch (ServiceException e1) {
        WebServicesException wsException = e1.getWsException();
        String error;
        if (wsException == null) {
            error = AN_ERROR_OCCURRED;
        } else {
            error = wsException.getError();
        }
        request.setAttribute(ERROR, error);
        show(request, response);
    } catch (SSORedirectException error) {
        response.sendRedirect(error.getRedirectURL());
    }
}

From source file:controller.ControlPembayaran.java

public void tampil(HttpServletRequest request, HttpServletResponse response, String information)
        throws ServletException, IOException {
    RequestDispatcher dispatcher;
    request.setAttribute("info", information);
    dispatcher = request.getRequestDispatcher("info.jsp");
    dispatcher.forward(request, response);
}