javax.servlet.http.HttpSession Java Examples
The following examples show how to use
javax.servlet.http.HttpSession.
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: DemoServlet.java From olingo-odata4 with Apache License 2.0 | 6 votes |
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { HttpSession session = req.getSession(true); Storage storage = (Storage) session.getAttribute(Storage.class.getName()); if (storage == null) { storage = new Storage(); session.setAttribute(Storage.class.getName(), storage); } // create odata handler and configure it with EdmProvider and Processor OData odata = OData.newInstance(); ServiceMetadata edm = odata.createServiceMetadata(new DemoEdmProvider(), new ArrayList<EdmxReference>()); ODataHttpHandler handler = odata.createHandler(edm); handler.register(new DemoEntityCollectionProcessor(storage)); handler.register(new DemoEntityProcessor(storage)); handler.register(new DemoPrimitiveProcessor(storage)); // let the handler do the work handler.process(req, resp); } catch (RuntimeException e) { LOG.error("Server Error occurred in ExampleServlet", e); throw new ServletException(e); } }
Example #2
Source File: MockPageContext.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Override public Enumeration<String> getAttributeNamesInScope(int scope) { switch (scope) { case PAGE_SCOPE: return getAttributeNames(); case REQUEST_SCOPE: return this.request.getAttributeNames(); case SESSION_SCOPE: HttpSession session = this.request.getSession(false); return (session != null ? session.getAttributeNames() : null); case APPLICATION_SCOPE: return this.servletContext.getAttributeNames(); default: throw new IllegalArgumentException("Invalid scope: " + scope); } }
Example #3
Source File: CarController.java From product-recommendation-system with MIT License | 6 votes |
/** * 向购物车添加商品 * @return 购物车页面的视图名称 */ @RequestMapping(value="/addCar", method = RequestMethod.POST) public String addCar(Long pid, Integer count, HttpSession session, Map<String, Object> map) { // 1.首先获得选中的商品 Product product = productService.getProductByProductId(pid); // 2.创建一个购物项,并设置商品的数量,商品的数量,商品的单价 CartItem cartItem = new CartItem(); cartItem.setProduct(product); cartItem.setCount(count); // 注:如果以后要开通优惠券系统,则需要在这里加判断即可 cartItem.setPrice(product.getSalePrice()); // 3.将该商品的信息放入session中 Cart cart = (Cart) session.getAttribute("cart"); if (cart == null) { cart = new Cart(); session.setAttribute("cart", cart); } // 4.将购物项添加进来 cart.addCart(cartItem); return "front/car"; }
Example #4
Source File: ConfigAction.java From Picuang with Apache License 2.0 | 6 votes |
@RequestMapping("/api/admin/import") @ResponseBody public Result importConfig(@PathVariable MultipartFile file, HttpSession session) { Result result = new Result(); try { String filename = file.getOriginalFilename(); // 如果已登录 && 文件不为空 && 是ini文件 if (logged(session) && (!file.isEmpty()) && filename.matches(".*(\\.ini)$")) { File config = new File("config.ini"); config.renameTo(new File("config.ini.backup")); File newConfig = new File(config.getAbsolutePath()); file.transferTo(newConfig); Logger.log(newConfig.getPath()); Prop.reload(); result.setCode(200); } else { result.setCode(500); } } catch (Exception e) { e.printStackTrace(); result.setCode(500); } return result; }
Example #5
Source File: TestExtendedResourceFinderAction.java From entando-components with GNU Lesser General Public License v3.0 | 6 votes |
public void testSearchImageResource_2() throws Throwable { this.executeEdit("ART102", "admin");//Contenuto customers String contentOnSessionMarker = super.extractSessionMarker("ART102", ApsAdminSystemConstants.EDIT); //iniziazione parametri sessione HttpSession session = this.getRequest().getSession(); session.setAttribute(ResourceAttributeActionHelper.ATTRIBUTE_NAME_SESSION_PARAM, "Foto"); session.setAttribute(ResourceAttributeActionHelper.RESOURCE_TYPE_CODE_SESSION_PARAM, "Image"); session.setAttribute(ResourceAttributeActionHelper.RESOURCE_LANG_CODE_SESSION_PARAM, "it"); this.initContentAction("/do/jacms/Content/Resource", "search", contentOnSessionMarker); this.addParameter("resourceTypeCode", "Image");//per replicare il chain in occasione dei chooseResource da edit Contenuto. String result = this.executeAction(); assertEquals(Action.SUCCESS, result); ResourceFinderAction action = (ResourceFinderAction) this.getAction(); assertEquals(3, action.getResources().size()); assertTrue(action.getResources().contains("82")); }
Example #6
Source File: UserController.java From SimpleBBS with Apache License 2.0 | 6 votes |
@ResponseBody @RequestMapping(value = "/register.do", method = RequestMethod.POST) public String register(User user, Invitecode invitecode, @RequestParam(value = "yzm", required = false) String yzm, HttpSession session) { if (user.getUname().length() > 16 || user.getUpwd().length() > 16 || user.getUpwd().length() < 6) { return "注册失败:用户名或密码长度必须小于16位"; } if (session.getAttribute("yzm").equals(yzm.toLowerCase())) { user.setUpwd(DigestUtils.md5DigestAsHex(user.getUpwd().getBytes())); user.setLevel(1); user.setUcreatetime(new Date()); user.setUstate(1); try { userService.register(user, invitecode); return "注册成功"; } catch (MessageException e) { return e.getMessage(); } } else return "验证码错误"; }
Example #7
Source File: CustomAuditEventRepositoryIntTest.java From okta-jhipster-microservices-oauth-example with Apache License 2.0 | 6 votes |
@Test public void testAddEventWithWebAuthenticationDetails() { HttpSession session = new MockHttpSession(null, "test-session-id"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSession(session); request.setRemoteAddr("1.2.3.4"); WebAuthenticationDetails details = new WebAuthenticationDetails(request); Map<String, Object> data = new HashMap<>(); data.put("test-key", details); AuditEvent event = new AuditEvent("test-user", "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(1); PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4"); assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id"); }
Example #8
Source File: SessionMgr.java From ranger with Apache License 2.0 | 6 votes |
public CopyOnWriteArrayList<UserSessionBase> getActiveSessionsOnServer() { CopyOnWriteArrayList<HttpSession> activeHttpUserSessions = RangerHttpSessionListener.getActiveSessionOnServer(); CopyOnWriteArrayList<UserSessionBase> activeRangerUserSessions = new CopyOnWriteArrayList<UserSessionBase>(); if (CollectionUtils.isEmpty(activeHttpUserSessions)) { return activeRangerUserSessions; } for (HttpSession httpSession : activeHttpUserSessions) { if (httpSession.getAttribute(RangerSecurityContextFormationFilter.AKA_SC_SESSION_KEY) == null) { continue; } RangerSecurityContext securityContext = (RangerSecurityContext) httpSession.getAttribute(RangerSecurityContextFormationFilter.AKA_SC_SESSION_KEY); if (securityContext.getUserSession() != null) { activeRangerUserSessions.add(securityContext.getUserSession()); } } return activeRangerUserSessions; }
Example #9
Source File: BrowserDetectionFilter.java From molgenis with GNU Lesser General Public License v3.0 | 6 votes |
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; if (!httpRequest.getRequestURI().startsWith("/api/") && !isSupported(httpRequest.getHeader(USER_AGENT_HEADER_NAME))) { HttpSession session = httpRequest.getSession(); if (session.getAttribute(CONTINUE_WITH_UNSUPPORTED_BROWSER_TOKEN) == null) { if (request.getParameter(CONTINUE_WITH_UNSUPPORTED_BROWSER_TOKEN) != null) { session.setAttribute(CONTINUE_WITH_UNSUPPORTED_BROWSER_TOKEN, true); } else { httpRequest .getRequestDispatcher(UNSUPPORTED_BROWSER_MESSAGE_PAGE) .forward(request, response); return; } } } chain.doFilter(request, response); }
Example #10
Source File: CustomAuditEventRepositoryIntTest.java From e-commerce-microservice with Apache License 2.0 | 6 votes |
@Test public void testAddEventWithWebAuthenticationDetails() { HttpSession session = new MockHttpSession(null, "test-session-id"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSession(session); request.setRemoteAddr("1.2.3.4"); WebAuthenticationDetails details = new WebAuthenticationDetails(request); Map<String, Object> data = new HashMap<>(); data.put("test-key", details); AuditEvent event = new AuditEvent("test-user", "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(1); PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4"); assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id"); }
Example #11
Source File: RecordService.java From JobX with Apache License 2.0 | 6 votes |
public void getPageBean(HttpSession session, PageBean<Record> pageBean,Record record,boolean status) { pageBean.put("record",record); pageBean.put("running",status); pageBean.put("currTime",new Date()); if (!JobXTools.isPermission(session)) { User user = JobXTools.getUser(session); pageBean.put("userId",user.getUserId()); } List<RecordBean> records = recordDao.getByPageBean(pageBean); if (CommonUtils.notEmpty(records)) { int count = recordDao.getCount(pageBean.getFilter()); List<Record> recordList = new ArrayList<Record>(0); for (RecordBean bean:records) { Record item = Record.transfer.apply(bean); List<Record> redoList = getRedoList(bean.getRecordId()); if (CommonUtils.notEmpty(recordList)) { item.setRedoList(redoList); item.setRedoCount(redoList.size()); } recordList.add(item); } pageBean.setResult(recordList); pageBean.setTotalCount(count); } }
Example #12
Source File: AuthServlet.java From incubator-retired-blur with Apache License 2.0 | 6 votes |
private void loginUser(HttpServletRequest request, HttpServletResponse response) throws IOException { Map<String, Object> responseData = new HashMap<String, Object>(); HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); IAuthenticationProvider authenticationProvider = Config.getAuthenticationProvider(); if(user == null) { user = authenticationProvider.login(request); } if (user == null) { responseData.put(LOGIN_STATUS_FIELD, false); String form = authenticationProvider.getLoginForm(); if (form != null) { responseData.put(LOGIN_FORM_FIELD, form); } } else { Config.getAuthorizationProvider().setUserSecurityAttributes(user); responseData.put(LOGIN_STATUS_FIELD, true); responseData.put(USER_FIELD, user); session.setAttribute("user", user); } HttpUtil.sendResponse(response, new ObjectMapper().writeValueAsString(responseData), HttpUtil.JSON); }
Example #13
Source File: Prj2000Controller.java From oslits with GNU General Public License v3.0 | 5 votes |
/** * 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 #14
Source File: MailingWizardAction.java From openemm with GNU Affero General Public License v3.0 | 5 votes |
private void setMailingWorkflowParameters(HttpServletRequest req, ComMailing mailing) { HttpSession session = req.getSession(); Integer workflowId = (Integer) session.getAttribute(WorkflowParametersHelper.WORKFLOW_ID); if (workflowId != null && workflowId > 0) { Map<String, String> forwardParams = AgnUtils.getParamsMap((String) session.getAttribute(WorkflowParametersHelper.WORKFLOW_FORWARD_PARAMS)); int mailingIconId = NumberUtils.toInt(forwardParams.get("nodeId")); workflowService.assignWorkflowDrivenSettings(AgnUtils.getAdmin(req), mailing, workflowId, mailingIconId); } }
Example #15
Source File: AdminController.java From newbee-mall with GNU General Public License v3.0 | 5 votes |
@PostMapping(value = "/login") public String login(@RequestParam("userName") String userName, @RequestParam("password") String password, @RequestParam("verifyCode") String verifyCode, HttpSession session) { if (StringUtils.isEmpty(verifyCode)) { session.setAttribute("errorMsg", "验证码不能为空"); return "admin/login"; } if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) { session.setAttribute("errorMsg", "用户名或密码不能为空"); return "admin/login"; } String kaptchaCode = session.getAttribute("verifyCode") + ""; if (StringUtils.isEmpty(kaptchaCode) || !verifyCode.equals(kaptchaCode)) { session.setAttribute("errorMsg", "验证码错误"); return "admin/login"; } AdminUser adminUser = adminUserService.login(userName, password); if (adminUser != null) { session.setAttribute("loginUser", adminUser.getNickName()); session.setAttribute("loginUserId", adminUser.getAdminUserId()); //session过期时间设置为7200秒 即两小时 //session.setMaxInactiveInterval(60 * 60 * 2); return "redirect:/admin/index"; } else { session.setAttribute("errorMsg", "登陆失败,请联系作者获得测试账号"); return "admin/login"; } }
Example #16
Source File: Login.java From secure-data-service with Apache License 2.0 | 5 votes |
@RequestMapping(value= "/admin", method = RequestMethod.POST) public ModelAndView admin(@RequestParam("SAMLRequest") String encodedSamlRequest, @RequestParam(value = "realm", required = false) String realm, HttpSession httpSession){ User user = (User) httpSession.getAttribute(USER_SESSION_KEY); AuthRequestService.Request requestInfo = authRequestService.processRequest(encodedSamlRequest, realm, null); user.getAttributes().put("isAdmin", "true"); user.setImpersonationUser(null); SamlAssertion samlAssertion = samlService.buildAssertion(user.getUserId(), user.getRoles(), user.getAttributes(), requestInfo); ModelAndView mav = new ModelAndView("post"); mav.addObject("samlAssertion", samlAssertion); return mav; }
Example #17
Source File: JobController.java From JobX with Apache License 2.0 | 5 votes |
@RequestMapping("editsingle.do") @ResponseBody @RequestRepeat public Job editSingleJob(HttpSession session, HttpServletResponse response, Long id) { Job job = jobService.getById(id); if (job == null) { write404(response); return null; } if (!jobService.checkJobOwner(session, job.getUserId())) return null; return job; }
Example #18
Source File: WechatLoginController.java From seezoon-framework-all with Apache License 2.0 | 5 votes |
@RequestMapping("/auth2Login.do") public void auth2Login(@RequestParam String code,@RequestParam String state,HttpServletResponse response,HttpSession session) throws IOException { String redirectUrl = valueOperations.get(state); Assert.hasLength(redirectUrl,"redirectUrl地址为空"); AuthAccessToken accessToken = wechatUserInfoServiceAPI.getUserInfoByCode(code); FrontUser frontUser = new FrontUser(); WechatUserInfo wechatUserInfo = new WechatUserInfo(); if ("snsapi_base".equals(accessToken.getScope())) {//不需要用户信息 frontUser.setUserId(accessToken.getOpenid()); wechatUserInfo.setOpenid(accessToken.getOpenid()); } else if ("snsapi_userinfo".equals(accessToken.getScope())) { UserInfo userinfo = wechatUserInfoServiceAPI.userinfo(accessToken); frontUser.setUserId(userinfo.getOpenid()); frontUser.setName(userinfo.getNickname()); wechatUserInfo.setOpenid(userinfo.getOpenid()); wechatUserInfo.setNickname(userinfo.getNickname()); wechatUserInfo.setSex(userinfo.getSex()); wechatUserInfo.setProvince(userinfo.getProvince()); wechatUserInfo.setCity(userinfo.getCity()); wechatUserInfo.setCountry(userinfo.getCountry()); wechatUserInfo.setHeadImgUrl(userinfo.getHeadimgurl()); wechatUserInfo.setUnionid(userinfo.getUnionid()); } WechatUserInfo dbWechatUserInfo = wechatUserInfoService.findByOpenId(wechatUserInfo.getOpenid()); if (null == dbWechatUserInfo) { wechatUserInfoService.save(wechatUserInfo); } else { wechatUserInfo.setId(dbWechatUserInfo.getId()); wechatUserInfoService.updateSelective(wechatUserInfo); } FrontSubject.putUserSession(session, frontUser); response.sendRedirect(redirectUrl); }
Example #19
Source File: TechnicalServlet.java From olingo-odata4 with Apache License 2.0 | 5 votes |
@Override protected void service(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { OData odata = OData.newInstance(); EdmxReference reference = new EdmxReference(URI.create("../v4.0/cs02/vocabularies/Org.OData.Core.V1.xml")); reference.addInclude(new EdmxReferenceInclude("Org.OData.Core.V1", "Core")); final ServiceMetadata serviceMetadata = odata.createServiceMetadata( new EdmTechProvider(), Collections.singletonList(reference), new MetadataETagSupport(metadataETag)); HttpSession session = request.getSession(true); DataProvider dataProvider = (DataProvider) session.getAttribute(DataProvider.class.getName()); if (dataProvider == null) { dataProvider = new DataProvider(odata, serviceMetadata.getEdm()); session.setAttribute(DataProvider.class.getName(), dataProvider); LOG.info("Created new data provider."); } ODataHttpHandler handler = odata.createHandler(serviceMetadata); // Register processors. handler.register(new TechnicalEntityProcessor(dataProvider, serviceMetadata)); handler.register(new TechnicalPrimitiveComplexProcessor(dataProvider, serviceMetadata)); handler.register(new TechnicalActionProcessor(dataProvider, serviceMetadata)); handler.register(new TechnicalBatchProcessor(dataProvider)); // Register helpers. handler.register(new ETagSupport()); handler.register(new DefaultDebugSupport()); // Process the request. handler.process(request, response); } catch (final RuntimeException e) { LOG.error("Server Error", e); throw new ServletException(e); } }
Example #20
Source File: LoginController.java From dpCms with Apache License 2.0 | 5 votes |
@RequestMapping(value = "/login/timeOut") @ResponseBody public Response timeOut(short StatusCode, HttpSession session) { Response response = ResponseFactory.getResponse(); response.setStateCode(StateCode.LOGIN_TIMEOUT); response.setMessage("会话已经超时,请重新登录"); return response; }
Example #21
Source File: LogoutServlet.java From getting-started-java with Apache License 2.0 | 5 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { // you can also make an authenticated request to logout, but here we choose to // simply delete the session variables for simplicity HttpSession session = req.getSession(false); if (session != null) { session.invalidate(); } // rebuild session req.getSession(); }
Example #22
Source File: UserSessionUtil.java From albert with MIT License | 5 votes |
private static Object getObjectFromSession(String attributeKey) { HttpSession session = getSession(); if (session != null) { return session.getAttribute(attributeKey); } return null; }
Example #23
Source File: ExtendedAccessLogValve.java From tomcatsrc with Apache License 2.0 | 5 votes |
@Override public void addElement(StringBuilder buf, Date date, Request request, Response response, long time) { HttpSession session = null; if (request != null) { session = request.getSession(false); if (session != null) { buf.append(wrap(session.getAttribute(attribute))); } } }
Example #24
Source File: DefaultHttpServletRequestTest.java From piranha with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Test isRequestedSessionIdValid method. */ @Test public void testIsRequestedSessionIdValid() { DefaultWebApplication webApp = new DefaultWebApplication(); DefaultWebApplicationRequest request = new TestWebApplicationRequest(); DefaultWebApplicationResponse response = new TestWebApplicationResponse(); request.setWebApplication(webApp); response.setWebApplication(webApp); webApp.linkRequestAndResponse(request, response); HttpSession session = request.getSession(true); request.setRequestedSessionId(session.getId()); assertTrue(request.isRequestedSessionIdValid()); }
Example #25
Source File: FrontSessionFilter.java From seezoon-framework-all with Apache License 2.0 | 5 votes |
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); FrontUser frontUser =FrontSubject.getUserSession(session); if (null == frontUser) { response.sendError(HttpStatus.NEED_LOGIN.getValue()); return false; } else { FrontSubject.put(frontUser); return true; } }
Example #26
Source File: BaseAuthenticationFilter.java From alfresco-remote-api with GNU Lesser General Public License v3.0 | 5 votes |
private void setExternalAuth(HttpSession session, boolean externalAuth) { if (externalAuth) { session.setAttribute(LOGIN_EXTERNAL_AUTH, Boolean.TRUE); } else { session.removeAttribute(LOGIN_EXTERNAL_AUTH); } }
Example #27
Source File: LoginSuccessHandler.java From secrets-proxy with Apache License 2.0 | 5 votes |
/** * Removes any temporary authentication-related data which may have been stored in the session * during the authentication process. * * @param request http request. */ private void clearAuthenticationAttributes(HttpServletRequest request) { // Don't create new session. HttpSession session = request.getSession(false); if (session == null) { return; } session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); }
Example #28
Source File: OIDCAuthenticationClient.java From carbon-apimgt with Apache License 2.0 | 5 votes |
public OIDCAuthenticationClient(ConfigurationContext ctx, String serverURL, String cookie, HttpSession session) throws Exception { this.session = session; String serviceEPR = serverURL + "OIDCAuthenticationService"; stub = new OIDCAuthenticationServiceStub(ctx, serviceEPR); ServiceClient client = stub._getServiceClient(); Options options = client.getOptions(); options.setManageSession(true); if (cookie != null) { options.setProperty(HTTPConstants.COOKIE_STRING, cookie); } }
Example #29
Source File: ApplicationContextHolder.java From elastic-rabbitmq with MIT License | 5 votes |
/** * @param tenantId * @param httpSession */ public static void addSession(Integer tenantId, HttpSession httpSession) { if (!httpSessions.containsKey(tenantId)) { httpSessions.put(tenantId, new HashSet<HttpSession>()); } httpSessions.get(tenantId).add(httpSession); }
Example #30
Source File: MySessionContext.java From HomeApplianceMall with MIT License | 5 votes |
public static synchronized HttpSession getSession(String session_id) { if (session_id == null){ return null; }else{ return mymap.get(session_id); } }