Java Code Examples for javax.servlet.http.HttpServletRequest#getAttribute()
The following examples show how to use
javax.servlet.http.HttpServletRequest#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: SecondCycleIndividualCandidacyProcessRefactoredDA.java From fenixedu-academic with GNU Lesser General Public License v3.0 | 6 votes |
@Override public ActionForward viewCandidacy(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { SecondCycleIndividualCandidacyProcess individualCandidacyProcess = (SecondCycleIndividualCandidacyProcess) request.getAttribute("individualCandidacyProcess"); SecondCycleIndividualCandidacyProcessBean bean = new SecondCycleIndividualCandidacyProcessBean(individualCandidacyProcess); bean.setPersonBean(new PersonBean(individualCandidacyProcess.getPersonalDetails())); request.setAttribute("individualCandidacyProcessBean", bean); request.setAttribute("hasSelectedDegrees", !individualCandidacyProcess.getSelectedDegrees().isEmpty()); request.setAttribute("isApplicationSubmissionPeriodValid", redefineApplicationSubmissionPeriodValid(individualCandidacyProcess)); return mapping.findForward("show-candidacy-details"); }
Example 2
Source File: DispatcherRequestTest.java From portals-pluto with Apache License 2.0 | 6 votes |
private TestResult checkGetRequestURI(HttpServletRequest request) { TestResult result = new TestResult(); result.setDescription("Ensure that method request.getRequestURI() " + "returns correct value."); result.setSpecPLT("16.3.3"); String expected = (String) request.getAttribute(EXPECTED_REQUEST_URI); String requestURI = request.getRequestURI(); if (requestURI != null && requestURI.equals(expected)) { result.setReturnCode(TestResult.PASSED); } else { TestUtils.failOnAssertion("request.getRequestURI()", requestURI, expected, result); } return result; }
Example 3
Source File: TwitterShowUserServlet.java From keycloak with Apache License 2.0 | 6 votes |
private TwitterOAuthResponse getTwitterOAuthResponse(final HttpServletRequest req) { ClientRequestFilter authFilter = new ClientRequestFilter() { @Override public void filter(ClientRequestContext requestContext) throws IOException { KeycloakSecurityContext securityContext = (KeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName()); String accessToken = securityContext.getTokenString(); requestContext.getHeaders().add(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken); } }; Client client = ClientBuilder.newBuilder().register(authFilter).build(); WebTarget target = client.target(getIdentityProviderTokenUrl()); return target.request().get().readEntity(TwitterOAuthResponse.class); }
Example 4
Source File: ShoppingCartEvents.java From scipio-erp with Apache License 2.0 | 5 votes |
/** Initialize order entry from a shopping list **/ public static String loadCartFromShoppingList(HttpServletRequest request, HttpServletResponse response) { LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); HttpSession session = request.getSession(); GenericValue userLogin = (GenericValue) session.getAttribute("userLogin"); String shoppingListId = request.getParameter("shoppingListId"); ShoppingCart cart = null; try { Map<String, Object> outMap = dispatcher.runSync("loadCartFromShoppingList", UtilMisc.<String, Object>toMap("shoppingListId", shoppingListId, "userLogin", userLogin)); if (ServiceUtil.isError(outMap)) { String errorMessage = ServiceUtil.getErrorMessage(outMap); request.setAttribute("_ERROR_MESSAGE_", errorMessage); Debug.logError(errorMessage, module); return "error"; } cart = (ShoppingCart)outMap.get("shoppingCart"); } catch (GenericServiceException exc) { request.setAttribute("_ERROR_MESSAGE_", exc.getMessage()); return "error"; } setSyncCartObjectAndAttr(request, cart); // SCIPIO: refactored return "success"; }
Example 5
Source File: SpanCustomizingAsyncHandlerInterceptor.java From brave with Apache License 2.0 | 5 votes |
/** * Sets the "error" and "http.route" attributes so that the {@link TracingFilter} can read them. */ @Override public void afterCompletion( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { Object span = request.getAttribute(SpanCustomizer.class.getName()); if (span instanceof SpanCustomizer) { setErrorAttribute(request, ex); setHttpRouteAttribute(request); } }
Example 6
Source File: PathDisplay.java From portals-pluto with Apache License 2.0 | 5 votes |
public PathDisplay(HttpServletRequest req, String caller) { this.caller = caller; title = (String) req.getAttribute("title"); async_request_uri = (String) req.getAttribute("javax.servlet.async.request_uri"); async_context_path = (String) req.getAttribute("javax.servlet.async.context_path"); async_servlet_path = (String) req.getAttribute("javax.servlet.async.servlet_path"); async_path_info = (String) req.getAttribute("javax.servlet.async.path_info"); async_query_string = (String) req.getAttribute("javax.servlet.async.query_string"); forward_request_uri = (String) req.getAttribute("javax.servlet.forward.request_uri"); forward_context_path = (String) req.getAttribute("javax.servlet.forward.context_path"); forward_servlet_path = (String) req.getAttribute("javax.servlet.forward.servlet_path"); forward_path_info = (String) req.getAttribute("javax.servlet.forward.path_info"); forward_query_string = (String) req.getAttribute("javax.servlet.forward.query_string"); include_request_uri = (String) req.getAttribute("javax.servlet.include.request_uri"); include_context_path = (String) req.getAttribute("javax.servlet.include.context_path"); include_servlet_path = (String) req.getAttribute("javax.servlet.include.servlet_path"); include_path_info = (String) req.getAttribute("javax.servlet.include.path_info"); include_query_string = (String) req.getAttribute("javax.servlet.include.query_string"); method_request_uri = req.getRequestURI(); method_context_path = req.getContextPath(); method_servlet_path = req.getServletPath(); method_path_info = req.getPathInfo(); method_path_xlated = req.getPathTranslated(); method_query_string = req.getQueryString(); type = req.getDispatcherType().name(); isAsyncSupported = req.isAsyncSupported(); Map<String, String[]> pmap = req.getParameterMap(); for (String key : pmap.keySet()) { params.put(key, Arrays.asList(pmap.get(key))); } }
Example 7
Source File: HandlerFunctionAdapter.java From spring-analysis-note with MIT License | 5 votes |
private ServerRequest getServerRequest(HttpServletRequest servletRequest) { ServerRequest serverRequest = (ServerRequest) servletRequest.getAttribute(RouterFunctions.REQUEST_ATTRIBUTE); Assert.state(serverRequest != null, () -> "Required attribute '" + RouterFunctions.REQUEST_ATTRIBUTE + "' is missing"); return serverRequest; }
Example 8
Source File: SessionManager.java From document-management-software with GNU Lesser General Public License v3.0 | 5 votes |
/** * Gets the Session ID specification from the current request following this * lookup strategy: * <ol> * <li>Session attribute <code>PARAM_SID</code></li> * <li>Request attribute <code>PARAM_SID</code></li> * <li>Request parameter <code>PARAM_SID</code></li> * <li>Cookie <code>COOKIE_SID</code></li> * <li>Spring SecurityContextHolder</li> * </ol> * * @param request The current request to inspect * * @return The SID if any */ public String getSessionId(HttpServletRequest request) { if (request != null) { if (request.getSession(false) != null && request.getSession(false).getAttribute(PARAM_SID) != null) return (String) request.getSession(false).getAttribute(PARAM_SID); if (request.getAttribute(PARAM_SID) != null) return (String) request.getAttribute(PARAM_SID); if (request.getParameter(PARAM_SID) != null) return (String) request.getParameter(PARAM_SID); Cookie cookies[] = request.getCookies(); if (cookies != null) for (Cookie cookie : cookies) { if (COOKIE_SID.equals(cookie.getName())) return cookie.getValue(); } } Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null && auth instanceof LDAuthenticationToken) return ((LDAuthenticationToken) auth).getSid(); if (request != null) { Client client = buildClient(request); Session session = getByClientId(client.getId()); if (session != null && isOpen(session.getSid())) return session.getSid(); } return null; }
Example 9
Source File: DispatcherServlet.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Convert the request into a multipart request, and make multipart resolver available. * <p>If no multipart resolver is set, simply use the existing request. * @param request current HTTP request * @return the processed request (multipart wrapper if necessary) * @see MultipartResolver#resolveMultipart */ protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException { if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) { if (WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class) != null) { logger.debug("Request is already a MultipartHttpServletRequest - if not in a forward, " + "this typically results from an additional MultipartFilter in web.xml"); } else if (hasMultipartException(request) ) { logger.debug("Multipart resolution failed for current request before - " + "skipping re-resolution for undisturbed error rendering"); } else { try { return this.multipartResolver.resolveMultipart(request); } catch (MultipartException ex) { if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) != null) { logger.debug("Multipart resolution failed for error dispatch", ex); // Keep processing error dispatch with regular request handle below } else { throw ex; } } } } // If not returned before: return original request. return request; }
Example 10
Source File: ChooseCurricularCourseDispatchActionForCoordinator.java From fenixedu-academic with GNU Lesser General Public License v3.0 | 5 votes |
private String getFromRequest(String parameter, HttpServletRequest request) { String parameterString = request.getParameter(parameter); if (parameterString == null) { parameterString = (String) request.getAttribute(parameter); } return parameterString; }
Example 11
Source File: DispatcherTests3S_SPEC2_19_ForwardServletAction_servlet.java From portals-pluto with Apache License 2.0 | 5 votes |
protected void processTCKReq(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PortletRequest portletReq = (PortletRequest) request.getAttribute("javax.portlet.request"); request.getAttribute("javax.portlet.response"); request.getAttribute("javax.portlet.config"); Thread.currentThread().getId(); portletReq.getAttribute(THREADID_ATTR); // Create result objects for the tests }
Example 12
Source File: PageViewsCollector.java From blog with MIT License | 5 votes |
@GetMapping("list") public BaseResponse getPageViewLists(HttpServletRequest request, @NonNull Long timestamp) { Object headerPermission = request.getAttribute("gunjianpan"); if (headerPermission != null && headerPermission.equals("Error")) { return BaseResponse.newFailResponse() .errorMsg("Have no Permission!!!") .errorCode(ErrorCodeConsts.STATUS_FORBIDDEN) .build(); } Boolean timePermission = permissionFilterService.haveTimePermission(timestamp); if (!timePermission) { return BaseResponse.newSuccResponse() .result( PageViewsBo.builder() .titleViewsMap(new HashMap<>()) .totalPageViews(8273) .totalSpider(1029831) .yesterdayPageSpider(1091) .yesterdayPageViews(21) .build() ).build(); } return BaseResponse.newSuccResponse() .result(pageViewsService.getPageViewsLists(timestamp)) .build(); }
Example 13
Source File: AuthTool.java From frostmourne with MIT License | 4 votes |
public static UserInfo currentUser() { HttpServletRequest request = currentRequest(); return (UserInfo) request.getAttribute(USER_ATTR); }
Example 14
Source File: ShallowEtagHeaderFilter.java From lams with GNU General Public License v2.0 | 4 votes |
private static boolean isContentCachingDisabled(HttpServletRequest request) { return (request.getAttribute(STREAMING_ATTRIBUTE) != null); }
Example 15
Source File: SeperateExecutionCourseDispatchAction.java From fenixedu-academic with GNU Lesser General Public License v3.0 | 4 votes |
public ActionForward manageCurricularSeparation(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws FenixServiceException, FenixActionException { // FIXME: ugly code to get attribute before parameter (parameter needs to be changed when coming from separate) String executionCourseId = (String) request.getAttribute("executionCourseId"); if (executionCourseId == null) { executionCourseId = RequestUtils.getAndSetStringToRequest(request, "executionCourseId"); } InfoExecutionCourse infoExecutionCourse; try { infoExecutionCourse = ReadInfoExecutionCourseByOID.run(executionCourseId); } catch (FenixServiceException e) { throw new FenixActionException(e); } if (infoExecutionCourse.getAssociatedInfoCurricularCourses() != null) { Collections.sort(infoExecutionCourse.getAssociatedInfoCurricularCourses(), new BeanComparator("name")); } request.setAttribute(PresentationConstants.EXECUTION_COURSE, infoExecutionCourse); // Setting bean for return to listExecutionCourseActions String executionCoursesNotLinked = RequestUtils.getAndSetStringToRequest(request, "executionCoursesNotLinked"); Boolean chooseNotLinked = false; if (!StringUtils.isEmpty(executionCoursesNotLinked) && Boolean.valueOf(executionCoursesNotLinked)) { chooseNotLinked = true; } String executionPeriodId = RequestUtils.getAndSetStringToRequest(request, "executionPeriodId"); ExecutionCourse executionCourse = FenixFramework.getDomainObject(executionCourseId); ExecutionSemester executionPeriod = FenixFramework.getDomainObject(executionPeriodId); ExecutionCourseBean sessionBean = new ExecutionCourseBean(); sessionBean.setSourceExecutionCourse(executionCourse); sessionBean.setExecutionSemester(executionPeriod); sessionBean.setChooseNotLinked(chooseNotLinked); if (!chooseNotLinked) { String originExecutionDegreeId = RequestUtils.getAndSetStringToRequest(request, "originExecutionDegreeId"); String curricularYearId = RequestUtils.getAndSetStringToRequest(request, "curricularYearId"); ExecutionDegree executionDegree = FenixFramework.getDomainObject(originExecutionDegreeId); CurricularYear curYear = FenixFramework.getDomainObject(curricularYearId); sessionBean.setExecutionDegree(executionDegree); sessionBean.setCurricularYear(curYear); request.setAttribute("curYear", curYear.getYear().toString()); request.setAttribute("originExecutionDegreeName", executionDegree.getPresentationName()); } request.setAttribute("sessionBean", sessionBean); return mapping.findForward("manageCurricularSeparation"); }
Example 16
Source File: MCRShibbolethLoginServlet.java From mycore with GNU General Public License v3.0 | 4 votes |
public void doGetPost(MCRServletJob job) throws Exception { HttpServletRequest req = job.getRequest(); HttpServletResponse res = job.getResponse(); String msg = null; String uid = (String) req.getAttribute("uid"); String userId = uid != null ? uid : req.getRemoteUser(); if (userId != null) { final String realmId = userId.contains("@") ? userId.substring(userId.indexOf("@") + 1) : null; if (realmId != null && MCRRealmFactory.getRealm(realmId) != null) { userId = realmId != null ? userId.replace("@" + realmId, "") : userId; final Map<String, Object> attributes = new HashMap<>(); final MCRUserAttributeMapper attributeMapper = MCRRealmFactory.getAttributeMapper(realmId); for (final String key : attributeMapper.getAttributeNames()) { final Object value = req.getAttribute(key); if (value != null) { LOGGER.info("received {}:{}", key, value); attributes.put(key, value); } } MCRUserInformation userinfo; MCRUser user = MCRUserManager.getUser(userId, realmId); if (user != null) { LOGGER.debug("login existing user \"{}\"", user.getUserID()); attributeMapper.mapAttributes(user, attributes); user.setLastLogin(); MCRUserManager.updateUser(user); userinfo = user; } else { userinfo = new MCRShibbolethUserInformation(userId, realmId, attributes); } MCRSessionMgr.getCurrentSession().setUserInformation(userinfo); // MCR-1154 req.changeSessionId(); res.sendRedirect(res.encodeRedirectURL(req.getParameter("url"))); return; } else { msg = "Login from realm \"" + realmId + "\" is not allowed."; } } else { msg = "Principal could not be received from IDP."; } job.getResponse().sendError(HttpServletResponse.SC_UNAUTHORIZED, msg); }
Example 17
Source File: IndexController.java From xxl-sso with GNU General Public License v3.0 | 4 votes |
@RequestMapping("/") @ResponseBody public ReturnT<XxlSsoUser> index(HttpServletRequest request) { XxlSsoUser xxlUser = (XxlSsoUser) request.getAttribute(Conf.SSO_USER); return new ReturnT<XxlSsoUser>(xxlUser); }
Example 18
Source File: OrderEvents.java From scipio-erp with Apache License 2.0 | 4 votes |
public static String downloadDigitalProduct(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); ServletContext application = session.getServletContext(); Delegator delegator = (Delegator) request.getAttribute("delegator"); GenericValue userLogin = (GenericValue) session.getAttribute("userLogin"); String dataResourceId = request.getParameter("dataResourceId"); try { // has the userLogin.partyId ordered a product with DIGITAL_DOWNLOAD content associated for the given dataResourceId? GenericValue orderRoleAndProductContentInfo = EntityQuery.use(delegator).from("OrderRoleAndProductContentInfo") .where("partyId", userLogin.get("partyId"), "dataResourceId", dataResourceId, "productContentTypeId", "DIGITAL_DOWNLOAD", "statusId", "ITEM_COMPLETED") .queryFirst(); if (orderRoleAndProductContentInfo == null) { request.setAttribute("_ERROR_MESSAGE_", "No record of purchase for digital download found (dataResourceId=[" + dataResourceId + "])."); return "error"; } // TODO: check validity based on ProductContent fields: useCountLimit, useTime/useTimeUomId if (orderRoleAndProductContentInfo.getString("mimeTypeId") != null) { response.setContentType(orderRoleAndProductContentInfo.getString("mimeTypeId")); } OutputStream os = response.getOutputStream(); GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).cache().queryOne(); Map<String, Object> resourceData = DataResourceWorker.getDataResourceStream(dataResource, "", application.getInitParameter("webSiteId"), UtilHttp.getLocale(request), application.getRealPath("/"), false); os.write(IOUtils.toByteArray((InputStream) resourceData.get("stream"))); os.flush(); } catch (GeneralException | IOException e) { String errMsg = "Error downloading digital product content: " + e.toString(); Debug.logError(e, errMsg, module); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } return "success"; }
Example 19
Source File: RequestHandler.java From scipio-erp with Apache License 2.0 | 4 votes |
/** * Performs HTTP redirect to the given URL. * <p> * SCIPIO: NOTE: All the code currently calling this may append jsessionIds (through processing * of changing encode to true to correct filter hook behavior). * Currently I don't see how this is bad. * If need to remove jsessionId from redirects, could uncomment the lines below. * <p> * SCIPIO: 2018-12-12: Modified to take Integer statusCode instead of statusCodeString. * <p> * SCIPIO: 2019-12-04: Added allowCacheRedirect to preventing caching 301 redirects. */ private void callRedirect(String url, HttpServletResponse resp, HttpServletRequest req, int statusCode, AttributesSpec saveAttrMap, String httpConnectionHeader, Boolean allowCacheRedirect) throws RequestHandlerException { // SCIPIO: Uncomment this to force remove jsessionId from controller redirects... //RequestUtil.removeJsessionId(url); if (Debug.infoOn()) Debug.logInfo("Sending redirect to: [" + url + "]." + showSessionId(req), module); // SCIPIO: sanity check if (url == null || url.isEmpty()) { Debug.logError("Scipio: Redirect URL is empty", module); throw new RequestHandlerException("Scipio: Redirect URL is empty"); } if (!saveAttrMap.isNone()) { // SCIPIO: not for all redirects! // set the attributes in the session so we can access it. Enumeration<String> attributeNameEnum = UtilGenerics.cast(req.getAttributeNames()); Map<String, Object> reqAttrMap = new HashMap<>(); SaveAttrPolicyInvoker<?> attrPolicyInvoker = RedirectAttrPolicy.SavePolicy.getInvoker(req); // SCIPIO while (attributeNameEnum.hasMoreElements()) { String name = attributeNameEnum.nextElement(); Object obj = req.getAttribute(name); if (obj instanceof Serializable) { if (saveAttrMap.includeAttribute(name)) { // SCIPIO: includeRequestAttribute filter // SCIPIO: New RequestAttrPolicy callbacks //reqAttrMap.put(name, obj); attrPolicyInvoker.filterSaveAttrToMap(reqAttrMap, name, obj); } } } // SCIPIO: NOTE: 2019-01-24: the "multiPartMap" exclude has been moved to the RedirectAttrPolicy invoker(s) for reuse //reqAttrMap.remove("multiPartMap"); if (reqAttrMap.size() > 0) { reqAttrMap.remove("_REQUEST_HANDLER_"); // RequestHandler is not serializable and must be removed first. See http://issues.apache.org/jira/browse/OFBIZ-750 byte[] reqAttrMapBytes = UtilObject.getBytes(reqAttrMap); if (reqAttrMapBytes != null) { req.getSession().setAttribute("_REQ_ATTR_MAP_", StringUtil.toHexString(reqAttrMapBytes)); } } } /* SCIPIO: already int Integer statusCode; try { statusCode = Integer.valueOf(statusCodeString); } catch (NumberFormatException e) { statusCode = 303; } */ // SCIPIO: By default, don't allow caching 301 redirects as this messes with most controller logic if (!Boolean.TRUE.equals(allowCacheRedirect)) { UtilHttp.setResponseBrowserProxyNoCacheRedirect(resp); } // send the redirect try { resp.setStatus(statusCode); resp.setHeader("Location", url); // SCIPIO: This is not appropriate; majority of redirects in scipio are intra-webapp, followed by inter-webapp //resp.setHeader("Connection", "close"); if (httpConnectionHeader != null) { resp.setHeader("Connection", httpConnectionHeader); } } catch (IllegalStateException ise) { throw new RequestHandlerException(ise.getMessage(), ise); } }
Example 20
Source File: SubjectUtil.java From JwtPermission with Apache License 2.0 | 2 votes |
/** * 从request中获取token * * @param request HttpServletRequest * @return Token */ public static Token getToken(HttpServletRequest request) { Object token = request.getAttribute(REQUEST_TOKEN_NAME); return token == null ? null : (Token) token; }