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:es.uma.inftel.blog.servlet.PostServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w w  w.  ja  v a 2  s  . c  om*/
 *
 * @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 {
    request.setCharacterEncoding("UTF-8");
    String tituloP = request.getParameter("tituloPost");
    String textoP = request.getParameter("textoPost");

    RequestDispatcher rd = request.getRequestDispatcher("/crearPost.jsp");
    if (tituloP == null && textoP == null) {
        BaseView crearPostView = new BaseView();
        BaseViewFacade<BaseView> crearPostViewFacade = new BaseViewFacade<>(postFacade);
        crearPostViewFacade.initView(crearPostView);
        request.setAttribute("crearPostView", crearPostView);
        rd.forward(request, response);
        return;
    }
    Usuario usuario = (Usuario) request.getSession().getAttribute("usuario");
    Post post = crearPost(tituloP, textoP, usuario);
    postFacade.create(post);

    String etiquetas = request.getParameter("etiqueta");
    insertarEtiquetas(etiquetas, post);
    if (!request.getParameter("lat").isEmpty()) {
        crearMapa(request, post);
    }
    //Crea Fotos
    insertarImagen(request, post);

    response.sendRedirect("post?id=" + post.getId());
}

From source file:org.apache.struts.action.ServicesServlet.java

protected boolean processValidate(ActionMapping mapping, ActionForm formInstance, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {

    if (formInstance == null)
        return (true);

    if (debug >= 1)
        log(" Validating input form properties");

    // Was this submit cancelled?
    if ((request.getParameter(Constants.CANCEL_PROPERTY) != null)
            || (request.getParameter(Constants.CANCEL_PROPERTY_X) != null)) {
        if (debug >= 1)
            log("  Cancelled transaction, no validation");
        return (true);
    }/*from  w  w  w. jav  a 2s .  co  m*/

    // Has validation been turned off on this mapping?
    if (!mapping.getValidate())
        return (true);

    ActionErrors errors = new ActionErrors();

    try {

        if (services.performBooleanCall("validateBefore",
                new Object[] { mapping, formInstance, request, response, errors }, true)) {

            if (debug >= 1)
                log("  No errors detected by 'before' services");

            // Call the validate() method of our ActionForm bean
            errors = formInstance.validate(mapping, request);
            if ((errors == null) || errors.isEmpty()) {
                if (debug >= 1)
                    log("  No errors detected by form validate");
                if (services.performBooleanCall("validateAfter",
                        new Object[] { mapping, formInstance, request, response, errors }, true)) {
                    if (debug >= 1)
                        log("  No errors detected by 'after' services");
                    return (true);
                }
            }
        }
    } catch (Exception e) {
        throw new ServletException("Exception at processValidate call to the services", e);
    }

    //does our form have a multipart request?
    if (formInstance.getMultipartRequestHandler() != null) {
        //rollback the request
        if (debug > 1) {
            log("  Rolling back the multipart request");
        }

        formInstance.getMultipartRequestHandler().rollback();
    }
    // Has an input form been specified for this mapping?
    String uri = mapping.getInput();
    if (uri == null) {
        if (debug >= 1)
            log("  No input form, but validation returned errors");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                internal.getMessage("noInput", mapping.getPath()));
        return (false);
    }

    // Save our error messages and return to the input form if possible
    if (debug >= 1)
        log("  Validation error(s), redirecting to: " + uri);
    request.setAttribute(Globals.ERROR_KEY, errors);
    //unwrap the multipart request if there is one
    if (request instanceof MultipartRequestWrapper) {
        request = ((MultipartRequestWrapper) request).getRequest();
    }
    RequestDispatcher rd = getServletContext().getRequestDispatcher(uri);
    if (rd == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                internal.getMessage("requestDispatcher", uri));
        return (false);
    }
    rd.forward(request, response);

    return false;

}

From source file:org.apache.roller.weblogger.ui.rendering.WeblogRequestMapper.java

public boolean handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // kinda silly, but we need to keep track of whether or not the url had
    // a trailing slash so that we can act accordingly
    boolean trailingSlash = false;

    String weblogHandle = null;/*from   w  ww. j a va2s  .c om*/
    String weblogLocale = null;
    String weblogRequestContext = null;
    String weblogRequestData = null;

    log.debug("evaluating [" + request.getRequestURI() + "]");

    // figure out potential weblog handle
    String servlet = request.getRequestURI();
    String pathInfo = null;

    if (servlet != null && servlet.trim().length() > 1) {

        if (request.getContextPath() != null)
            servlet = servlet.substring(request.getContextPath().length());

        // strip off the leading slash
        servlet = servlet.substring(1);

        // strip off trailing slash if needed
        if (servlet.endsWith("/")) {
            servlet = servlet.substring(0, servlet.length() - 1);
            trailingSlash = true;
        }

        if (servlet.indexOf("/") != -1) {
            weblogHandle = servlet.substring(0, servlet.indexOf("/"));
            pathInfo = servlet.substring(servlet.indexOf("/") + 1);
        } else {
            weblogHandle = servlet;
        }
    }

    log.debug("potential weblog handle = " + weblogHandle);

    // check if it's a valid weblog handle
    if (restricted.contains(weblogHandle) || !this.isWeblog(weblogHandle)) {
        log.debug("SKIPPED " + weblogHandle);
        return false;
    }

    String weblogAbsoluteURL = WebloggerConfig.getProperty("weblog.absoluteurl." + weblogHandle);
    if (weblogAbsoluteURL != null) {
        // An absolute URL is specified for this weblog, make sure request URL matches
        if (!request.getRequestURL().toString().startsWith(weblogAbsoluteURL)) {
            log.debug("SKIPPED " + weblogHandle);
            return false;
        }
    }

    log.debug("WEBLOG_URL " + request.getServletPath());

    // parse the rest of the url and build forward url
    if (pathInfo != null) {

        // parse the next portion of the url
        // we expect [locale/]<context>/<extra>/<info>
        String[] urlPath = pathInfo.split("/", 3);

        // if we have a locale, deal with it
        if (this.isLocale(urlPath[0])) {
            weblogLocale = urlPath[0];

            // no extra path info specified
            if (urlPath.length == 2) {
                weblogRequestContext = urlPath[1];
                weblogRequestData = null;

                // request contains extra path info
            } else if (urlPath.length == 3) {
                weblogRequestContext = urlPath[1];
                weblogRequestData = urlPath[2];
            }

            // otherwise locale is empty
        } else {
            weblogLocale = null;
            weblogRequestContext = urlPath[0];

            // last part of request is extra path info
            if (urlPath.length == 2) {
                weblogRequestData = urlPath[1];

                // if we didn't have a locale then we have split too much
                // so we reassemble the last 2 path elements together
            } else if (urlPath.length == 3) {
                weblogRequestData = urlPath[1] + "/" + urlPath[2];
            }
        }

    }

    // special handling for trailing slash issue
    // we need this because by http standards the urls /foo and /foo/ are
    // supposed to be considered different, so we must enforce that
    if (weblogRequestContext == null && !trailingSlash) {
        // this means someone referred to a weblog index page with the 
        // shortest form of url /<weblog> or /<weblog>/<locale> and we need
        // to do a redirect to /<weblog>/ or /<weblog>/<locale>/
        String redirectUrl = request.getRequestURI() + "/";
        if (request.getQueryString() != null) {
            redirectUrl += "?" + request.getQueryString();
        }

        response.sendRedirect(redirectUrl);
        return true;

    } else if (weblogRequestContext != null && "tags".equals(weblogRequestContext)) {
        // tags section can have an index page at /<weblog>/tags/ and
        // a tags query at /<weblog>/tags/tag1+tag2, buth that's it
        if ((weblogRequestData == null && !trailingSlash) || (weblogRequestData != null && trailingSlash)) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return true;
        }
    } else if (weblogRequestContext != null && trailingSlash) {
        // this means that someone has accessed a weblog url and included
        // a trailing slash, like /<weblog>/entry/<anchor>/ which is not
        // supported, so we need to offer up a 404 Not Found
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return true;
    }

    // calculate forward url
    String forwardUrl = calculateForwardUrl(request, weblogHandle, weblogLocale, weblogRequestContext,
            weblogRequestData);

    // if we don't have a forward url then the request was invalid somehow
    if (forwardUrl == null) {
        return false;
    }

    // dispatch to forward url
    log.debug("forwarding to " + forwardUrl);
    RequestDispatcher dispatch = request.getRequestDispatcher(forwardUrl);
    dispatch.forward(request, response);

    // we dealt with this request ourselves, so return "true"
    return true;
}

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

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

    VitroRequest request = new VitroRequest(req);

    EditProcessObject epo = super.createEpo(request);
    request.setAttribute("epoKey", epo.getKey());

    OntologyDao oDao = request.getUnfilteredWebappDaoFactory().getOntologyDao();
    Ontology o = null;
    if (request.getParameter("uri") == null) {
        log.error("doPost() expects non-null uri parameter");
    } else {
        o = oDao.getOntologyByURI(request.getParameter("uri"));
        if (o == null) {
            if (!VitroVocabulary.vitroURI.equals(request.getParameter("uri"))) {
                log.debug(
                        "doPost(): no ontology object found for the namespace " + request.getParameter("uri"));
            }
        } else {
            request.setAttribute("Ontology", o);
        }
    }
    ArrayList<String> results = new ArrayList<String>();
    results.add("Ontology");
    results.add("Namespace");
    results.add("Prefix");
    String name = o == null ? "" : (o.getName() == null) ? "" : o.getName();
    results.add(name);
    String namespace = o == null ? "" : (o.getURI() == null) ? "" : o.getURI();
    results.add(namespace);
    String prefix = o == null ? "" : (o.getPrefix() == null) ? "" : o.getPrefix();
    results.add(prefix);
    request.setAttribute("results", results);
    request.setAttribute("columncount", 3);
    request.setAttribute("suppressquery", "true");

    epo.setDataAccessObject(oDao);
    FormObject foo = new FormObject();
    HashMap<String, List<Option>> OptionMap = new HashMap<String, List<Option>>();

    HashMap formSelect = new HashMap(); // tells the JSP what select lists are populated, and thus should be displayed
    request.setAttribute("formSelect", formSelect);

    // add the options
    foo.setOptionLists(OptionMap);
    epo.setFormObject(foo);

    // funky hack because Ontology.getURI() will append a hash for a hash namespace
    // See OntologyDaoJena.ontologyFromOntologyResource() comments
    String realURI = OntologyDaoJena.adjustOntologyURI(o.getURI());
    request.setAttribute("realURI", realURI);
    request.setAttribute("exportURL", request.getContextPath() + Controllers.EXPORT_RDF);

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("epoKey", epo.getKey());
    request.setAttribute("bodyJsp", "/templates/edit/specific/ontologies_edit.jsp");
    request.setAttribute("title", "Ontology Control Panel");
    request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\""
            + request.getAppBean().getThemeDir() + "css/edit.css\"/>");

    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error("OntologyEditController could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

}

From source file:com.laxser.blitz.web.portal.impl.WindowTask.java

@Override
public void run() {
    try {//from  www .j  a v a  2  s  .  co m
        // started
        window.getContainer().onWindowStarted(window);

        // doRequest
        String windowPath = window.getPath();
        if (windowPath.length() == 0 || windowPath.charAt(0) != '/') {
            String requestUri = request.getRequestURI();
            if (!requestUri.endsWith("/")) {
                requestUri = requestUri + "/";
            }
            windowPath = requestUri + windowPath;
        }

        final RequestDispatcher rd = request.getRequestDispatcher(windowPath);
        request.setAttribute("$$blitz-portal.window", window);
        if (this.response.isCommitted()) {
            if (logger.isDebugEnabled()) {
                logger.debug("onWindowTimeout: response has committed. [" + window.getName() + "]@"
                        + window.getContainer());
            }
            window.getContainer().onWindowTimeout(window);
            return;
        }
        rd.forward(request, this.response);

        // done!
        window.getContainer().onWindowDone(window);
    } catch (Throwable e) {
        logger.error("", e);
        window.setThrowable(e);
        window.getContainer().onWindowError(window);
    } finally {
        // remove request from ThreadLocal in PortalRequest 
        // ?PortalRequestThreadLocal???? ?request?
        final HttpServletRequest wrapper = window.getContainer().getRequest();
        final PortalRequest portalRequest = PortalRequest.unwrapPortalRequest(wrapper);
        portalRequest.setRequest(null);

    }
}

From source file:org.apache.roller.weblogger.ui.rendering.servlets.CommentServlet.java

/**
 * Service incoming POST requests.// w  ww.java2 s  .c om
 *
 * Here we handle incoming comment postings.
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    String error = null;
    String dispatch_url = null;

    Weblog weblog = null;
    WeblogEntry entry = null;

    String message = null;
    RollerMessages messages = new RollerMessages();

    // are we doing a preview?  or a post?
    String method = request.getParameter("method");
    final boolean preview;
    if (method != null && method.equals("preview")) {
        preview = true;
        messages.addMessage("commentServlet.previewCommentOnly");
        log.debug("Handling comment preview post");
    } else {
        preview = false;
        log.debug("Handling regular comment post");
    }

    // throttling protection against spammers
    if (commentThrottle != null && commentThrottle.processHit(request.getRemoteAddr())) {

        log.debug("ABUSIVE " + request.getRemoteAddr());
        IPBanList.getInstance().addBannedIp(request.getRemoteAddr());
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    WeblogCommentRequest commentRequest = null;
    try {
        commentRequest = new WeblogCommentRequest(request);

        // lookup weblog specified by comment request
        weblog = WebloggerFactory.getWeblogger().getWeblogManager()
                .getWeblogByHandle(commentRequest.getWeblogHandle());

        if (weblog == null) {
            throw new WebloggerException("unable to lookup weblog: " + commentRequest.getWeblogHandle());
        }

        // lookup entry specified by comment request
        entry = commentRequest.getWeblogEntry();
        if (entry == null) {
            throw new WebloggerException("unable to lookup entry: " + commentRequest.getWeblogAnchor());
        }

        // we know what the weblog entry is, so setup our urls
        dispatch_url = "/roller-ui/rendering/page/" + weblog.getHandle();
        if (commentRequest.getLocale() != null) {
            dispatch_url += "/" + commentRequest.getLocale();
        }
        dispatch_url += "/entry/" + URLUtilities.encode(commentRequest.getWeblogAnchor());

    } catch (Exception e) {
        // some kind of error parsing the request or looking up weblog
        log.debug("error creating page request", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    log.debug("Doing comment posting for entry = " + entry.getPermalink());

    // collect input from request params and construct new comment object
    // fields: name, email, url, content, notify
    // TODO: data validation on collected comment data
    WeblogEntryComment comment = new WeblogEntryComment();
    comment.setName(commentRequest.getName());
    comment.setEmail(commentRequest.getEmail());
    comment.setUrl(commentRequest.getUrl());
    comment.setContent(commentRequest.getContent());
    comment.setNotify(Boolean.valueOf(commentRequest.isNotify()));
    comment.setWeblogEntry(entry);
    comment.setRemoteHost(request.getRemoteHost());
    comment.setPostTime(new Timestamp(System.currentTimeMillis()));

    // set comment content-type depending on if html is allowed
    if (WebloggerRuntimeConfig.getBooleanProperty("users.comments.htmlenabled")) {
        comment.setContentType("text/html");
    } else {
        comment.setContentType("text/plain");
    }

    // set whatever comment plugins are configured
    comment.setPlugins(WebloggerRuntimeConfig.getProperty("users.comments.plugins"));

    WeblogEntryCommentForm cf = new WeblogEntryCommentForm();
    cf.setData(comment);
    if (preview) {
        cf.setPreview(comment);
    }

    I18nMessages messageUtils = I18nMessages.getMessages(commentRequest.getLocaleInstance());

    // check if comments are allowed for this entry
    // this checks site-wide settings, weblog settings, and entry settings
    if (!entry.getCommentsStillAllowed() || !entry.isPublished()) {
        error = messageUtils.getString("comments.disabled");

        // if this is a real comment post then authenticate request
    } else if (!preview && !this.authenticator.authenticate(request)) {
        error = messageUtils.getString("error.commentAuthFailed");
        log.debug("Comment failed authentication");
    }

    // bail now if we have already found an error
    if (error != null) {
        cf.setError(error);
        request.setAttribute("commentForm", cf);
        RequestDispatcher dispatcher = request.getRequestDispatcher(dispatch_url);
        dispatcher.forward(request, response);
        return;
    }

    int validationScore = commentValidationManager.validateComment(comment, messages);
    log.debug("Comment Validation score: " + validationScore);

    if (!preview) {

        if (validationScore == 100 && weblog.getCommentModerationRequired()) {
            // Valid comments go into moderation if required
            comment.setStatus(WeblogEntryComment.PENDING);
            message = messageUtils.getString("commentServlet.submittedToModerator");
        } else if (validationScore == 100) {
            // else they're approved
            comment.setStatus(WeblogEntryComment.APPROVED);
            message = messageUtils.getString("commentServlet.commentAccepted");
        } else {
            // Invalid comments are marked as spam
            log.debug("Comment marked as spam");
            comment.setStatus(WeblogEntryComment.SPAM);
            error = messageUtils.getString("commentServlet.commentMarkedAsSpam");

            // add specific error messages if they exist
            if (messages.getErrorCount() > 0) {
                Iterator errors = messages.getErrors();
                RollerMessage errorKey = null;

                StringBuilder buf = new StringBuilder();
                buf.append("<ul>");
                while (errors.hasNext()) {
                    errorKey = (RollerMessage) errors.next();

                    buf.append("<li>");
                    if (errorKey.getArgs() != null) {
                        buf.append(messageUtils.getString(errorKey.getKey(), errorKey.getArgs()));
                    } else {
                        buf.append(messageUtils.getString(errorKey.getKey()));
                    }
                    buf.append("</li>");
                }
                buf.append("</ul>");

                error += buf.toString();
            }

        }

        try {
            if (!WeblogEntryComment.SPAM.equals(comment.getStatus())
                    || !WebloggerRuntimeConfig.getBooleanProperty("comments.ignoreSpam.enabled")) {

                WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager();
                mgr.saveComment(comment);
                WebloggerFactory.getWeblogger().flush();

                // Send email notifications only to subscribers if comment is 100% valid
                boolean notifySubscribers = (validationScore == 100);
                MailUtil.sendEmailNotification(comment, messages, messageUtils, notifySubscribers);

                // only re-index/invalidate the cache if comment isn't moderated
                if (!weblog.getCommentModerationRequired()) {
                    IndexManager manager = WebloggerFactory.getWeblogger().getIndexManager();

                    // remove entry before (re)adding it, or in case it isn't Published
                    manager.removeEntryIndexOperation(entry);

                    // if published, index the entry
                    if (entry.isPublished()) {
                        manager.addEntryIndexOperation(entry);
                    }

                    // Clear all caches associated with comment
                    CacheManager.invalidate(comment);
                }

                // comment was successful, clear the comment form
                cf = new WeblogEntryCommentForm();
            }

        } catch (WebloggerException re) {
            log.error("Error saving comment", re);
            error = re.getMessage();
        }
    }

    // the work has been done, now send the user back to the entry page
    if (error != null) {
        cf.setError(error);
    }
    if (message != null) {
        cf.setMessage(message);
    }
    request.setAttribute("commentForm", cf);

    log.debug("comment processed, forwarding to " + dispatch_url);
    RequestDispatcher dispatcher = request.getRequestDispatcher(dispatch_url);
    dispatcher.forward(request, response);
}

From source file:net.paoding.rose.web.portal.impl.WindowTask.java

@Override
public void run() {
    try {//from w w w  . j av  a2  s .  c o  m
        // started
        window.getContainer().onWindowStarted(window);

        // doRequest
        String windowPath = window.getPath();
        if (windowPath.length() == 0 || windowPath.charAt(0) != '/') {
            String requestUri = request.getRequestURI();
            if (!requestUri.endsWith("/")) {
                requestUri = requestUri + "/";
            }
            windowPath = requestUri + windowPath;
        }

        final RequestDispatcher rd = request.getRequestDispatcher(windowPath);
        request.setAttribute("$$paoding-rose-portal.window", window);
        if (this.response.isCommitted()) {
            if (logger.isDebugEnabled()) {
                logger.debug("onWindowTimeout: response has committed. [" + window.getName() + "]@"
                        + window.getContainer());
            }
            window.getContainer().onWindowTimeout(window);
            return;
        }
        rd.forward(request, this.response);

        // done!
        window.getContainer().onWindowDone(window);
    } catch (Throwable e) {
        logger.error("", e);
        window.setThrowable(e);
        window.getContainer().onWindowError(window);
    } finally {
        // remove request from ThreadLocal in PortalRequest 
        // ?PortalRequestThreadLocal???? ?request?
        final HttpServletRequest wrapper = window.getContainer().getRequest();
        final PortalRequest portalRequest = PortalRequest.unwrapPortalRequest(wrapper);
        portalRequest.setRequest(null);

    }
}

From source file:prop_add_serv.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w  w  w  .  j a va 2s. 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, FileUploadException {
    response.setContentType("text/html;charset=UTF-8");

    HttpSession hs = request.getSession();
    PrintWriter out = response.getWriter();
    try {

        if (hs.getAttribute("user") != null) {
            Login ln = (Login) hs.getAttribute("user");
            System.out.println(ln.getUId());
            String pradd1 = "";
            String pradd2 = "";
            String prage = "";
            String prarea = "";
            String prbhk = "";
            String prdescrip = "";
            String prprice = "";
            String prcity = "";
            String prstate = "";
            String prname = "";
            String prtype = "";

            String prfarea = "";
            String prphoto1 = "";
            String prphoto2 = "";
            String prphoto3 = "";
            String prphoto4 = "";

            //             
            // creates FileItem instances which keep their content in a temporary file on disk
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            //get the list of all fields from request
            List<FileItem> fields = upload.parseRequest(request);
            // iterates the object of list
            Iterator<FileItem> it = fields.iterator();
            //getting objects one by one
            while (it.hasNext()) {
                //assigning coming object if list to object of FileItem
                FileItem fileItem = it.next();
                //check whether field is form field or not
                boolean isFormField = fileItem.isFormField();

                if (isFormField) {
                    //get the filed name 
                    String fieldName = fileItem.getFieldName();

                    if (fieldName.equals("pname")) {
                        //getting value of field
                        prname = fileItem.getString();
                        System.out.println(prname);
                    } else if (fieldName.equals("price")) {
                        //getting value of field
                        prprice = fileItem.getString();
                        System.out.println(prprice);
                    } else if (fieldName.equals("city")) {
                        prcity = fileItem.getString();
                        System.out.println(prcity);
                    } else if (fieldName.equals("state")) {
                        prstate = fileItem.getString();
                        System.out.println(prstate);
                    } else if (fieldName.equals("area")) {
                        prarea = fileItem.getString();
                        System.out.println(prarea);
                    } else if (fieldName.equals("pbhk")) {
                        prbhk = fileItem.getString();
                        System.out.println(prbhk);
                    } else if (fieldName.equals("pdescription")) {
                        prdescrip = fileItem.getString();
                        System.out.println(prdescrip);

                    } else if (fieldName.equals("ptype")) {
                        prtype = fileItem.getString();
                        System.out.println(prtype);

                    } else if (fieldName.equals("paddress1")) {
                        pradd1 = fileItem.getString();
                        System.out.println(pradd1);
                    } else if (fieldName.equals("paddress2")) {
                        pradd2 = fileItem.getString();
                        System.out.println(pradd2);
                    } else if (fieldName.equals("page")) {
                        prage = fileItem.getString();
                        System.out.println(prage);
                    } else if (fieldName.equals("pfarea")) {
                        prfarea = fileItem.getString();
                        System.out.println(prfarea);
                    }
                } else {

                    String fieldName = fileItem.getFieldName();

                    if (fieldName.equals("photo1")) {

                        //getting name of file
                        prphoto1 = new File(fileItem.getName()).getName();

                        //get the extension of file by diving name into substring
                        // String extension=prphoto.substring(prphoto.indexOf(".")+1,prphoto.length());;
                        //rename file...concate name and extension
                        //prphoto=prname+"."+extension;
                        //System.out.println(prphoto);
                        try {

                            String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/";
                            // FOR UBUNTU add GETRESOURCE  and GETPATH
                            // String filePath = this.getServletContext().getResource("/images").getPath() + "\\";
                            fileItem.write(new File(fp + prphoto1));
                        } catch (Exception ex) {
                            out.println(ex.toString());
                        }
                    }

                    //PHOTO 2

                    else if (fieldName.equals("photo2")) {
                        prphoto2 = new File(fileItem.getName()).getName();

                        try {

                            String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/";
                            fileItem.write(new File(fp + prphoto2));
                        } catch (Exception ex) {
                            out.println(ex.toString());
                        }

                    }
                    //PHOTO 3
                    else if (fieldName.equals("photo3")) {

                        prphoto3 = new File(fileItem.getName()).getName();
                        try {

                            String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/";
                            fileItem.write(new File(fp + prphoto3));
                        } catch (Exception ex) {
                            out.println(ex.toString());
                        }
                    }

                    //PHOTO 4
                    else if (fieldName.equals("photo4")) {
                        prphoto4 = new File(fileItem.getName()).getName();
                        try {

                            String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/";
                            fileItem.write(new File(fp + prphoto4));
                        } catch (Exception ex) {
                            out.println(ex.toString());
                        }
                    }

                }

            }

            SessionFactory sf = NewHibernateUtil.getSessionFactory();
            Session ss = sf.openSession();
            Transaction tr = ss.beginTransaction();

            String op = "";
            Criteria cr = ss.createCriteria(StateMaster.class);
            cr.add(Restrictions.eq("sId", Integer.parseInt(prstate)));
            ArrayList<StateMaster> ar = (ArrayList<StateMaster>) cr.list();
            if (ar.isEmpty()) {

            } else {
                StateMaster sm = ar.get(0);
                op = sm.getSName();

            }

            String city = "";
            Criteria cr2 = ss.createCriteria(CityMaster.class);
            cr2.add(Restrictions.eq("cityId", Integer.parseInt(prcity)));
            ArrayList<CityMaster> ar2 = (ArrayList<CityMaster>) cr2.list();
            System.out.println("----------" + ar2.size());
            if (ar2.isEmpty()) {

            } else {
                city = ar2.get(0).getCityName();
                System.out.println("-------" + city);
            }

            String area = "";
            Criteria cr3 = ss.createCriteria(AreaMaster.class);
            cr3.add(Restrictions.eq("areaId", Integer.parseInt(prarea)));
            ArrayList<AreaMaster> ar3 = (ArrayList<AreaMaster>) cr3.list();
            System.out.println("----------" + ar3.size());
            if (ar3.isEmpty()) {

            } else {
                area = ar3.get(0).getAreaName();
                System.out.println("-------" + area);
            }

            PropDetail pd = new PropDetail();

            pd.setUId(ln);

            pd.setPAge(Integer.parseInt(prage));

            pd.setPBhk(prbhk);
            pd.setPDescription(prdescrip.trim());
            pd.setPAdd1(pradd1);
            pd.setPAdd2(pradd2);
            pd.setPPrice(Integer.parseInt(prprice));

            pd.setPCity(city);
            pd.setPState(op);
            pd.setPArea(area);

            pd.setPName(prname);
            pd.setPType(prtype);
            pd.setPImg1(prphoto1);
            System.out.println(prphoto1);
            System.out.println(prphoto2);
            pd.setPImg2(prphoto2);

            pd.setPImg3(prphoto3);
            pd.setPImg4(prphoto4);

            pd.setPFloor(Integer.parseInt(prfarea));

            ss.save(pd);

            tr.commit();

            RequestDispatcher rd = request.getRequestDispatcher("property_search_1.jsp");
            rd.forward(request, response);
        }
    } catch (HibernateException e) {
        out.println(e.getMessage());
    }
}

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

private void forwardToFileUploadError(String errrorMsg, HttpServletRequest req, HttpServletResponse response)
        throws ServletException {
    VitroRequest vreq = new VitroRequest(req);
    req.setAttribute("title", "RDF Upload Error ");
    req.setAttribute("bodyJsp", "/jsp/fileUploadError.jsp");
    req.setAttribute("errors", errrorMsg);

    RequestDispatcher rd = req.getRequestDispatcher(Controllers.BASIC_JSP);
    req.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\""
            + vreq.getAppBean().getThemeDir() + "css/edit.css\"/>");
    try {/*from   w  ww .j  av a2s. c  om*/
        rd.forward(req, response);
    } catch (IOException e1) {
        log.error(e1);
        throw new ServletException(e1);
    }
    return;
}

From source file:net.unicon.cas.chalkwire.servlet.CasChalkWireHttpServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {//from   w w  w. j a v  a  2s.c  om
        if (req.getRemoteUser() == null)
            throw new ServletException("User is not authenticated. Check the CAS client log files for details");

        String userId = req.getUserPrincipal().getName();

        if (logger.isDebugEnabled())
            logger.debug("Received login request from user " + userId);

        final String URL = buildSingleSignOnTokenRequestUrl(userId);

        if (logger.isDebugEnabled()) {
            logger.debug("Requesing security token from ePortfolio Connect Server");
            logger.debug("Requesting url:" + URL);
        }

        /*
         * Send the single sign-on request url to server and parse the response.
         */
        ChalkWireResponseParser parser = new ChalkWireResponseParser(URL);

        if (logger.isDebugEnabled())
            logger.debug("Response is success:" + parser.isSuccess());

        if (parser.isSuccess()) {

            if (logger.isDebugEnabled())
                logger.debug("url: " + parser.getURL());

            if (logger.isDebugEnabled())
                logger.debug("token: " + parser.getToken());

            String finalURL = buildFinalSingleSignOnUrl(userId, parser);

            if (logger.isDebugEnabled())
                logger.debug("Single sign-on URL:" + finalURL);

            parser = new ChalkWireResponseParser(finalURL);

            if (!parser.isSuccess())
                throw new ServletException(parser.getMessage());

            resp.sendRedirect(finalURL);

        } else
            throw new ServletException(parser.getMessage());

    } catch (ServletException e) {
        logger.error(e.getMessage(), e);

        String casServerLoginUrl = getServletContext().getInitParameter("casServerLoginUrl");

        String service = req.getRequestURL().toString();
        casServerLoginUrl += "login?renew=true&service=" + URLEncoder.encode(service, ENCODING_TYPE);

        RequestDispatcher dispatcher = getServletContext()
                .getRequestDispatcher("/WEB-INF/view/jsp/chalkWireError.jsp");
        req.setAttribute("exception", e);

        if (logger.isDebugEnabled())
            logger.debug("Constructed CAS login url:" + casServerLoginUrl);

        req.setAttribute("loginUrl", casServerLoginUrl);
        dispatcher.forward(req, resp);

    }

}