Java Code Examples for javax.servlet.http.HttpSession#removeAttribute()

The following examples show how to use javax.servlet.http.HttpSession#removeAttribute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MessageSaver.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Restore saved messages.
 * 
 * @param context
 *        The current faces context.
 */
public static void restoreMessages(FacesContext context)
{
	if (context == null) return;

	// look in the session
	HttpSession s = (HttpSession) context.getExternalContext().getSession(false);
	if (s == null) return;

	// get messages
	List msgs = (List) s.getAttribute(ATTR_MSGS);
	if (msgs != null)
	{
		// process each one - add it to this context's message set
		for (Iterator iMessages = msgs.iterator(); iMessages.hasNext();)
		{
			FacesMessage msg = (FacesMessage) iMessages.next();
			// Note: attributed to no specific tree element
			context.addMessage(null, msg);
		}

		s.removeAttribute(ATTR_MSGS);
	}
}
 
Example 2
Source File: UserController.java    From Cynthia with GNU General Public License v2.0 6 votes vote down vote up
/**
	 * @description:user login
	 * @date:2014-5-5 下午8:45:46
	 * @version:v1.0
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/logout.do")
	@ResponseBody
	public String logout(HttpServletRequest request, HttpServletResponse response ,HttpSession session) throws Exception {
		CookieManager.delCookie(response, "jpassport-sp");
		CookieManager.delCookie(response, "login_username");
		CookieManager.delCookie(response, "login_nickname");
		CookieManager.delCookie(response, "login_password");
		CookieManager.delCookie(response, "id");
		CookieManager.delCookie(response, "userId");
		session.removeAttribute("key");
		session.removeAttribute("userName");
		session.invalidate();
		String targetUrl = request.getParameter("targetUrl"); //是否回跳
		if (!CynthiaUtil.isNull(targetUrl)) {
			String logoutUrl  = ConfigUtil.getLogOutUrl();
//			logoutUrl += (logoutUrl.indexOf("?") != -1 ? "&" : "?") + "targetUrl=" + URLEncoder.encode(targetUrl,"UTF-8");
			logoutUrl += (logoutUrl.indexOf("?") != -1 ? "&" : "?") + "targetUrl=" + URLEncoder.encode(targetUrl,"UTF-8") + "&returnUrl=" + ConfigUtil.getCynthiaWebRoot() + "user/login.do";
			System.out.println("usercontroller sendredirect:" + logoutUrl);
			response.sendRedirect(logoutUrl);
		}
		return "";
	}
 
Example 3
Source File: ProgressServlet.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
  * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
  * @param request
  * @param response
  * @throws IOException
  * @throws ServletException
  */
 public void doPost (HttpServletRequest request, HttpServletResponse response)
 throws IOException, ServletException {
 	// We get a Session object
     HttpSession session = request.getSession(false);
     try {
     	MyPdf pdf = (MyPdf) session.getAttribute("myPdf");
     	session.removeAttribute("myPdf");
ByteArrayOutputStream baos = pdf.getPdf();
//setting some response headers
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
//setting the content type
response.setContentType("application/pdf");
// the contentlength is needed for MSIE!!!
response.setContentLength(baos.size());
// write ByteArrayOutputStream to the ServletOutputStream
ServletOutputStream out = response.getOutputStream();
baos.writeTo(out);
out.flush();
     }
     catch(Exception e) {
     	isError(response.getOutputStream());
     }
 }
 
Example 4
Source File: LoginController.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
/**
 * 生成校验码图,每次访问会随机生成新的校验码图
 */
@GetMapping("checkcode")
public void authImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");
    // 生成随机字串
    CheckCodeUtils.CheckCode checkCode = CheckCodeUtils.create(60);
    // 存入会话session
    HttpSession session = request.getSession(true);
    // 删除以前的
    session.removeAttribute("code");
    session.removeAttribute("expireTime");
    session.setAttribute("code", checkCode.getCode());
    session.setAttribute("expireTime", checkCode.getExpireTime());
    OutputStream out = response.getOutputStream();
    CheckCodeUtils.toOutputStream(checkCode, out);
}
 
Example 5
Source File: TicketController.java    From Movie-Ticketing-System-BC-2018.7 with MIT License 6 votes vote down vote up
@RequestMapping(value="/user/ListTicketsCtrl", method=RequestMethod.POST)
public String listBy(Model model, HttpSession session, String date, String price) {		
	session.removeAttribute("TicketQueryState");
	
	List<Ticket> list=null;
	TicketQueryState state= new TicketQueryState(0,date,price);
	
	try {
			int lastPage = ticketService.getLastPage(state);
			state.setLastPage(lastPage);
			list = ticketService.getTickets(state);
			session.setAttribute("TicketQueryState", state);
			model.addAttribute("lastPage", lastPage);
		
	} catch (Exception e) {
		e.printStackTrace();
	}
	session.setAttribute("listTickets", list); 
	return "user/BookingTicket";
}
 
Example 6
Source File: AuthController.java    From my-site with Apache License 2.0 6 votes vote down vote up
/**
 * 注销
 *
 * @param session
 * @param response
 */
@RequestMapping("/logout")
public void logout(HttpSession session, HttpServletResponse response, org.apache.catalina.servlet4preview.http.HttpServletRequest request) {
    session.removeAttribute(WebConst.LOGIN_SESSION_KEY);
    Cookie cookie = new Cookie(WebConst.USER_IN_COOKIE, "");
    cookie.setValue(null);
    cookie.setMaxAge(0);// 立即销毁cookie
    cookie.setPath("/");
    response.addCookie(cookie);
    try {
        response.sendRedirect("/admin/login");
    } catch (IOException e) {
        e.printStackTrace();
        LOGGER.error("注销失败", e);
    }
}
 
Example 7
Source File: ImportUserResultController.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@RequestMapping(path = "/importuserresult")
   public String execute(HttpServletRequest request) throws Exception {
HttpSession ss = SessionManager.getSession();

List results = (List) ss.getAttribute(IImportService.IMPORT_RESULTS);
String successMessageKey = "";
try {
    MultipartFile file = (MultipartFile) ss.getAttribute(IImportService.IMPORT_FILE);
    successMessageKey = (importService.isUserSpreadsheet(file) ? "msg.users.created" : "msg.users.added");
} catch (Exception e) {
    log.error("Couldn't check spreadsheet type!", e);
}

int successful = 0;
for (int i = 0; i < results.size(); i++) {
    ArrayList rowResult = (ArrayList) results.get(i);
    if (rowResult.isEmpty()) {
	successful++;
    }
}
String[] args = new String[1];
args[0] = String.valueOf(successful);

request.setAttribute("results", results);
request.setAttribute("successful", messageService.getMessage(successMessageKey, args));

// remove temporary session vars that allowed status to be displayed
// to user during import
ss.removeAttribute(IImportService.STATUS_IMPORT_TOTAL);
ss.removeAttribute(IImportService.STATUS_IMPORTED);
ss.removeAttribute(IImportService.IMPORT_FILE);
ss.removeAttribute(IImportService.IMPORT_RESULTS);

return "import/importresult";
   }
 
Example 8
Source File: WebController.java    From hasor with Apache License 2.0 5 votes vote down vote up
/**
 * Remove Object in session.
 * @param key a String specifying the key of the Object stored in session
 * @return 返回this.
 */
protected WebController removeSessionAttr(String key) {
    HttpSession session = this.getRequest().getSession(false);
    if (session != null) {
        session.removeAttribute(key);
    }
    return this;
}
 
Example 9
Source File: StudentController.java    From ssm-Online_Examination with Apache License 2.0 5 votes vote down vote up
/**
 * 退出
 * @param request
 * @return
 */
@RequestMapping(value = "logout.do")
public String logout(HttpServletRequest request){
    HttpSession session = request.getSession();
    session.removeAttribute("student");
    return "index";
}
 
Example 10
Source File: SessionStorage.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Wrapper for HttpSession.getAttribute
 * @param session The user's session.
 * @param key The key of the stored object.
 */
public void removeAttribute(final HttpSession session, final String key)
{
  synchronized (session) {
    if (log.isDebugEnabled() == true) {
      log.debug("Removing object from the user's session " + session.getId() + " with key " + key);
    }
    session.removeAttribute(key);
  }
}
 
Example 11
Source File: ClearSessionController.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
   public void clearSession(String customiseSessionID, HttpSession session, ToolAccessMode mode) {
session.removeAttribute(CommonConstants.LAMS_AUTHORING_SUCCESS_FLAG);
if (mode.isAuthor()) {
    ClearSessionController.logger.debug("In Author mode");
    session.removeAttribute(customiseSessionID);
}
   }
 
Example 12
Source File: AuthorizationFilter.java    From development with Apache License 2.0 5 votes vote down vote up
private void rollbackDefaultTimeout(HttpServletRequest httpRequest) {
    HttpSession session = httpRequest.getSession();
    Integer attributeInt = (Integer) session.getAttribute(Constants.SESS_ATTR_DEFAULT_TIMEOUT);
    if (attributeInt != null) {
        session.setMaxInactiveInterval(attributeInt.intValue());
        session.removeAttribute(Constants.SESS_ATTR_DEFAULT_TIMEOUT);
    }
}
 
Example 13
Source File: AdminController.java    From QiQuYingServer with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value="/loginout")
public String loginOut(HttpSession session) {
	session.removeAttribute(Constants.KEY_CURR_USER);
	return "redirect:login";
}
 
Example 14
Source File: AdminController.java    From Movie-Ticketing-System-BC-2018.7 with MIT License 4 votes vote down vote up
@RequestMapping(value="/LogoutCtrl", method=RequestMethod.GET)
public String logout(HttpSession session) {
	session.removeAttribute(AdminLoginFilter.ATTR_ADMINUSER);
	return "redirect:../";
}
 
Example 15
Source File: PassiveSTS.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private void process(HttpServletRequest request, HttpServletResponse response,
                     SessionDTO sessionDTO, AuthenticationResult authnResult) throws ServletException, IOException {

    HttpSession session = request.getSession();

    session.removeAttribute(PassiveRequestorConstants.PASSIVE_REQ_ATTR_MAP);

    RequestToken reqToken = new RequestToken();

    Map<ClaimMapping, String> attrMap = authnResult.getSubject().getUserAttributes();
    StringBuilder buffer = null;

    if (MapUtils.isNotEmpty(attrMap)) {
        buffer = new StringBuilder();
        for (Iterator<Entry<ClaimMapping, String>> iterator = attrMap.entrySet().iterator(); iterator
                .hasNext(); ) {
            Entry<ClaimMapping, String> entry = iterator.next();
            buffer.append("{" + entry.getKey().getRemoteClaim().getClaimUri() + "|" + entry.getValue() + "}#CODE#");
        }
    }

    reqToken.setAction(sessionDTO.getAction());
    if (buffer != null) {
        reqToken.setAttributes(buffer.toString());
    } else {
        reqToken.setAttributes(sessionDTO.getAttributes());
    }
    reqToken.setContext(sessionDTO.getContext());
    reqToken.setReplyTo(sessionDTO.getReplyTo());
    reqToken.setPseudo(sessionDTO.getPseudo());
    reqToken.setRealm(sessionDTO.getRealm());
    reqToken.setRequest(sessionDTO.getRequest());
    reqToken.setRequestPointer(sessionDTO.getRequestPointer());
    reqToken.setPolicy(sessionDTO.getPolicy());
    reqToken.setPseudo(session.getId());
    reqToken.setUserName(authnResult.getSubject().getAuthenticatedSubjectIdentifier());
    reqToken.setTenantDomain(sessionDTO.getTenantDomain());

    String serverURL = CarbonUIUtil.getServerURL(session.getServletContext(), session);
    ConfigurationContext configContext =
            (ConfigurationContext) session.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);

    IdentityPassiveSTSClient passiveSTSClient = null;
    passiveSTSClient = new IdentityPassiveSTSClient(serverURL, configContext);

    ResponseToken respToken = passiveSTSClient.getResponse(reqToken);

    if (respToken != null && respToken.getResults() != null) {
        persistRealms(reqToken, request.getSession());
        sendData(response, respToken, reqToken.getAction(),
                 authnResult.getAuthenticatedIdPs());
    }
}
 
Example 16
Source File: ClearSessionController.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
   public void clearSession(String customiseSessionID, HttpSession session, ToolAccessMode mode) {
if (mode.isAuthor()) {
    session.removeAttribute(customiseSessionID);
}
   }
 
Example 17
Source File: ClearSessionController.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
   public void clearSession(String customiseSessionID, HttpSession session, ToolAccessMode mode) {
if (mode.isAuthor()) {
    session.removeAttribute(customiseSessionID);
}
   }
 
Example 18
Source File: UseController.java    From activiti-in-action-codes with Apache License 2.0 4 votes vote down vote up
/**
 * 退出登录
 */
@RequestMapping(value = "/logout")
public String logout(HttpSession session) {
    session.removeAttribute("user");
    return "/login";
}
 
Example 19
Source File: WebauthnService.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
@POST
@Path("/" + Constants.RP_REGISTER_PATH)
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response register(JsonObject input) {
    try{
        HttpSession session = request.getSession(false);
        if(session == null){
            return generateResponse(Response.Status.FORBIDDEN, POCLogger.getMessageProperty("POC-WS-ERR-1003"));
        }

        //Get information stored in session
        String email = (String) session.getAttribute(Constants.SESSION_EMAIL);
        String username = (String) session.getAttribute(Constants.SESSION_USERNAME);
        String firstName = (String) session.getAttribute(Constants.SESSION_FIRSTNAME);
        String lastName = (String) session.getAttribute(Constants.SESSION_LASTNAME);

        //Verify email was not used to generate another account
        if (doesEmailExist(email)) {
            POCLogger.logp(Level.SEVERE, CLASSNAME, "register", "POC-WS-ERR-1005", email);
            return generateResponse(Response.Status.CONFLICT,
                    POCLogger.getMessageProperty("POC-WS-ERR-1005"));
        }

        if (!doesAccountExist(username)) {
            String regresponse = SKFSClient.register(username, getOrigin(), input);
            //On success, add user to database
            userdatabase.addUser(email, username, firstName, lastName);

            //Remove registration request from DB
            registrationDB.deleteRegistration(email);
            session.removeAttribute(Constants.SESSION_FIRSTNAME);
            session.removeAttribute(Constants.SESSION_LASTNAME);
            session.removeAttribute(Constants.SESSION_EMAIL);

            session.setAttribute(Constants.SESSION_USERNAME, username);
            session.setAttribute(Constants.SESSION_ISAUTHENTICATED, true);
            session.setMaxInactiveInterval(Constants.SESSION_TIMEOUT_VALUE);
            System.out.println("Received from FIDO Server: " + regresponse);
            return generateResponse(Response.Status.OK, getResponseFromSKFSResponse(regresponse));
        } else {
            //If the user already exists, throw an error
            POCLogger.logp(Level.SEVERE, CLASSNAME, "register", "POC-WS-ERR-1001", username);
            return generateResponse(Response.Status.CONFLICT, POCLogger.getMessageProperty("POC-WS-ERR-1001"));
        }
    }
    catch (Exception ex) {
        ex.printStackTrace();
        POCLogger.logp(Level.SEVERE, CLASSNAME, "register", "POC-WS-ERR-1000", ex.getLocalizedMessage());
        return generateResponse(Response.Status.INTERNAL_SERVER_ERROR,
                POCLogger.getMessageProperty("POC-WS-ERR-1000"));
    }
}
 
Example 20
Source File: SessionServiceImpl.java    From onboard with Apache License 2.0 4 votes vote down vote up
public void removeUserInformation() {
    HttpSession httpSession = globalService.getSession();
    httpSession.removeAttribute(CURRENT_USER);
    httpSession.removeAttribute(CURRENT_COMPANY);
    httpSession.removeAttribute(CURRENT_PROJECT);
}