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:com.ibm.jaggr.core.impl.transport.RequestedModuleNamesTest.java

@SuppressWarnings("deprecation")
@Test/*w w w.  j  av  a2s.c  o m*/
public void testSetRequestedModuleNamesWithDeprecatedParams() throws Exception {
    IAggregator mockAggregator = TestUtils.createMockAggregator();
    Map<String, Object> requestAttributes = new HashMap<String, Object>();
    Map<String, String[]> requestParams = new HashMap<String, String[]>();
    HttpServletRequest request = TestUtils.createMockRequest(mockAggregator, requestAttributes, requestParams,
            null, null);
    EasyMock.replay(mockAggregator, request);

    // check the warn deprecated flag when using 'modules' (dev/debug only)
    requestParams.put(AbstractHttpTransport.REQUESTEDMODULES_REQPARAM, new String[] { "foo/a,bar/b" });
    RequestedModuleNames requestedNames = new RequestedModuleNames(request, null, null);
    assertEquals(Arrays.asList(new String[] { "foo/a", "bar/b" }), requestedNames.getScripts());
    assertEquals(Collections.emptyList(), requestedNames.getModules());
    assertFalse(TypeUtil
            .asBoolean(request.getAttribute(AbstractHttpTransport.WARN_DEPRECATED_USE_OF_MODULES_QUERYARG)));
    // now enable debug mode
    request.removeAttribute(AbstractHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME);
    request.removeAttribute(AbstractHttpTransport.WARN_DEPRECATED_USE_OF_MODULES_QUERYARG);
    mockAggregator.getOptions().setOption(IOptions.DEBUG_MODE, true);
    requestedNames = new RequestedModuleNames(request, null, null);
    assertEquals(Arrays.asList(new String[] { "foo/a", "bar/b" }), requestedNames.getScripts());
    assertTrue(TypeUtil
            .asBoolean(request.getAttribute(AbstractHttpTransport.WARN_DEPRECATED_USE_OF_MODULES_QUERYARG)));
    // make sure it works for development mode as well
    request.removeAttribute(AbstractHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME);
    request.removeAttribute(AbstractHttpTransport.WARN_DEPRECATED_USE_OF_MODULES_QUERYARG);
    mockAggregator.getOptions().setOption(IOptions.DEBUG_MODE, false);
    mockAggregator.getOptions().setOption(IOptions.DEVELOPMENT_MODE, true);
    requestedNames = new RequestedModuleNames(request, null, null);
    assertEquals(Arrays.asList(new String[] { "foo/a", "bar/b" }), requestedNames.getScripts());
    assertTrue(TypeUtil
            .asBoolean(request.getAttribute(AbstractHttpTransport.WARN_DEPRECATED_USE_OF_MODULES_QUERYARG)));

    // check the warn deprecated flag when using 'require' (dev/debug only)
    requestParams.clear();
    requestAttributes.clear();
    mockAggregator.getOptions().setOption(IOptions.DEVELOPMENT_MODE, false);
    requestAttributes.put(IAggregator.AGGREGATOR_REQATTRNAME, mockAggregator);
    requestParams.put(AbstractHttpTransport.REQUIRED_REQPARAM, new String[] { "foo/a,bar/b" });
    requestedNames = new RequestedModuleNames(request, null, null);
    assertEquals(Arrays.asList(new String[] { "foo/a", "bar/b" }), requestedNames.getDeps());
    assertFalse(TypeUtil
            .asBoolean(request.getAttribute(AbstractHttpTransport.WARN_DEPRECATED_USE_OF_REQUIRED_QUERYARG)));
    // now enable debug mode
    request.removeAttribute(AbstractHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME);
    request.removeAttribute(AbstractHttpTransport.WARN_DEPRECATED_USE_OF_REQUIRED_QUERYARG);
    mockAggregator.getOptions().setOption(IOptions.DEBUG_MODE, true);
    requestedNames = new RequestedModuleNames(request, null, null);
    assertEquals(Arrays.asList(new String[] { "foo/a", "bar/b" }), requestedNames.getDeps());
    assertTrue(TypeUtil
            .asBoolean(request.getAttribute(AbstractHttpTransport.WARN_DEPRECATED_USE_OF_REQUIRED_QUERYARG)));
    // make sure it works for development mode as well
    request.removeAttribute(AbstractHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME);
    request.removeAttribute(AbstractHttpTransport.WARN_DEPRECATED_USE_OF_REQUIRED_QUERYARG);
    mockAggregator.getOptions().setOption(IOptions.DEBUG_MODE, false);
    mockAggregator.getOptions().setOption(IOptions.DEVELOPMENT_MODE, true);
    requestedNames = new RequestedModuleNames(request, null, null);
    assertEquals(Arrays.asList(new String[] { "foo/a", "bar/b" }), requestedNames.getDeps());
    assertTrue(TypeUtil
            .asBoolean(request.getAttribute(AbstractHttpTransport.WARN_DEPRECATED_USE_OF_REQUIRED_QUERYARG)));
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.commons.ChooseContextDispatchActionNew.java

public ActionForward nextPagePublic(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    final ActionErrors errors = new ActionErrors();
    final DynaActionForm escolherContextoForm = (DynaActionForm) form;

    // degreeID/*w  ww  .  j ava 2 s.c om*/
    final String degreeId = getFromRequest("degreeID", request);
    request.setAttribute("degreeID", degreeId);

    // degreeCurricularPlanID
    final String degreeCurricularPlanId = getFromRequest("degreeCurricularPlanID", request);
    request.setAttribute("degreeCurricularPlanID", degreeCurricularPlanId);

    // lista
    final List<LabelValueBean> executionPeriodsLabelValueList = buildExecutionPeriodsLabelValueList(
            degreeCurricularPlanId);
    if (executionPeriodsLabelValueList.size() > 1) {
        request.setAttribute("lista", executionPeriodsLabelValueList);
    } else {
        request.removeAttribute("lista");
    }

    // curYear
    final Integer anoCurricular = (Integer) escolherContextoForm.get("curYear");
    request.setAttribute("curYear", anoCurricular);

    // infoDegreeCurricularPlan
    if (degreeCurricularPlanId != null) {
        final DegreeCurricularPlan degreeCurricularPlan = FenixFramework
                .getDomainObject(degreeCurricularPlanId);

        InfoDegreeCurricularPlan infoDegreeCurricularPlan = InfoDegreeCurricularPlan
                .newInfoFromDomain(degreeCurricularPlan);
        request.setAttribute("infoDegreeCurricularPlan", infoDegreeCurricularPlan);
    }

    InfoExecutionPeriod infoExecutionPeriod = (InfoExecutionPeriod) request
            .getAttribute(PresentationConstants.EXECUTION_PERIOD);
    String executionPeriodID = (String) escolherContextoForm.get("indice");
    if (StringUtils.isEmpty(executionPeriodID)) {
        executionPeriodID = getFromRequest("indice", request);
    }
    if (!StringUtils.isEmpty(executionPeriodID)) {
        infoExecutionPeriod = ReadExecutionPeriodByOID.run(executionPeriodID);
    }
    request.setAttribute("indice", infoExecutionPeriod.getExternalId());
    escolherContextoForm.set("indice", infoExecutionPeriod.getExternalId());
    RequestUtils.setExecutionPeriodToRequest(request, infoExecutionPeriod);
    request.setAttribute(PresentationConstants.EXECUTION_PERIOD, infoExecutionPeriod);
    request.setAttribute(PresentationConstants.EXECUTION_PERIOD_OID,
            infoExecutionPeriod.getExternalId().toString());
    request.setAttribute("semester", infoExecutionPeriod.getSemester());

    final ExecutionSemester executionSemester = FenixFramework
            .getDomainObject(infoExecutionPeriod.getExternalId());
    final DegreeCurricularPlan degreeCurricularPlan = FenixFramework.getDomainObject(degreeCurricularPlanId);
    ExecutionDegree executionDegree = degreeCurricularPlan
            .getExecutionDegreeByYear(executionSemester.getExecutionYear());
    if (executionDegree == null) {
        executionDegree = degreeCurricularPlan.getMostRecentExecutionDegree();

        if (executionDegree != null) {
            infoExecutionPeriod = InfoExecutionPeriod
                    .newInfoFromDomain(executionDegree.getExecutionYear().getExecutionSemesterFor(1));
            request.setAttribute("indice", infoExecutionPeriod.getExternalId());
            escolherContextoForm.set("indice", infoExecutionPeriod.getExternalId());
            RequestUtils.setExecutionPeriodToRequest(request, infoExecutionPeriod);
            request.setAttribute(PresentationConstants.EXECUTION_PERIOD, infoExecutionPeriod);
            request.setAttribute(PresentationConstants.EXECUTION_PERIOD_OID,
                    infoExecutionPeriod.getExternalId().toString());
            request.setAttribute("semester", infoExecutionPeriod.getSemester());
        }
    }

    if (executionDegree != null) {
        InfoExecutionDegree infoExecutionDegree = InfoExecutionDegree.newInfoFromDomain(executionDegree);
        request.setAttribute(PresentationConstants.EXECUTION_DEGREE, infoExecutionDegree);
        request.setAttribute("executionDegreeID", infoExecutionDegree.getExternalId().toString());
        RequestUtils.setExecutionDegreeToRequest(request, infoExecutionDegree);

        request.setAttribute("infoDegreeCurricularPlan", infoExecutionDegree.getInfoDegreeCurricularPlan());
        request.setAttribute(PresentationConstants.INFO_DEGREE_CURRICULAR_PLAN,
                infoExecutionDegree.getInfoDegreeCurricularPlan());
    }

    String nextPage = request.getParameter("nextPage");
    if (nextPage != null) {
        return mapping.findForward(nextPage);
    } else {
        throw new FenixActionException();
    }

}

From source file:Index.LoginServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w  w w .  ja  v a2 s .  c  o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();

    try {
        String user, password, errorMessage;
        if (request.getParameter("user") != null && request.getParameter("password") != null) {

            user = request.getParameter("user");
            password = request.getParameter("password");

            if (user.equalsIgnoreCase("") || password.equalsIgnoreCase("")) {

                errorMessage = "Ingrese todos los datos.";
                request.setAttribute("error", errorMessage);
                request.setAttribute("funcionalidad", "Login");
                request.getRequestDispatcher("/Login.jsp").forward(request, response);

            } else {

                if (user.equals("admin") && password.equals("admin")) {

                    HttpSession session = request.getSession();
                    session.setAttribute("Admin", user);
                    request.removeAttribute("error");
                    request.removeAttribute("funcionalidad");
                    request.getRequestDispatcher("/Index.jsp").forward(request, response);
                } else {
                    QuickOrderWebService webService = new QuickOrderWebService();
                    ControllerInterface port = webService.getQuickOrderWebServicePort();
                    webservice.Cliente usr = port.infoCliente(user);

                    if (usr != null && usr.getNickname() != null) {

                        String encriptMD5 = DigestUtils.md5Hex(password);
                        password = "md5:" + encriptMD5;

                        if (usr.getPassword().equals(password)) {
                            HttpSession session = request.getSession();
                            session.setAttribute("Usuario", usr);

                            request.removeAttribute("error");
                            request.removeAttribute("funcionalidad");
                            request.getRequestDispatcher("/Index.jsp").forward(request, response);
                        } else {
                            errorMessage = "Credenciales invalidas";
                            request.setAttribute("error", errorMessage);
                            request.setAttribute("funcionalidad", "Login");
                            request.getRequestDispatcher("/Login.jsp").forward(request, response);
                        }
                    } else {
                        errorMessage = "Credenciales invalidas";
                        request.setAttribute("error", errorMessage);
                        request.setAttribute("funcionalidad", "Login");
                        request.getRequestDispatcher("/Login.jsp").forward(request, response);
                    }
                }
            }
        } else {
            errorMessage = "Error al realizar login.";
            request.setAttribute("error", errorMessage);
            request.setAttribute("funcionalidad", "Login");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Login.jsp");
            dispatcher.forward(request, response);
        }
    } catch (Exception ex) {
        out.println("Error en proceso de login: " + ex.getMessage());
    } finally {
        out.close();
    }

}

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

/**
 * *****************************************************************************
 * Crea los programas de los usuarios y los almacena en la base de datos.
 * *****************************************************************************
 * @param id//from   w ww.  ja v  a2 s  .  c o m
 * @param request
 * @param response
 * @return
 * @throws Exception 
 */
@RequestMapping("/programa/crear/{id}")
public ModelAndView crear(@PathVariable Integer id, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    HttpSession sess = request.getSession();
    if (sess != null) {
        Programa p = new Programa();
        ModelAndView m = new ModelAndView("/programa/crear");

        Session s = HibernateUtil.getSessionFactory().openSession();
        Modelo u = (Modelo) s.get(Modelo.class, id);

        Criteria cm = s.createCriteria(Programa.class);
        cm.add(Restrictions.eq("modelo", u));
        List<Programa> l = cm.list();
        //cm.add(Restrictions.eq(id, u.getModeloId()));
        if (l.isEmpty()) {
            //System.out.print("si");
            p.setModelo(u);
            p.setDescripcion("");
            Transaction t = s.getTransaction();
            s.beginTransaction();
            s.saveOrUpdate(p);
            t.commit();
            m.addObject("programa", p);
            //p.setModelo(u.getModeloId());
            return m;
        }

        return lista(request, response);
    } else {
        request.removeAttribute("usuario");
        return new ModelAndView("redirect:/usuario/login.htm");
    }
}

From source file:com.glaf.oa.contract.web.springmvc.ContractController.java

@RequestMapping("/review")
public ModelAndView review(HttpServletRequest request, ModelMap modelMap) {
    RequestUtils.setRequestParameterToAttribute(request);
    request.removeAttribute("canSubmit");

    Contract contract = contractService.getContract(RequestUtils.getLong(request, "id"));
    if (RequestUtils.getBoolean(request, "lookover")) {
        request.setAttribute("lookover", true);
    } else {//from   w  w w  . j  a va  2s. c  o m
        request.setAttribute("lookover", false);
    }

    if (contract != null) {
        request.setAttribute("contract", contract);
        JSONObject rowJSON = contract.toJsonObject();
        request.setAttribute("x_json", rowJSON.toJSONString());
    }

    boolean canUpdate = false;
    String x_method = request.getParameter("x_method");
    if (StringUtils.equals(x_method, "submit")) {

    }

    if (StringUtils.containsIgnoreCase(x_method, "update")) {
        if (contract != null) {
            if (contract.getStatus() == 0 || contract.getStatus() == -1) {
                canUpdate = true;
            }
        }
    }

    request.setAttribute("canUpdate", canUpdate);

    // ?
    List<BaseDataInfo> brandlist = BaseDataManager.getInstance().getDataList("Brand");
    BaseDataInfo brand1 = null;
    BaseDataInfo brand2 = null;
    for (BaseDataInfo info : brandlist) {
        if ("1".equals(info.getValue())) {
            request.setAttribute("brand1", info.getName());
            brand1 = info;
        } else if ("2".equals(info.getValue())) {
            request.setAttribute("brand2", info.getName());
            brand2 = info;
        }
    }
    if (contract != null) {
        if ("".equals(contract.getBrands1().trim()) && "".equals(contract.getBrands2().trim())) {
            request.setAttribute("Brands", "MUL");
        } else if (!"".equals(contract.getBrands1().trim()) && "".equals(contract.getBrands2().trim())) {
            request.setAttribute("Brands", brand1.getCode());
        } else if (!"".equals(contract.getBrands2().trim()) && "".equals(contract.getBrands1().trim())) {
            request.setAttribute("Brands", brand2.getCode());
        } else if (!"".equals(contract.getBrands2().trim()) && !"".equals(contract.getBrands1().trim())) {
            request.setAttribute("Brands", "MUL");
        }
    }

    String view = request.getParameter("view");
    if (StringUtils.isNotEmpty(view)) {
        return new ModelAndView(view, modelMap);
    }

    String x_view = ViewProperties.getString("contract.edit");
    if (StringUtils.isNotEmpty(x_view)) {
        return new ModelAndView(x_view, modelMap);
    }

    return new ModelAndView("/oa/contract/review", modelMap);
}

From source file:com.ms.commons.summer.web.handler.ComponentMethodHandlerAdapter.java

private ModelAndView buildModelAndView(HttpServletRequest request, HttpServletResponse response, Object result,
        ExtendedModelMap model) {//from   w ww.  j  ava 2  s  .  co m
    if (result instanceof WebResult) {
        // mime
        if (result instanceof MimeResult) {
            return new MimeModelAndView((MimeResult) result);
        }
        WebResult webResult = (WebResult) result;
        // ??,model?
        if (result instanceof Redirect) {
            model.clear();
        } else {
            model.addAllAttributes(webResult.getParameters());
            if (result instanceof View) {
                View view = (View) result;
                if (!view.isUselayout()) {
                    request.setAttribute(SummerVelocityLayoutView.USE_LAYOUT, "false");
                }
            }
            // forward,request??
            else if (result instanceof Forward) {
                request.removeAttribute(NAMESPACE_KEY);
            }
        }
        return new WebResultModelAndView(webResult.getView()).addAllObjects(model);
    } else {
        return new ModelAndView().addAllObjects(model);
    }
}

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

@RequestMapping("/usuario/lista")
public ModelAndView lista(HttpServletRequest request, HttpServletResponse response) throws IOException {
    HttpSession sess = request.getSession();
    if (sess != null) {
        Session s = HibernateUtil.getSessionFactory().openSession();

        Criteria c = s.createCriteria(Usuario.class);
        List<Usuario> l = c.list();
        ModelAndView m = new ModelAndView("/usuario/lista");
        //HttpSession session = request.getSession(true);
        //Usuario us = (Usuario)request.getAttribute("usuario");
        Usuario us = (Usuario) sess.getAttribute("usuario");
        //Usuario us = (Usuario)session.getAttribute("usuario");

        if (us == null) {
            return new ModelAndView("redirect:/usuario/login.htm");
        } else {//from  w  ww.  j  a v  a2  s .c o  m
            m.addObject("nombreUsuario", us.getNombre());
            m.addObject("usuarios", l);
            logger.info("Empieza a mostrar lista");
            return m;
        }
    } else {
        request.removeAttribute("usuario");
        return new ModelAndView("redirect:/usuario/login.htm");
    }
}

From source file:com.glaf.oa.contract.web.springmvc.ContractController.java

@RequestMapping("/edit")
public ModelAndView edit(HttpServletRequest request, ModelMap modelMap) {
    User user = RequestUtils.getUser(request);
    RequestUtils.setRequestParameterToAttribute(request);
    request.removeAttribute("canSubmit");
    Contract contract = contractService.getContract(RequestUtils.getLong(request, "id"));
    if (contract != null) {
        request.setAttribute("contract", contract);
        JSONObject rowJSON = contract.toJsonObject();
        request.setAttribute("x_json", rowJSON.toJSONString());
    }//from w w  w  .j a v  a2 s  . com

    boolean canUpdate = false;
    String x_method = request.getParameter("x_method");
    if (StringUtils.equals(x_method, "submit")) {

    }

    if (StringUtils.containsIgnoreCase(x_method, "update")) {
        if (contract != null) {
            if (contract.getStatus() == 0 || contract.getStatus() == -1) {
                canUpdate = true;
            }
        }
    }

    request.setAttribute("canUpdate", canUpdate);

    if (contract != null) {

    } else {
        contract = new Contract();
        long deptId01 = user.getDeptId();
        SysDepartment curdept = sysDepartmentService.findById(deptId01);
        // ?
        String curAreadeptCode = curdept.getCode().substring(0, 2);

        contract.setArea(curAreadeptCode);
        contract.setDept(curdept.getCode());
        contract.setAppuser(user.getActorId());
        contract.setPost(RequestUtil.getLoginUser(request).getHeadship());
        request.setAttribute("contract", contract);
        JSONObject rowJSON = contract.toJsonObject();
        request.setAttribute("x_json", rowJSON.toJSONString());
    }

    String view = request.getParameter("view");
    if (StringUtils.isNotEmpty(view)) {
        return new ModelAndView(view, modelMap);
    }

    String x_view = ViewProperties.getString("contract.edit");
    if (StringUtils.isNotEmpty(x_view)) {
        return new ModelAndView(x_view, modelMap);
    }

    return new ModelAndView("/oa/contract/edit", modelMap);
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.resourceAllocationManager.ManageLessonDA.java

public ActionForward deleteLesson(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    List<String> lessons = new ArrayList<String>();
    lessons.add(request.getParameter(PresentationConstants.LESSON_OID));

    try {/*from   w w w .j ava  2s.com*/
        DeleteLessons.run(lessons);

    } catch (FenixServiceMultipleException e) {
        final ActionErrors actionErrors = new ActionErrors();
        for (final DomainException domainException : e.getExceptionList()) {
            actionErrors.add(domainException.getMessage(),
                    new ActionError(domainException.getMessage(), domainException.getArgs()));
        }
        saveErrors(request, actionErrors);
        return mapping.findForward("LessonDeleted");
    }

    request.removeAttribute(PresentationConstants.LESSON_OID);
    return mapping.findForward("LessonDeleted");
}

From source file:org.springframework.web.servlet.SimpleDispatcherServlet.java

/**
 * Return the HandlerExecutionChain for this request. Try all handler mappings in order.
 * @param request current HTTP request/* w w  w.j a v  a2 s  .co  m*/
 * @param cache whether to cache the HandlerExecutionChain in a request attribute
 * @return the HandlerExceutionChain, or <code>null</code> if no handler could be found
 */
public HandlerExecutionChain getHandler(HttpServletRequest request, boolean cache) throws Exception {
    HandlerExecutionChain handler = (HandlerExecutionChain) request
            .getAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);
    if (handler != null) {
        if (!cache) {
            request.removeAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);
        }
        return handler;
    }

    for (HandlerMapping hm : this.handlerMappings) {
        if (logger.isTraceEnabled()) {
            logger.trace("Testing handler map [" + hm + "] in DispatcherServlet with name '" + getServletName()
                    + "'");
        }
        handler = hm.getHandler(request);
        if (handler != null) {
            if (cache) {
                request.setAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE, handler);
            }
            return handler;
        }
    }
    return null;
}