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

The following examples show how to use javax.servlet.http.HttpSession#getAttribute() . 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: MemberController.java    From product-recommendation-system with MIT License 6 votes vote down vote up
/**
 * 修改商城会员密码 
 * @param oldPsd 旧密码
 * @param newPsd 新密码
 * @param confirmPsd 确认的新密码
 * @return
 */
@RequestMapping(value="/updatePassword")
public @ResponseBody Map<String, Object> updatePassword(String oldPsd, String newPsd,
	String confirmPsd, HttpSession session) {
	
	Map<String, Object> message = new HashMap<String, Object>();
	message.put(FRONT_TIPS_ATTR, UPDATE_PASSWORD_FAILED);
	
	// 1.确定密码是否为空
	if (StringUtils.isEmpty(oldPsd) || StringUtils.isEmpty(newPsd) || 
		StringUtils.isEmpty(confirmPsd)) {
		return message; 
	}
	
	// 2.更新商城会员密码,获取当前商城会员id
	Member member = (Member) session.getAttribute(LoginMemberController.SESSION_MEMBER_ATTR);
	Long memberId = member.getId();
	boolean flag = this.memberService.updatePassword(memberId, oldPsd, newPsd, confirmPsd);
	
	if (flag) {
		message.put(FRONT_TIPS_ATTR, UPDATE_PASSWORD_SUCCESS);
	}
	
	return message;
}
 
Example 2
Source File: DataAnalysisController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@RequestMapping( value = "validationRules/report.csv", method = RequestMethod.GET )
public void getValidationRulesCSVReport( HttpSession session, HttpServletResponse response )
    throws Exception
{
    @SuppressWarnings( "unchecked" )
    List<ValidationResult> results = (List<ValidationResult>) session.getAttribute( KEY_VALIDATION_RESULT );
    Grid grid = generateValidationRulesReportGridFromResults( results, (OrganisationUnit) session.getAttribute(
        KEY_ORG_UNIT )
    );

    String filename = filenameEncode( grid.getTitle() ) + ".csv";
    contextUtils
        .configureResponse( response, ContextUtils.CONTENT_TYPE_CSV, CacheStrategy.RESPECT_SYSTEM_SETTING, filename,
            false );

    GridUtils.toCsv( grid, response.getWriter() );
}
 
Example 3
Source File: Cmm1100Controller.java    From oslits with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Prj1000 조회버튼 클릭시 프로젝트 생성관리 조회 AJAX
 * @param 
 * @return 
 * @exception Exception
 */
   @SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(value="/cmm/cmm1000/cmm1100/selectCmm1100ViewAjax.do")
   public ModelAndView selectCmm1100ViewAjax(HttpServletRequest request, HttpServletResponse response, ModelMap model ) throws Exception {
   	try{
   		

   		//리퀘스트에서 넘어온 파라미터를 맵으로 세팅
   		Map<String, String> paramMap = RequestConvertor.requestParamToMap(request, true);
   		
   		//로그인VO 가져오기
   		HttpSession ss = request.getSession();
   		LoginVO loginVO = (LoginVO) ss.getAttribute("loginVO");

   		if(paramMap.get("selectSearch") == null){
   			paramMap.put("selectSearch", "");
   		}
   		
   		paramMap.put("usrId", loginVO.getUsrId());
   		
       	//프로젝트 생성관리 목록 가져오기
       	List<Map> selectCmm1100List = (List) cmm1100Service.selectCmm1100View(paramMap);

       	model.put("list", selectCmm1100List);
       	
       	//조회성공메시지 세팅
       	model.addAttribute("message", egovMessageSource.getMessage("success.common.select"));
       	
       	

       	return new ModelAndView("jsonView", model);
   	}
   	catch(Exception ex){
   		Log.error("selectCmm1100ViewAjax()", ex);
   		model.addAttribute("message", egovMessageSource.getMessage("fail.common.select"));
   		throw new Exception(ex.getMessage());
   	}
   }
 
Example 4
Source File: CookieBasedAuthenticationHandler.java    From product-private-paas with Apache License 2.0 5 votes vote down vote up
private boolean isUserLoggedIn(HttpSession httpSession) {
    String userName = (String) httpSession.getAttribute("userName");
    String tenantDomain = (String) httpSession.getAttribute("tenantDomain");
    Integer tenantId = (Integer) httpSession.getAttribute("tenantId");
    if (userName != null && tenantDomain != null && tenantId != null) {
        return true;
    }
    return false;
}
 
Example 5
Source File: UserSession.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Return the UserSession of the given request if it is already set or null otherwise
 * 
 * @param hreq
 * @return
 */
public static UserSession getUserSessionIfAlreadySet(HttpServletRequest hreq) {
    HttpSession session = hreq.getSession(false);
    if (session == null) {
        return null;
    }
    session.setMaxInactiveInterval(UserSession.sessionTimeoutInSec);
    synchronized (session) {// o_clusterOK by:se
        return (UserSession) session.getAttribute(USERSESSIONKEY);
    }
}
 
Example 6
Source File: CrossContextServletSessionTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    HttpSession session = req.getSession();
    Integer value = (Integer)session.getAttribute("key");
    if(value == null) {
        value = 1;
    }
    session.setAttribute("key", value + 1);
    req.getServletContext().getContext(req.getParameter("context")).getRequestDispatcher(req.getParameter("path")).forward(req, resp);
}
 
Example 7
Source File: IndexController.java    From pybbs with GNU Affero General Public License v3.0 5 votes vote down vote up
@GetMapping("/settings")
public String settings(HttpSession session, Model model) {
    // 再查一遍,保证数据的最新
    User user = (User) session.getAttribute("_user");
    user = userService.selectById(user.getId());
    model.addAttribute("user", user);
    return render("user/settings");
}
 
Example 8
Source File: GreeterSessionImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public String greetMe(String me) {
    LOG.info("Executing operation greetMe");
    LOG.info("Message received: " + me);
    MessageContext mc = context.getMessageContext();
    HttpServletRequest req = (HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST);
    Cookie[] cookies = req.getCookies();
    String val = "";
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            val += ";" + cookie.getName() + "=" + cookie.getValue();
        }
    }


    HttpSession session = req.getSession();
    // Get a session property "counter" from context
    if (session == null) {
        throw new WebServiceException("No session in WebServiceContext");
    }
    String name = (String)session.getAttribute("name");
    if (name == null) {
        name = me;
        LOG.info("Starting the Session");
    }

    session.setAttribute("name", me);

    return "Hello " + name + val;
}
 
Example 9
Source File: AuthenticationFilter.java    From authmore-framework with Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    HttpSession session = request.getSession(true);
    UserDetails user = (UserDetails) session.getAttribute(SessionProperties.CURRENT_USER_DETAILS);
    if (null == user) {
        redirectToSignin(request, response);
        return;
    }

    filterChain.doFilter(request, response);
}
 
Example 10
Source File: KeycloakDropwizardAuthenticator.java    From keycloak-dropwizard-integration with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory)
        throws ServerAuthException {
    HttpServletRequest request = ((HttpServletRequest) req);
    request.setAttribute(HttpServletRequest.class.getName(), request);
    if (!getAdapterConfig().isBearerOnly()
            && request.getQueryString() != null
            && request.getQueryString().contains("code=")) {
        // we receive a code as part of the query string that is returned by OAuth
        // but only assume control is this is not bearer only!
        mandatory = true;
    } else if (request.getHeaders("Authorization").hasMoreElements()) {
        // we receive Authorization, might be Bearer or Basic Auth (both supported by Keycloak)
        mandatory = true;
    }
    HttpSession session = ((HttpServletRequest) req).getSession(false);
    if (session != null && session.getAttribute(JettyAdapterSessionStore.CACHED_FORM_PARAMETERS) != null) {
        // this is a redirect after the code has been received for a FORM
        mandatory = true;
    } else if (session != null && session.getAttribute(KeycloakSecurityContext.class.getName()) != null) {
        // there is an existing authentication in the session, use it
        mandatory = true;
    }
    Authentication authentication = super.validateRequest(req, res, mandatory);
    if (authentication instanceof DeferredAuthentication) {
        // resolving of a deferred authentication later will otherwise lead to a NullPointerException
        authentication = null;
    }
    return authentication;
}
 
Example 11
Source File: SessionCodeService.java    From oauth-boot with MIT License 5 votes vote down vote up
@Override
public String getCodeValue(String key){
    HttpSession session = this.getSession();
    if (session==null){
        log.error("当前请求获取不到Session");
        return null;
    }
    return  (String)session.getAttribute(key);
}
 
Example 12
Source File: CategoryManageController.java    From MMall_JAVA with GNU General Public License v3.0 5 votes vote down vote up
@RequestMapping("get_deep_category.do")
    public ServerResponse getCategoryAndDeepChildrenCategory(HttpSession session, @RequestParam(value = "categoryId", defaultValue = "0") Integer categoryId) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
        }
        if (iUserService.checkAdminRole(user).isSuccess()) {
            //查询当前节点的id和递归子节点的id
//            0->10000->100000
            return iCategoryService.selectCategoryAndChildrenById(categoryId);

        } else {
            return ServerResponse.createByErrorMessage("无权限操作,需要管理员权限");
        }
    }
 
Example 13
Source File: LearningController.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private McQueUsr getCurrentUser(String toolSessionId) {

	// get back login user DTO
	HttpSession ss = SessionManager.getSession();
	UserDTO toolUser = (UserDTO) ss.getAttribute(AttributeNames.USER);
	Long userId = new Long(toolUser.getUserID().longValue());

	McSession mcSession = mcService.getMcSessionById(new Long(toolSessionId));
	McQueUsr qaUser = mcService.getMcUserBySession(userId, mcSession.getUid());
	if (qaUser == null) {
	    qaUser = mcService.createMcUser(new Long(toolSessionId));
	}

	return mcService.getMcUserBySession(userId, mcSession.getUid());
    }
 
Example 14
Source File: AdminController.java    From MOOC with MIT License 5 votes vote down vote up
@RequestMapping(value="logoutadmin")//管理员注销
public String logoutadmin(HttpSession session,HttpServletRequest req){
	User loginUser = (User) session.getAttribute("loginUser");
	session.invalidate();
	setlog(loginUser, req.getRemoteAddr(),"注销", loginUser.getUsername());
	return "loginadmin";
}
 
Example 15
Source File: Prj2000Controller.java    From oslits with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Prj2000 권한정보 삭제(단건) AJAX
 * 권한정보 삭제 처리
 * @param 
 * @return 
 * @exception Exception
 */
@RequestMapping(value="/prj/prj2000/prj2000/deletePrj2000AuthGrpInfoAjax.do")
   public ModelAndView deletePrj2000AuthGrpInfoAjax(HttpServletRequest request, HttpServletResponse response, ModelMap model ) throws Exception {
   	
   	try{
       	
   		// request 파라미터를 map으로 변환
       	Map<String, String> paramMap = RequestConvertor.requestParamToMapAddSelInfo(request, true);
       	HttpSession ss = request.getSession();
      		LoginVO loginVO = (LoginVO) ss.getAttribute("loginVO");
          	paramMap.put("licGrpId", loginVO.getLicGrpId());
          	
       	// 메뉴 삭제
       	prj2000Service.deletePrj2000AuthGrpInfoAjax(paramMap);
       	
       	//등록 성공 메시지 세팅
       	model.addAttribute("message", egovMessageSource.getMessage("success.common.delete"));
       	
       	return new ModelAndView("jsonView");
   	}
   	catch(Exception ex){
   		Log.error("deletePrj2000AuthGrpInfoAjax()", ex);

   		//삭제실패 메시지 세팅 및 저장 성공여부 세팅
   		model.addAttribute("saveYN", "N");
   		model.addAttribute("message", egovMessageSource.getMessage("fail.common.delete"));
   		return new ModelAndView("jsonView");
   	}
   }
 
Example 16
Source File: SetupWizardSessionCache.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Retrieve subscriptions from cache for the given credentials.
 * @param creds credentials
 * @param request request
 * @return list of subscriptions
 */
@SuppressWarnings("unchecked")
public static List<SubscriptionDto> getSubscriptions(MirrorCredentialsDto creds,
        HttpServletRequest request) {
    List<SubscriptionDto> ret = null;
    HttpSession session = request.getSession();
    Map<String, List<SubscriptionDto>> subsMap =
            (Map<String, List<SubscriptionDto>>) session
                    .getAttribute(SUBSCRIPTIONS_KEY);
    if (subsMap != null) {
        ret = subsMap.get(creds.getUser());
    }
    return ret;
}
 
Example 17
Source File: UserServlet.java    From mytwitter with Apache License 2.0 4 votes vote down vote up
private void signUp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	HttpSession session = request.getSession();

	String name = (String) session.getAttribute("name");
	String uname = (String) session.getAttribute("uname");
	String pwd = (String) session.getAttribute("pwd");
	String aite = request.getParameter("aite");
	Timestamp utime = Times.getSystemTime();

	int n = usersDao.addUser(uname, pwd, name, aite, utime);
	if (n > 0) {
		ServletContext application = session.getServletContext();
		Integer zhuceNum = (Integer) application.getAttribute("zhuceNum");
		if (zhuceNum == null) {
			zhuceNum = 1;
		} else {
			zhuceNum += 1;
		}
		application.setAttribute("newTweetNum", zhuceNum);
		Users user = usersDao.checkLogin(uname, pwd);

		int m = usersinfoDao.addUserinfo(user.getUid());
		if (m > 0) {
			Usersinfo info = usersinfoDao.getInfos(user.getUid());

			String folder = request.getSession().getServletContext().getRealPath("/img/" + user.getUname());
			String img = request.getSession().getServletContext().getRealPath("/img");
			File file = new File(folder);
			file.mkdir();

			InputStream is = new FileInputStream(img + "/" + info.getUlogo());
			OutputStream os = new FileOutputStream(folder + "/" + info.getUlogo(), true);
			byte[] b = new byte[1024];
			int a = is.read(b); // 实际读到的文件的长度

			while (a > 0) {
				os.write(b, 0, a);
				a = is.read(b);
			}

			os.close();
			is.close();

			session.setAttribute("info", info);
			session.setAttribute("user", user);
			response.sendRedirect("start.jsp");
		}
	}

}
 
Example 18
Source File: LoginInterceptor.java    From disconf with Apache License 2.0 4 votes vote down vote up
/**
 * 采用两级缓存。先访问session,<br/>
 * 如果存在,则直接使用,并更新 threadlocal <br/>
 * 如果不存在,则访问 redis,<br/>
 * 如果redis存在,则更新session和threadlocal<br/>
 * 如果redis也不存在,则认为没有登录
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

    //
    // 去掉不需拦截的path
    //
    String requestPath = request.getRequestURI();

    // 显示所有用户的请求
    LOG.info(request.getRequestURI());

    if (notInterceptPathList != null) {

        // 更精确的定位
        for (String path : notInterceptPathList) {
            if (requestPath.contains(path)) {
                return true;
            }
        }
    }

    /**
     * 种植Cookie
     */
    plantCookie(request, response);

    /**
     * 登录与否判断
     */

    //
    // 判断session中是否有visitor
    //
    HttpSession session = request.getSession();
    Visitor visitor = (Visitor) session.getAttribute(UserConstant.USER_KEY);

    //
    // session中没有该信息,则从 redis上获取,并更新session的数据
    //
    if (visitor == null) {

        Visitor redisVisitor = redisLogin.isLogin(request);

        //
        // 有登录信息
        //
        if (redisVisitor != null) {

            // 更新session中的登录信息
            redisLogin.updateSessionVisitor(session, redisVisitor);

        } else {

            // 还是没有登录
            returnJsonSystemError(request, response, "login.error", ErrorCode.LOGIN_ERROR);
            return false;
        }
    } else {

        // 每次都更新session中的登录信息
        redisLogin.updateSessionVisitor(session, visitor);
    }

    return true;
}
 
Example 19
Source File: OutcomeService.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private static UserDTO getUserDTO() {
HttpSession ss = SessionManager.getSession();
return (UserDTO) ss.getAttribute(AttributeNames.USER);
   }
 
Example 20
Source File: Stm1100Controller.java    From oslits with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Stm1100 프로젝트에 API를 등록/삭제한다.
 * @param request
 * @param response
 * @param model
 * @return
 * @throws Exception
 */
@RequestMapping(value="/stm/stm1000/stm1100/saveStm1100Ajax.do")
   public ModelAndView saveStm1100Ajax(HttpServletRequest request, HttpServletResponse response, ModelMap model ) throws Exception {
   	try{
   		// request 파라미터를 map으로 변환
       	Map<String, String> paramMap = RequestConvertor.requestParamToMap(request, true);
       	
       	HttpSession ss = request.getSession();
   		LoginVO loginVO = (LoginVO) ss.getAttribute("loginVO");

   	
       	String[] apiIds =  request.getParameterValues("apiId");
       	String[] isCheckeds =  request.getParameterValues("isChecked");
       	String[] orgCheckeds =  request.getParameterValues("orgChecked");
       	
       	List<Stm1100VO> list = new ArrayList<Stm1100VO>();
       	
       	Stm1100VO stm1100VO =null;
       	
       	for (int i = 0; i < apiIds.length; i++) {
       		stm1100VO  = new Stm1100VO();
       		
       		stm1100VO.setPrjId(paramMap.get("prjId"));
       		stm1100VO.setApiId(apiIds[i]);
       		stm1100VO.setIsChecked( isCheckeds[i]  );
       		stm1100VO.setOrgChecked(orgCheckeds[i]);
       		
       		stm1100VO.setRegUsrId(paramMap.get("regUsrId"));
       		stm1100VO.setRegUsrIp(paramMap.get("regUsrIp"));
       		
       		stm1100VO.setLicGrpId(loginVO.getLicGrpId());
       		
       		list.add(stm1100VO);
		}
       	
       	// 프로젝트 생성관리 수정
       	stm1100Service.saveStm1100(list);
       	
       	model.put("prjId", paramMap.get("prjId"));
     
       	// 등록/삭제 메시지 세팅
       	model.addAttribute("message", egovMessageSource.getMessage("success.common.save"));
       	
       	return new ModelAndView("jsonView", model);
   	}
   	catch(Exception ex){
   		Log.error("saveStm1100Ajax()", ex);
   		// 등록/삭제 실패메시지 세팅
   		model.addAttribute("message", egovMessageSource.getMessage("fail.common.save"));
   		return new ModelAndView("jsonView");
   	}
   }