Java Code Examples for javax.servlet.http.HttpSession.setAttribute()

The following are Jave code examples for showing how to use setAttribute() of the javax.servlet.http.HttpSession class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: csap-core   File: ServiceRequests.java   View Source Code Vote up 6 votes
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();
	}
}
 
Example 2
Project: mmall   File: UserController.java   View Source Code Vote up 6 votes
/**
 * 更新信息接口
 * @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;
}
 
Example 3
Project: simple-sso   File: LoginFilter.java   View Source Code Vote up 6 votes
@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());
}
 
Example 4
Project: EasyHousing   File: AdminInit.java   View Source Code Vote up 6 votes
@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;
}
 
Example 5
Project: Monsters_Portal   File: ComprarController.java   View Source Code Vote up 6 votes
@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;
	}
}
 
Example 6
Project: full-javaee-app   File: AdministratorApproveCandidateServlet.java   View Source Code Vote up 6 votes
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");
            }

	}
 
Example 7
Project: dswork   File: WebFilter.java   View Source Code Vote up 6 votes
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;
}
 
Example 8
Project: solo-spring   File: Sessions.java   View Source Code Vote up 6 votes
/**
 * 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);
	}
}
 
Example 9
Project: MMall_JAVA   File: UserController.java   View Source Code Vote up 5 votes
@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;
}
 
Example 10
Project: Monsters_Portal   File: Identificacao.java   View Source Code Vote up 5 votes
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
}
 
Example 11
Project: lams   File: ServletRequestAttributes.java   View Source Code Vote up 5 votes
@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);
	}
}
 
Example 12
Project: full-javaee-app   File: AdministratorAuthenticationFilter.java   View Source Code Vote up 5 votes
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);
	}

}
 
Example 13
Project: LojaDeInstrumentosMusicais   File: ConsultaUsuariosTotaisServlet.java   View Source Code Vote up 5 votes
@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");   
    
}
 
Example 14
Project: OMIPlatform   File: OfficialResouceController.java   View Source Code Vote up 5 votes
/**
 * 官网首页数据展示
 *
 * @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";
}
 
Example 15
Project: full-javaee-app   File: SchoolViewCandidateProfileServlet.java   View Source Code Vote up 4 votes
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");
	}
	
}
 
Example 16
Project: lams   File: LocaleAction.java   View Source Code Vote up 4 votes
/**
 * <p>
 * Change the user's {@link java.util.Locale} based on {@link ActionForm}
 * properties.
 * </p>
 * <p>
 * This <code>Action</code> looks for <code>language</code> and
 * <code>country</code> properties on the given form, constructs an
 * appropriate Locale object, and sets it as the Struts Locale for this
 * user's session.
 * Any <code>ActionForm</code>, including a 
 * {@link org.apache.struts.action.DynaActionForm}, may be used.
 * </p>
 * <p>
 * If a <code>page</code> property is also provided, then after
 * setting the Locale, control is forwarded to that URI path.
 * Otherwise, control is forwarded to "success".
 * </p>
 *
 * @param mapping The ActionMapping used to select this instance
 * @param form The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @return Action to forward to
 * @exception java.lang.Exception if an input/output error or servlet exception occurs
 */
public ActionForward execute(ActionMapping mapping,
             ActionForm form,
             HttpServletRequest request,
             HttpServletResponse response)
throws Exception {

// Extract attributes we will need
HttpSession session = request.getSession();
Locale locale = getLocale(request);

String language = null;
String country = null;
String page = null;

try {
        language = (String)
          PropertyUtils.getSimpleProperty(form, "language");
        country = (String)
          PropertyUtils.getSimpleProperty(form, "country");
        page = (String)
          PropertyUtils.getSimpleProperty(form, "page");
    } catch (Exception e) {
       log.error(e.getMessage(), e);
    }

    boolean isLanguage = (language != null && language.length() > 0);
    boolean isCountry = (country != null && country.length() > 0);

    if ((isLanguage) && (isCountry)) {
       locale = new java.util.Locale(language, country);
    } else if (isLanguage) {
       locale = new java.util.Locale(language, "");
}

    session.setAttribute(Globals.LOCALE_KEY, locale);

    if (null==page) return mapping.findForward("success");
    else return new ActionForward(page);

}
 
Example 17
Project: convertigo-engine   File: AuthenticatedSessionManager.java   View Source Code Vote up 4 votes
public void addAuthenticatedSession(HttpSession httpSession, Role[] roles) {
	httpSession.setAttribute(SessionKey.ADMIN_ROLES.toString(), roles);
	Engine.logAdmin.debug("Added roles " + roles + " to session " + httpSession.getId());
}
 
Example 18
Project: sso   File: SessionCaptchaResultProvider.java   View Source Code Vote up 4 votes
@Override
public void store(HttpSession httpSession, String s) {
    httpSession.setAttribute(CaptchaConstants.STORE_CODE, s);
}
 
Example 19
Project: webpoll   File: LoginSessionManager.java   View Source Code Vote up 4 votes
/**
 * Gets the previously typed username.
 * @return The previously typed username.
 */
public void setTypedUsername(String username){
	HttpSession session = request.getSession();
	
	session.setAttribute(USERNAME_ATTRIBUTE_NAME, username);
}
 
Example 20
Project: zhkuas_ssm_maven   File: MySchemeController.java   View Source Code Vote up 4 votes
@ResponseBody
@RequestMapping(value = "/user/curriculum/scheme", method = RequestMethod.POST)
public Map<String, Object> addScheme(HttpSession session, HttpServletRequest request) {
	if (!SecurityUtil.checkLogin(session)) {
		return WebUtils.webJsonError(Error.LOGIN_OUT_TIME);
	}
	String cNo = request.getParameter("cNo");
	Term term = null;
	String displayValue = request.getParameter("displayValue");
	String formValue = request.getParameter("formValue");
	String schoolTime = request.getParameter("schoolTime");
	Object obj = session.getAttribute("term");
	if (obj != null) {
		term = (Term) obj;
	} else {
		term = termService.getCurrentTerm();
	}
	User user = (User) session.getAttribute(SessionKey.LOGIN_USER.toString());
	int uid = user.getUid();
	MyCourseScheme myCourseScheme = new MyCourseScheme();
	if (cNo != null && displayValue != null && formValue != null && uid != 0) {
		myCourseScheme.setcNo(cNo);
		myCourseScheme.setDisplayValue(displayValue);
		myCourseScheme.setFormValue(formValue);
		myCourseScheme.setTerm(term);
		myCourseScheme.setUid(uid);
		myCourseScheme.setSchoolTime(schoolTime);
		MyCourseScheme findScheme = myCourseSchemeService.findMyCourseScheme(myCourseScheme);
		if (findScheme != null) {
			myCourseScheme.setId(findScheme.getId());
			myCourseScheme.setOrderNum(findScheme.getOrderNum());
			myCourseSchemeService.updateMyCourseScheme(myCourseScheme);
			return WebUtils.webJsonResult("update success");
		}
		myCourseSchemeService.addMyCourseScheme(myCourseScheme);
		List schemes = (List) session.getAttribute(Constants.SessionKey.MYSCHEMES.toString());
		if (schemes != null) {
			schemes.add(myCourseScheme);
			session.setAttribute(Constants.SessionKey.MYSCHEMES.toString(), schemes);
		}
		return WebUtils.webJsonResult("add success");
	}else{
		return WebUtils.webJsonError(Error.FAILURE);
	}

}