Example usage for javax.servlet.http HttpSession removeAttribute

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

Introduction

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

Prototype

public void removeAttribute(String name);

Source Link

Document

Removes the object bound with the specified name from this session.

Usage

From source file:com.xhm.longxin.qth.web.admin.module.action.AdminAction.java

public void doLogout(HttpSession session, Navigator nav, ParameterParser params) throws Exception {

    session.removeAttribute(AdminConstant.QTH_ADMIN_SESSION_KEY);

    redirectToReturnPage(nav, params);// w ww  . ja va2s. c  o m
}

From source file:com.controller.RecipeImage.java

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

    //retrieving the path to store image from web.xml
    filePath = getServletContext().getInitParameter("recipeImageStorePath");

    //retrieving the path to display image from web.xml
    fileDisplay = getServletContext().getInitParameter("recipeImageDisplayPath");

    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("c:\\temp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("1");
        while (i.hasNext()) {
            out.println("2");
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                fileName = randomString(fileName);
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                out.println("Uploaded Filename: " + fileName + "<br>" + filePath);
            } else {
                out.println("No file");
            }
        }
        out.println("</body>");
        out.println("</html>");

        RecipeBean recipeBean = new RecipeBean();
        RecipeDAO recipeDAO = new RecipeDAO();

        String image = fileDisplay + "" + fileName;
        out.println(image);

        HttpSession session = request.getSession();
        String recipeId = (String) session.getAttribute("recipeId");
        session.removeAttribute("recipeId");
        recipeDAO.addImage(recipeId, image);

        response.sendRedirect("Home");

    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:gov.nih.nci.ncicb.cadsr.umlmodelbrowser.struts.actions.BaseDispatchAction.java

/**
 * Remove a session object based on the request and the attribute name.
 *//*from   w  w w  .jav a2  s.  c  o  m*/
protected void removeSessionObject(HttpServletRequest req, String attrName) {
    HttpSession session = req.getSession(false);

    if (session != null) {
        session.removeAttribute(attrName);
    }
}

From source file:nl.strohalm.cyclos.controls.access.ListConnectedUsersAction.java

@Override
@SuppressWarnings("unchecked")
protected ActionForward executeAction(final ActionContext context) throws Exception {
    final ListConnectedUsersForm form = context.getForm();
    final HttpServletRequest request = context.getRequest();
    final HttpSession session = request.getSession();
    List<UserLoginDTO> users;
    if (context.isAdmin()) {
        Collection<Nature> natures = getDataBinder().readFromString(form);
        if (RequestHelper.isFromMenu(request)) {
            session.removeAttribute("_natures");
        } else {//from  w ww  .  jav a 2 s  .  c o m
            if (CollectionUtils.isEmpty(natures)) {
                natures = (Collection<Nature>) session.getAttribute("_natures");
            } else {
                session.setAttribute("_natures", natures);
            }
        }
        request.setAttribute("selectedNatures", natures);
        users = getAccessService().listConnectedUsers(natures);

        final PermissionService permissionService = getPermissionService();
        final List<Group.Nature> groupNatures = new ArrayList<Nature>();
        if (permissionService.checkPermission("systemStatus", "viewConnectedAdmins")) {
            groupNatures.add(Group.Nature.ADMIN);
        }
        if (permissionService.checkPermission("systemStatus", "viewConnectedMembers")) {
            groupNatures.add(Group.Nature.MEMBER);
        }
        if (permissionService.checkPermission("systemStatus", "viewConnectedBrokers")) {
            groupNatures.add(Group.Nature.BROKER);
        }
        if (permissionService.checkPermission("systemStatus", "viewConnectedOperators")) {
            groupNatures.add(Group.Nature.OPERATOR);
        }
        request.setAttribute("groupNatures", groupNatures);
        request.setAttribute("canDisconnectAdmin",
                permissionService.checkPermission("adminAdminAccess", "disconnect"));
        request.setAttribute("canDisconnectMember",
                permissionService.checkPermission("adminMemberAccess", "disconnect"));
    } else {
        users = getAccessService().listConnectedOperators();
    }
    request.setAttribute("users", users);
    return context.getInputForward();
}

From source file:puma.sp.authentication.controllers.authentication.AccessController.java

@RequestMapping(value = "/SubmitWAYF", method = RequestMethod.GET)
public String submitWAYF(ModelMap model, HttpSession session) {
    if (session.getAttribute("Authenticated") == null
            || !((Boolean) session.getAttribute("Authenticated")).booleanValue()) {
        Tenant tenantObject = (Tenant) session.getAttribute("ChosenTenant");
        session.removeAttribute("ChosenTenant");
        if (tenantObject == null) {
            // Redirect back to WAYF with message
            session.setAttribute("FlowRedirectionElement", new FlowDirecter("/SubmitWAYF"));
            return "redirect:/";
        } else {/* ww  w .  ja va 2 s.c o  m*/
            session.setAttribute("Tenant", tenantObject);
            this.ensureRelayState(session);
            // Redirect to next flow element
            return "redirect:/AuthenticationRequestServlet";
        }
    } else {
        // Obtain relay state
        String relayState = this.ensureRelayState(session);
        // Check tenants, if different or null ('something went wrong'), logout
        Tenant one = (Tenant) session.getAttribute("ChosenTenant");
        Tenant other = (Tenant) session.getAttribute("Tenant");
        if (one == null || other == null || !one.equals(other))
            return "redirect:/LogoutServlet?RelayState=" + relayState;
        // Else, redirect to authenticatino servlet
        session.removeAttribute("ChosenTenant");
        return "redirect:/AuthenticationRequestServlet";
    }
}

From source file:org.duracloud.account.app.controller.AccountGroupsControllerTest.java

@Test
public void testGetGroupEdit() throws Exception {
    expectGroupGroups(1);/*from  ww w  .  ja v a  2 s.  c  o  m*/

    HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
    HttpSession session = EasyMock.createMock(HttpSession.class);
    EasyMock.expect(request.getSession()).andReturn(session).once();

    session.removeAttribute(AccountGroupsController.GROUP_USERS_KEY);
    EasyMock.expectLastCall().once();

    EasyMock.expect(session.getAttribute(AccountGroupsController.GROUP_USERS_KEY)).andReturn(null).once();

    session.setAttribute(EasyMock.anyObject(String.class), (Collection<DuracloudUser>) EasyMock.anyObject());
    EasyMock.expectLastCall().once();

    EasyMock.replay(request, session);

    replayMocks();
    String view = this.accountGroupsController.editGroup(accountId, DuracloudGroup.PREFIX + TEST_GROUP_NAME,
            request, model);
    Assert.assertEquals(AccountGroupsController.GROUP_EDIT_VIEW_ID, view);
    Assert.assertNotNull(getModelAttribute(AccountGroupsController.GROUP_KEY));
    Assert.assertNotNull(getModelAttribute(AccountGroupsController.GROUP_USERS_KEY));
    Assert.assertNotNull(getModelAttribute(AccountGroupsController.AVAILABLE_USERS_KEY));

}

From source file:fr.paris.lutece.plugins.crm.business.demand.PaginationFilterSortManager.java

/**
 * Delete stored values for filter/*  w w w  .ja v  a2  s.  c o  m*/
 */
public void cleanSessionFilter() {
    HttpSession session = _request.getSession();
    session.removeAttribute(SESSION_FILTER_DEMAND_TYPE);
    session.removeAttribute(SESSION_FILTER_MODIFICATION_DATE);
    session.removeAttribute(SESSION_FILTER_NOTIFICATION);
}

From source file:cn.edu.zjnu.acm.judge.user.ResetPasswordController.java

@PostMapping("/resetPassword")
public void doPost(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "action", required = false) String action,
        @RequestParam(value = "verify", required = false) String verify,
        @RequestParam(value = "username", required = false) String username, Locale locale) throws IOException {
    response.setContentType("text/javascript;charset=UTF-8");
    PrintWriter out = response.getWriter();

    HttpSession session = request.getSession(false);
    String word = null;/*ww w.j  av a2 s. co m*/
    if (session != null) {
        word = (String) session.getAttribute("word");
        session.removeAttribute("word");
    }
    if (word == null || !word.equalsIgnoreCase(verify)) {
        out.print("alert('??');");
        return;
    }

    User user = userMapper.findOne(username);
    if (user == null) {
        out.print("alert('?');");
        return;
    }
    String email = user.getEmail();
    if (email == null || !email.toLowerCase().matches(ValueCheck.EMAIL_PATTERN)) {
        out.print(
                "alert('???????');");
        return;
    }
    try {
        String vc = user.getVcode();
        if (vc == null || user.getExpireTime() != null && user.getExpireTime().compareTo(Instant.now()) < 0) {
            vc = Utility.getRandomString(16);
        }
        user = user.toBuilder().vcode(vc).expireTime(Instant.now().plus(1, ChronoUnit.HOURS)).build();
        userMapper.update(user);
        String url = getPath(request, "/resetPassword.html?vc=", vc + "&u=", user.getId());
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("url", url);
        map.put("ojName", judgeConfiguration.getContextPath() + " OJ");

        String content = templateEngine.process("users/password", new Context(locale, map));
        String title = templateEngine.process("users/passwordTitle", new Context(locale, map));

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setTo(email);
        helper.setSubject(title);
        helper.setText(content, true);
        helper.setFrom(javaMailSender.getUsername());

        javaMailSender.send(mimeMessage);
    } catch (MailException | MessagingException ex) {
        log.error("", ex);
        out.print("alert('?????')");
        return;
    }
    out.print("alert('???" + user.getEmail() + "??');");
}

From source file:com.exxonmobile.ace.hybris.storefront.controllers.pages.AbstractLoginPageController.java

protected String getDefaultLoginPage(final boolean loginError, final HttpSession session, final Model model)
        throws CMSItemNotFoundException {
    final LoginForm loginForm = new LoginForm();
    model.addAttribute(loginForm);/*  www .ja va 2s.  c o  m*/
    final String username = (String) session.getAttribute(SPRING_SECURITY_LAST_USERNAME);
    if (username != null) {
        session.removeAttribute(SPRING_SECURITY_LAST_USERNAME);
    }

    loginForm.setJ_username(username);
    storeCmsPageInModel(model, getLoginCmsPage());
    setUpMetaDataForContentPage(model, (ContentPageModel) getLoginCmsPage());
    model.addAttribute("metaRobots", "index,no-follow");

    final Breadcrumb loginBreadcrumbEntry = new Breadcrumb("#",
            getMessageSource().getMessage("header.link.login", null, getI18nService().getCurrentLocale()),
            null);
    model.addAttribute("breadcrumbs", Collections.singletonList(loginBreadcrumbEntry));

    if (loginError) {
        GlobalMessages.addErrorMessage(model, "login.error.account.not.found.title");
    }

    return getLoginView();
}