Example usage for javax.servlet.http HttpServletRequest removeAttribute

List of usage examples for javax.servlet.http HttpServletRequest removeAttribute

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest removeAttribute.

Prototype

public void removeAttribute(String name);

Source Link

Document

Removes an attribute from this request.

Usage

From source file:net.paoding.rose.web.impl.thread.RootEngine.java

/**
 * Restore the request attributes after an include.
 * /*from w w  w  . java 2  s. c o m*/
 * @param request current HTTP request
 * @param attributesSnapshot the snapshot of the request attributes
 *        before the include
 */
private void restoreRequestAttributesAfterInclude(Invocation inv) {
    logger.debug("Restoring snapshot of request attributes after include");
    HttpServletRequest request = inv.getRequest();

    @SuppressWarnings("unchecked")
    Map<String, Object> attributesSnapshot = (Map<String, Object>) inv
            .getAttribute("$$paoding-rose.attributesBeforeInclude");

    // Need to copy into separate Collection here, to avoid side effects
    // on the Enumeration when removing attributes.
    Set<String> attrsToCheck = new HashSet<String>();
    Enumeration<?> attrNames = request.getAttributeNames();
    while (attrNames.hasMoreElements()) {
        String attrName = (String) attrNames.nextElement();
        attrsToCheck.add(attrName);
    }

    // Iterate over the attributes to check, restoring the original value
    // or removing the attribute, respectively, if appropriate.
    for (String attrName : attrsToCheck) {
        Object attrValue = attributesSnapshot.get(attrName);
        if (attrValue != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Restoring original value of attribute [" + attrName + "] after include");
            }
            request.setAttribute(attrName, attrValue);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Removing attribute [" + attrName + "] after include");
            }
            request.removeAttribute(attrName);
        }
    }

}

From source file:com.opencnc.controllers.ElementoGraficoController.java

/**
 * *****************************************************************************
 * Crea la vista del CAD, dependiendo del modelo.
 * *****************************************************************************
 * @param id/*from w w  w .j a  va2  s .c  o m*/
 * @param request
 * @param response
 * @return
 * @throws Exception 
 */

@RequestMapping("/elemento/crear/{id}")
public ModelAndView crear(@PathVariable Integer id, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    HttpSession sess = request.getSession();
    if (sess != null) {
        Session s = HibernateUtil.getSessionFactory().openSession();

        //ElementoGrafico e = new ElementoGrafico();
        ModelAndView m = new ModelAndView("/elemento/crear");
        m.addObject("Id", id);
        Modelo mod = (Modelo) s.get(Modelo.class, id);
        m.addObject("NombreModel", mod.getNombre());
        //m.addObject("TipoMaquina",mod.getTipoMaquina());
        ident = id;

        /*
        Session s = HibernateUtil.getSessionFactory().openSession();
        Modelo u = (Modelo)s.get(Modelo.class,id);
        e.setModelo(u);
        //falta seguir 
        Transaction t = s.getTransaction();
        s.beginTransaction();
        s.saveOrUpdate(e);
        t.commit();
                
        */
        //m.addObject("elementoGrafico",e);
        return m;
    } else {
        request.removeAttribute("usuario");
        return new ModelAndView("redirect:/usuario/login.htm");
    }
}

From source file:com.laxser.blitz.web.impl.thread.RootEngine.java

/**
 * Restore the request attributes after an include.
 * /*from   w  ww.j  av  a2s.  c o  m*/
 * @param request current HTTP request
 * @param attributesSnapshot the snapshot of the request attributes
 *        before the include
 */
private void restoreRequestAttributesAfterInclude(Invocation inv) {
    logger.debug("Restoring snapshot of request attributes after include");
    HttpServletRequest request = inv.getRequest();

    @SuppressWarnings("unchecked")
    Map<String, Object> attributesSnapshot = (Map<String, Object>) inv
            .getAttribute("$$paoding-blitz.attributesBeforeInclude");

    // Need to copy into separate Collection here, to avoid side effects
    // on the Enumeration when removing attributes.
    Set<String> attrsToCheck = new HashSet<String>();
    Enumeration<?> attrNames = request.getAttributeNames();
    while (attrNames.hasMoreElements()) {
        String attrName = (String) attrNames.nextElement();
        attrsToCheck.add(attrName);
    }

    // Iterate over the attributes to check, restoring the original value
    // or removing the attribute, respectively, if appropriate.
    for (String attrName : attrsToCheck) {
        Object attrValue = attributesSnapshot.get(attrName);
        if (attrValue != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Restoring original value of attribute [" + attrName + "] after include");
            }
            request.setAttribute(attrName, attrValue);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Removing attribute [" + attrName + "] after include");
            }
            request.removeAttribute(attrName);
        }
    }

}

From source file:org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpoint.java

/**
 * Remove authentication result from request
 * @param req//from   w w  w  .  j a  v  a  2s.c om
 */
private void removeAuthenticationResult(HttpServletRequest req, String sessionDataKey) {

    if (isCacheAvailable) {
        FrameworkUtils.removeAuthenticationResultFromCache(sessionDataKey);
    } else {
        req.removeAttribute(FrameworkConstants.RequestAttribute.AUTH_RESULT);
    }
}

From source file:org.openmrs.web.controller.report.ReportObjectFormController.java

@Override
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response,
        Object obj, BindException be) throws Exception {
    String submitted = ServletRequestUtils.getStringParameter(request, "submitted", "");

    if (submitted.length() > 0) {
        AbstractReportObject reportObject = (AbstractReportObject) obj;

        // no matter what, we want to do some minimal validation
        if (reportObject.getName() == null)
            be.rejectValue("name", "error.name");
        else if (reportObject.getName().length() <= 0)
            be.rejectValue("name", "error.name");

        if (reportObject.getType() == null)
            be.rejectValue("type", "error.reportObject.type.required");

        if (reportObject.getSubType() == null)
            be.rejectValue("subType", "error.reportObject.subType.required");
    }//w  ww.  j a  va  2s  .c o m

    // TODO: This is NOT the place to be clearing out hte mapping of html included files.  
    // Is this even needed?? In what situations?

    // not adding data, but need to take out HtmlIncludeMap before we display this form, in case it is a re-showing of
    if (request.getAttribute(HtmlIncludeTag.OPENMRS_HTML_INCLUDE_MAP_KEY) != null) {
        log.debug("\n\nREMOVING HTMLINCLUDEMAP FROM REQUEST\n\n");
        request.removeAttribute(HtmlIncludeTag.OPENMRS_HTML_INCLUDE_MAP_KEY);
    }

    return super.processFormSubmission(request, response, obj, be);
}

From source file:Index.RegisterClienteImagesServlet.java

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

        String ubicacionArchivo = "~\\NetBeansProjects\\QuickOrderWeb\\web\\images";

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024);
        factory.setRepository(new File(ubicacionArchivo));

        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            List<FileItem> partes = upload.parseRequest(request);
            webservice.Cliente client = new webservice.Cliente();

            for (FileItem item : partes) {
                client = (webservice.Cliente) request.getSession().getAttribute("registroUsuario");
                File file = new File(ubicacionArchivo, client.getNickname() + ".jpg");
                item.write(file);
                System.out.println("name: " + item.getName());
                client.setImagen(client.getNickname() + ".jpg");
            }

            QuickOrderWebService webService = new QuickOrderWebService();
            ControllerInterface port = webService.getQuickOrderWebServicePort();
            port.registrarCliente(client);

            request.setAttribute("error", null);
            request.setAttribute("agregado", "OK");
            request.removeAttribute("registroUsuario");
            request.getSession().removeAttribute("userName");

            request.getRequestDispatcher("/AltaCliente.jsp").forward(request, response);
        } catch (FileUploadException ex) {
            System.out.println("Error al subir el archivo: " + ex.getMessage());

            request.setAttribute("error", "Error al subir la imagen");
            request.setAttribute("funcionalidad", "Imagen");

            request.getRequestDispatcher("/Login.jsp").forward(request, response);
        } catch (Exception ex) {
            System.out.println("Error al subir el archivo: " + ex.getMessage());
            request.setAttribute("error", "Error al subir la imagen");
            request.setAttribute("funcionalidad", "Imagen");

            request.getRequestDispatcher("/Login.jsp").forward(request, response);

        }
    }
}

From source file:com.opencnc.controllers.ModeloController.java

/**
 * *****************************************************************************
 * Guarda los modelos en la base de datos.
 * *****************************************************************************
 * @param modelo/* ww  w  .  j a  va 2s  .com*/
 * @param unidadMedidaId
 * @param tipoMaquinaId
 * @param usuarioId
 * @param request
 * @param response
 * @return
 * @throws Exception 
 */
@RequestMapping("/modelo/guardarModelo")
public ModelAndView guardarModelo(@ModelAttribute Modelo modelo, @RequestParam Integer unidadMedidaId,
        @RequestParam Integer tipoMaquinaId, @RequestParam Integer usuarioId, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    HttpSession sess = request.getSession();
    if (sess != null) {
        if (!"".equals(modelo.getNombre())) {

            Calendar c = new GregorianCalendar();
            Date d1 = c.getTime();

            modelo.setCreadoFecha(d1);
            Session s = HibernateUtil.getSessionFactory().openSession();

            UnidadMedida un = (UnidadMedida) s.get(UnidadMedida.class, unidadMedidaId);
            modelo.setUnidadMedida(un);
            TipoMaquina tm = (TipoMaquina) s.get(TipoMaquina.class, tipoMaquinaId);
            modelo.setTipoMaquina(tm);

            Usuario us = (Usuario) sess.getAttribute("usuario");

            // hay que hacer cambios
            modelo.setCreadoPor(0);
            //modelo.setCreadoPor(us.getCreadoPor());
            //Usuario us = (Usuario)s.get(Usuario.class, usuarioId);
            //Usuario us = (Usuario)s.get(Usuario.class, 2);

            modelo.setUsuario(us);

            Transaction t = s.getTransaction();
            s.beginTransaction();
            s.saveOrUpdate(modelo);
            t.commit();
        }
        //return abrir(usuarioId);
        return abrir(request, response);
    } else {
        request.removeAttribute("usuario");
        return new ModelAndView("redirect:/usuario/login.htm");
    }

}

From source file:com.redhat.rhn.frontend.action.channel.manage.repo.RepoDetailsAction.java

/** {@inheritDoc} */
public ActionForward execute(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
        HttpServletResponse response) {//from  ww w.j  a v a 2s . com
    DynaActionForm form = (DynaActionForm) formIn;
    RequestContext ctx = new RequestContext(request);
    Map params = makeParamMap(request);

    request.setAttribute(mapping.getParameter(), Boolean.TRUE);

    if (ctx.isSubmitted()) {

        ValidatorResult result = RhnValidationHelper.validate(this.getClass(), makeValidationMap(form), null,
                VALIDATION_XSD);
        if (!result.isEmpty()) {
            getStrutsDelegate().saveMessages(request, result);
            RhnValidationHelper.setFailedValidation(request);
        } else {
            try {
                ActionErrors errors = new ActionErrors();
                ContentSource repo = submit(request, errors, form);
                if (!errors.isEmpty()) {
                    addErrors(request, errors);
                    setupPopup(ctx);
                    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
                }
                if (isCreateMode(request)) {
                    createSuccessMessage(request, "repos.jsp.create.success", repo.getLabel());
                } else {
                    createSuccessMessage(request, "repos.jsp.update.success", repo.getLabel());
                }
                request.removeAttribute(CREATE_MODE);
                setupRepo(request, form, repo);
                params.put("id", repo.getId());
                return getStrutsDelegate().forwardParams(mapping.findForward("success"), params);
            } catch (ValidatorException ve) {
                getStrutsDelegate().saveMessages(request, ve.getResult());
                RhnValidationHelper.setFailedValidation(request);
            }
        }
    }

    setup(request, form, isCreateMode(request));

    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
}

From source file:org.codehaus.groovy.grails.web.sitemesh.GrailsPageFilter.java

@Override
protected DecoratorSelector initDecoratorSelector(SiteMeshWebAppContext webAppContext) {
    // TODO: Remove heavy coupling on horrible SM2 Factory
    final Factory factory = Factory.getInstance(new Config(filterConfig));
    factory.refresh();/*  w  w w  .  j  a  va 2s .  c  o m*/
    return new DecoratorMapper2DecoratorSelector(factory.getDecoratorMapper()) {
        @Override
        public Decorator selectDecorator(Content content, SiteMeshContext context) {
            SiteMeshWebAppContext webAppContext = (SiteMeshWebAppContext) context;
            final com.opensymphony.module.sitemesh.Decorator decorator = factory.getDecoratorMapper()
                    .getDecorator(webAppContext.getRequest(), content2htmlPage(content));
            if (decorator == null || decorator.getPage() == null) {
                return new GrailsNoDecorator();
            } else {
                return new OldDecorator2NewDecorator(decorator) {
                    @Override
                    protected void render(Content content, HttpServletRequest request,
                            HttpServletResponse response, ServletContext servletContext,
                            SiteMeshWebAppContext webAppContext) throws IOException, ServletException {

                        HTMLPage htmlPage = content2htmlPage(content);
                        request.setAttribute(PAGE, htmlPage);

                        // see if the URI path (webapp) is set
                        if (decorator.getURIPath() != null) {
                            // in a security conscious environment, the servlet container
                            // may return null for a given URL
                            if (servletContext.getContext(decorator.getURIPath()) != null) {
                                servletContext = servletContext.getContext(decorator.getURIPath());
                            }
                        }
                        // get the dispatcher for the decorator
                        RequestDispatcher dispatcher = servletContext.getRequestDispatcher(decorator.getPage());
                        if (response.isCommitted()) {
                            dispatcher.include(request, response);
                        } else {
                            dispatcher.forward(request, response);
                        }

                        request.removeAttribute(PAGE);
                    }

                };
            }
        }
    };
}

From source file:it.classhidra.core.controller.bsController.java

public static void isException(i_action action_instance, HttpServletRequest request) {
    if (action_instance != null)
        request.setAttribute(CONST_BEAN_$INSTANCEACTION, action_instance);
    if (request.getParameter(CONST_ID_JS4AJAX) == null && action_instance != null
            && action_instance.get_bean() != null)
        request.setAttribute(CONST_ID_JS4AJAX, action_instance.get_bean().getJs4ajax());
    if (request.getParameter(CONST_ID_JS4AJAX) == null && action_instance == null)
        request.setAttribute(CONST_ID_JS4AJAX, "false");
    request.removeAttribute(CONST_ID_REQUEST_TYPE);

}