当前位置: 首页>>代码示例>>Java>>正文


Java HttpSession.setAttribute方法代码示例

本文整理汇总了Java中javax.servlet.http.HttpSession.setAttribute方法的典型用法代码示例。如果您正苦于以下问题:Java HttpSession.setAttribute方法的具体用法?Java HttpSession.setAttribute怎么用?Java HttpSession.setAttribute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在javax.servlet.http.HttpSession的用法示例。


在下文中一共展示了HttpSession.setAttribute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: isSessionExpired

import javax.servlet.http.HttpSession; //导入方法依赖的package包/类
public void isSessionExpired ( HttpSession session ) {
	// Hook for checking for expired SSO cookie.
	if ( session.getAttribute( "renew" ) == null ) {
		session.setAttribute( "renew", System.currentTimeMillis() );
		// logger.info("session.getAttribute(ServiceRequests.PROGRESS_BUFF"
		// + session.getAttribute(ServiceRequests.PROGRESS_BUFF) ) ;
		if ( session.getAttribute( SESSION_EXPIRED ) == null ) {
			session.setAttribute( SESSION_EXPIRED, new StringBuffer() );
		}
	}
	// logger.debug("\n\n ******** session.getAttribute(renew)" +
	// session.getAttribute("renew") + " current: " +
	// System.currentTimeMillis() ) ;
	// hook for expiring sessions. We force SSO validation every hour,
	// but never interupting t
	if ( ((StringBuffer) session.getAttribute( SESSION_EXPIRED )).length() == 0
			&& System.currentTimeMillis() - ((long) session.getAttribute( "renew" )) > 60 * 60 * 1000 ) {
		// 60*60*1000
		// logger.warn("\n\n **************** Forcing session renew
		// *****************")
		// ;
		session.invalidate();
	}
}
 
开发者ID:csap-platform,项目名称:csap-core,代码行数:25,代码来源:ServiceRequests.java

示例2: updateInformation

import javax.servlet.http.HttpSession; //导入方法依赖的package包/类
/**
 * 更新信息接口
 * @param session
 * @param user
 * @return
 */
@RequestMapping(value = "updateInformation.do", method = RequestMethod.POST)
@ResponseBody
public ServerResponse<User> updateInformation(HttpSession session,User user){
    User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
    if (currentUser == null){
        return ServerResponse.createByError("用户未登录");
    }
    //设置userId-->因为传过来的userId是为null的;为什么????
    user.setId(currentUser.getId());
    user.setUsername(currentUser.getUsername());
    ServerResponse<User> userServerResponse = iUserService.updateInformation(user);
    if (userServerResponse.isSuccess()){
        session.setAttribute(Const.CURRENT_USER,userServerResponse.getData());
    }
    return userServerResponse;
}
 
开发者ID:wangshufu,项目名称:mmall,代码行数:23,代码来源:UserController.java

示例3: doFilter

import javax.servlet.http.HttpSession; //导入方法依赖的package包/类
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest) req;
	HttpServletResponse response = (HttpServletResponse) res;
	HttpSession session = request.getSession();
	
	// 已经登录,放行
	if (session.getAttribute(AuthConst.IS_LOGIN) != null) {
		chain.doFilter(req, res);
		return;
	}
	// 从认证中心回跳的带有token的请求,有效则放行
	String token = request.getParameter(AuthConst.TOKEN);
	if (token != null) {
		session.setAttribute(AuthConst.IS_LOGIN, true);
		session.setAttribute(AuthConst.TOKEN, token);
		// 存储,用于注销
		SessionStorage.INSTANCE.set(token, session);
		chain.doFilter(req, res);
		return;
	}

	// 重定向至登录页面,并附带当前请求地址
	response.sendRedirect(config.getInitParameter(AuthConst.LOGIN_URL) + "?" + AuthConst.CLIENT_URL + "=" + request.getRequestURL());
}
 
开发者ID:sheefee,项目名称:simple-sso,代码行数:26,代码来源:LoginFilter.java

示例4: homeinit

import javax.servlet.http.HttpSession; //导入方法依赖的package包/类
@RequestMapping(value="homeinit.do", method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView homeinit(HttpServletRequest request) {
	ModelAndView modelAndView = new ModelAndView();
	HttpSession session = request.getSession();
	
	//获取用户数量,租房数量,楼盘数量,租房成交数量
	List<User> userList = userService.selectAllUser();
	session.setAttribute("userListSize", userList.size());
	
	List<BuildingDeal> buildingDealList = buildingDealDao.selectAll();
	session.setAttribute("buildingDealListSize", buildingDealList.size());
	
	List<RentHouseDeal> rentHouseDealList = rentHouseDealDao.selectAll();
	session.setAttribute("rentHouseDealListSize", rentHouseDealList.size());
	
	List<RentHouse> rentHouseList = rentHouseDao.selectAllRentHouse();
	session.setAttribute("rentHouseListSize", rentHouseList.size());
	
	modelAndView.setViewName("SystemUser/home");
	return modelAndView;
}
 
开发者ID:632team,项目名称:EasyHousing,代码行数:22,代码来源:AdminInit.java

示例5: comprar

import javax.servlet.http.HttpSession; //导入方法依赖的package包/类
@RequestMapping(value = "/FinalizarCompraSegura")
public String comprar(Model model, @Valid Pedido pedido, HttpSession session, BindingResult result) {
	
	Cliente cliente = (Cliente) session.getAttribute("clienteLogado");
	Carrinho carrinho = (Carrinho) session.getAttribute("carrinho");
	
	// Gerar numero randomico
	int min = 100000000;//na vdd s�o 14 campos
	int max = 999999999;
	int numb_ped = ThreadLocalRandom.current().nextInt(min, max + 1);
	
	pedido.setNumero_ped(numb_ped);
	
	if(result.hasErrors()) {
	    return "forward:forma_de_pagamento";
	} else {
		carrinho.removeAll();
		session.setAttribute("carrinho", carrinho);
		Long id = dao.create(pedido, carrinho, cliente);
		return "redirect:boleto/"+id;
	}
}
 
开发者ID:iurigodoy,项目名称:Monsters_Portal,代码行数:23,代码来源:ComprarController.java

示例6: doPost

import javax.servlet.http.HttpSession; //导入方法依赖的package包/类
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		HttpSession session = request.getSession();

            Candidates candidate = CandidatePersistence.getCandidateByID(Integer.parseInt(request.getParameter("candidateID")));

            if (candidate != null) {
                candidate.setApproved("Yes");
                try {
                    CandidatePersistence.merge(candidate);
                    List<Candidates> approvalList = CandidatePersistence.getApprovalList();
                    List<Candidates> listCandidates = CandidatePersistence.getAll();
                    session.setAttribute("listCandidates", listCandidates);
                    session.setAttribute("approvalList", approvalList);
                    response.sendRedirect("admin/admin-approve.jsp");
                } catch (Exception e) {
                    e.printStackTrace();
                    response.sendRedirect("admin/admin-approve.jsp");
                }
            } else {
                response.sendRedirect("admin/admin-approve.jsp");
            }

	}
 
开发者ID:faizan-ali,项目名称:full-javaee-app,代码行数:25,代码来源:AdministratorApproveCandidateServlet.java

示例7: doValidateAccount

import javax.servlet.http.HttpSession; //导入方法依赖的package包/类
private boolean doValidateAccount(HttpSession session, IUser user, String ticket)
{
	try
	{
		if(user != null && user.getAccount().length() > 0 && !"null".equals(user.getAccount()))
		{
			session.setAttribute(LOGINER, user);
			session.setAttribute(TICKET, ticket);
			if(log.isDebugEnabled())
			{
				log.debug("sameDomain=" + (sameDomain) + ", account=" + user.getAccount() + ", ticket=" + ticket);
			}
			return true;
		}
	}
	catch(Exception e)
	{
		log.error(e.getMessage());
	}
	logout(session);
	return false;
}
 
开发者ID:skeychen,项目名称:dswork,代码行数:23,代码来源:WebFilter.java

示例8: login

import javax.servlet.http.HttpSession; //导入方法依赖的package包/类
/**
 * Logins the specified user from the specified request.
 * 
 * <p>
 * If no session of the specified request, do nothing.
 * </p>
 *
 * @param request
 *            the specified request
 * @param response
 *            the specified response
 * @param user
 *            the specified user, for example,
 * 
 *            <pre>
 * {
 *     "userEmail": "",
 *     "userPassword": ""
 * }
 *            </pre>
 */
public static void login(final HttpServletRequest request, final HttpServletResponse response,
		final JSONObject user) {
	final HttpSession session = request.getSession();

	if (null == session) {
		logger.warn("The session is null");
		return;
	}

	session.setAttribute(User.USER, user);

	try {
		final JSONObject cookieJSONObject = new JSONObject();

		cookieJSONObject.put(User.USER_EMAIL, user.optString(User.USER_EMAIL));
		cookieJSONObject.put(User.USER_PASSWORD, user.optString(User.USER_PASSWORD));

		final Cookie cookie = new Cookie("b3log-latke", cookieJSONObject.toString());

		cookie.setPath("/");
		cookie.setMaxAge(COOKIE_EXPIRY);

		response.addCookie(cookie);
	} catch (final Exception e) {
		logger.warn("Can not write cookie", e);
	}
}
 
开发者ID:daima,项目名称:solo-spring,代码行数:49,代码来源:Sessions.java

示例9: update_information

import javax.servlet.http.HttpSession; //导入方法依赖的package包/类
@RequestMapping(value = "update_information.do",method = RequestMethod.POST)
public ServerResponse<User> update_information(HttpSession session,User user){
    User currentUser = (User)session.getAttribute(Const.CURRENT_USER);
    if(currentUser == null){
        return ServerResponse.createByErrorMessage("用户未登录");
    }
    user.setId(currentUser.getId());
    user.setUsername(currentUser.getUsername());
    ServerResponse<User> response = iUserService.updateInformation(user);
    if(response.isSuccess()){
        response.getData().setUsername(currentUser.getUsername());
        session.setAttribute(Const.CURRENT_USER,response.getData());
    }
    return response;
}
 
开发者ID:Liweimin0512,项目名称:MMall_JAVA,代码行数:16,代码来源:UserController.java

示例10: loginDao

import javax.servlet.http.HttpSession; //导入方法依赖的package包/类
protected String loginDao(String email, String senha, HttpSession session,
		Model model, String paginaSucesso, String paginaErro){
	
	Cliente autenticacao = (Cliente) dao_cli.autenticaEmailSenha(email, senha);	// Faz autentica��o do cliente pelo email e senha e retorna com todos os dados
	if(autenticacao != null) {													// Checa se n�o veio nula
		session.setAttribute("clienteLogado", autenticacao);					// Armazena os dados na sessão
		return "redirect:"+paginaSucesso;										// Redireciona para a página
	}
	model.addAttribute("login_error", "Usuário ou senha incorretos");			// Mensagem de erro
	return "redirect:"+paginaErro;												// redireciona de volta para a página
}
 
开发者ID:iurigodoy,项目名称:Monsters_Portal,代码行数:12,代码来源:Identificacao.java

示例11: setAttribute

import javax.servlet.http.HttpSession; //导入方法依赖的package包/类
@Override
public void setAttribute(String name, Object value, int scope) {
	if (scope == SCOPE_REQUEST) {
		if (!isRequestActive()) {
			throw new IllegalStateException(
					"Cannot set request attribute - request is not active anymore!");
		}
		this.request.setAttribute(name, value);
	}
	else {
		HttpSession session = getSession(true);
		this.sessionAttributesToUpdate.remove(name);
		session.setAttribute(name, value);
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:16,代码来源:ServletRequestAttributes.java

示例12: doFilter

import javax.servlet.http.HttpSession; //导入方法依赖的package包/类
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {

	HttpSession session = ((HttpServletRequest) request).getSession();

	if (session.getAttribute("user") == null) {
		session.setAttribute("error",
				"You have been logged out due to inactivity or invalid authentication. Please login again.");
		((HttpServletResponse) response).sendRedirect("team.jsp");
	} else {
		chain.doFilter(request, response);
	}

}
 
开发者ID:faizan-ali,项目名称:full-javaee-app,代码行数:15,代码来源:AdministratorAuthenticationFilter.java

示例13: doPost

import javax.servlet.http.HttpSession; //导入方法依赖的package包/类
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //Instância Objeto Fornecedor
    Usuario u = new Usuario();
    
    //Instância de ArrayList para acumular fornecedores
    ArrayList<Usuario> Lista = new ArrayList();
    
    //Instância serviço de servidor para efetuar consulta e ligação com FornecedorDAO
    ServicoUsuario su = new ServicoUsuario();
    
    //Criação se sessão para retorno em tela
    HttpSession sessao = request.getSession();
    
    //Atribuição de valores digitados na tela de fornecedor e código da empresa
    String usuario = request.getParameter("usuarios").toLowerCase();
    String codigoempresa = (String) sessao.getAttribute("Empresa");
    
    try {
        Lista = (ArrayList<Usuario>) su.listarUsuarios(usuario, Integer.parseInt(codigoempresa));
    } catch (Exception e) {
    }
    
    sessao.setAttribute("listaUsuario", Lista);
    response.sendRedirect(request.getContextPath() + "/consultarUsuario.jsp");   
    
}
 
开发者ID:Dinossaura,项目名称:LojaDeInstrumentosMusicais,代码行数:29,代码来源:ConsultaUsuariosTotaisServlet.java

示例14: index

import javax.servlet.http.HttpSession; //导入方法依赖的package包/类
/**
 * 官网首页数据展示
 *
 * @return
 */
@GetMapping("/index")
public String index(HttpServletRequest request, Model model, HttpSession session) {

    Integer newpv = (Integer) session.getAttribute("is_new");
    if (newpv == null) {
        TzPv pv = new TzPv();
        pv.setUserip(Utils.getIpAddress(request));
        pv.setUseragent(request.getHeader("User-Agent"));
        pv.setVisittime(new Timestamp(System.currentTimeMillis()));
        pv.setModule(3);
        this.tzPvService.insert(pv);
        session.setAttribute("is_new", 1);
    }

    //获取导航菜单资源
    List<OfficialResouce> menus = officialResouceService.findResourceByCid(1, 0, 4);
    //轮播图获取
    List<OfficialResouce> carousels = officialResouceService.findResourceByCid(2, 0, 4);
    //公司展示图片获取
    List<OfficialResouce> companyPic = officialResouceService.findResourceByCid(3, 0, 3);
    //新闻中心截图获取
    List<OfficalNews> news = officalNewsService.findNewsByCid(13, 0, 5);
    //视频
    List<OfficalNews> videos = officalNewsService.findNewsByCid(14, 0, 6);

    List<OfficalNews> notices = officalNewsService.findNewsByCid(15, 0, 3);

    List<OfficialResouce> lovePics = officialResouceService.findResourceByCid(10, 0, 6);

    session.setAttribute("menu", menus);
    model.addAttribute("carousels", carousels);
    model.addAttribute("companyPic", companyPic);
    model.addAttribute("lovePics", lovePics);
    model.addAttribute("videos", videos);
    model.addAttribute("news", news);
    model.addAttribute("notices", notices);
    return "index";
}
 
开发者ID:TZClub,项目名称:OMIPlatform,代码行数:44,代码来源:OfficialResouceController.java

示例15: doGet

import javax.servlet.http.HttpSession; //导入方法依赖的package包/类
protected void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	HttpSession session = request.getSession();
	Candidates candidate = new Candidates();

	// Retrieves candidateID of candidate who's profile needs to be
	// displayed
	int candidateID = Integer.parseInt(request.getParameter("candidateID"));

	// Creates EntityManager to query database
	EntityManager em = EMFUtil.getEMFactory().createEntityManager();
	EntityTransaction trans = em.getTransaction();

	// Retrieves user from database based on userID
	candidate = em.find(Candidates.class, candidateID);

	session.setAttribute("candidate", candidate);
	session.setAttribute("candidateID", candidateID);

	// For logging activity
	SchoolLoginLogs loginLog = (SchoolLoginLogs) session.getAttribute("loginLog");
	SchoolActivityLogs activityLog = new SchoolActivityLogs();
	activityLog.setSchoolLoginLogID(loginLog.getSchoolLoginLogID());
	activityLog.setLoginLog(loginLog);
	activityLog.setTime(Clock.getCurrentTime());
	activityLog.setCandidateID(candidateID);
	activityLog.setCandidate(candidate);
	activityLog.setSchoolActivity("Viewed Profile");

	try {
		trans.begin();
		em.persist(activityLog);
		trans.commit();
		session.setAttribute("loginLog", loginLog);
	} catch (Exception e) {
		trans.rollback();
		e.printStackTrace();
	} finally {
		em.close();
		response.sendRedirect("schools/school-candidate-profile.jsp");
	}
	
}
 
开发者ID:faizan-ali,项目名称:full-javaee-app,代码行数:44,代码来源:SchoolViewCandidateProfileServlet.java


注:本文中的javax.servlet.http.HttpSession.setAttribute方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。