Java Code Examples for javax.servlet.http.HttpServletRequest.getAttribute()

The following are Jave code examples for showing how to use getAttribute() of the javax.servlet.http.HttpServletRequest 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: xxl-api   File: XxlApiUserController.java   View Source Code Vote up 6 votes
@RequestMapping
   @PermessionLimit(superUser = true)
public String index(Model model, HttpServletRequest request) {

	// permission
	XxlApiUser loginUser = (request.getAttribute(LOGIN_IDENTITY_KEY)!=null)? (XxlApiUser) request.getAttribute(LOGIN_IDENTITY_KEY) :null;
	if (loginUser.getType()!=1) {
		throw new RuntimeException("权限拦截.");
	}

	List<XxlApiUser> userList = xxlApiUserDao.loadAll();
	if (CollectionUtils.isEmpty(userList)) {
		userList = new ArrayList<>();
	} else {
		for (XxlApiUser user: userList) {
			user.setPassword("***");
		}
	}
	model.addAttribute("userList", JacksonUtil.writeValueAsString(userList));

	return "user/user.list";
}
 
Example 2
Project: accumulate   File: ExecuteTimeInterceptor.java   View Source Code Vote up 6 votes
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	Long long1 = (Long) request.getAttribute(EXECUTE_TIME_ATTRIBUTE_NAME);
	if (long1 == null) {
		Long long2 = (Long) request.getAttribute(START_TIME_ATTRIBUTE_NAME);
		Long long3 = Long.valueOf(System.currentTimeMillis());
		long1 = Long.valueOf(long3.longValue() - long2.longValue());
		request.setAttribute(START_TIME_ATTRIBUTE_NAME, long2);
	}
	if (modelAndView != null) {
		String s = modelAndView.getViewName();
		if (!StringUtils.startsWith(s, "redirect:"))
			modelAndView.addObject(EXECUTE_TIME_ATTRIBUTE_NAME, long1);
	}
	if (logger.isDebugEnabled()) {
		logger.debug((new StringBuilder("[")).append(handler).append("] executeTime: ").append(long1).append("ms").toString());
	}
}
 
Example 3
Project: SSMShiro   File: IndexController.java   View Source Code Vote up 6 votes
@RequestMapping("/login")
public String login(HttpServletRequest request) throws Exception{
	String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
	//根据shiro返回的异常类路径判断,抛出指定异常信息
	if(exceptionClassName!=null){
		if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
			//最终会抛给异常处理器
			throw new UnknownAccountException("账号不存在");
		} else if (IncorrectCredentialsException.class.getName().equals(
				exceptionClassName)) {
			throw new IncorrectCredentialsException("用户名/密码错误");
		}else {
			throw new Exception();//最终在异常处理器生成未知错误
		}
	}
	return "login";
}
 
Example 4
Project: oscm   File: BaseBesFilter.java   View Source Code Vote up 6 votes
/**
 * Get the relative URL for the login page. In case of a marketplace login
 * the path of the marketplace login page is returned. In case of a BES
 * login the passed default page is returned.
 * 
 * @param httpRequest
 *            - the HTTP request
 * @param defaultLoginPage
 *            - the path of page to be shown if it is no marketplace login.
 * 
 * @return see above.
 */
protected String getActualLoginPage(HttpServletRequest httpRequest,
        String defaultLoginPage, AuthenticationSettings authSettings) {

    if (BesServletRequestReader.isMarketplaceRequest(httpRequest)) {
        return BaseBean.MARKETPLACE_LOGIN_PAGE;
    }

    // Check if service login for a marketplace service is
    // requested. In this case add it as parameter to be treated by the
    // login panel.
    String loginType = (String) httpRequest
            .getAttribute(Constants.REQ_ATTR_SERVICE_LOGIN_TYPE);
    if (Constants.REQ_ATTR_LOGIN_TYPE_MPL.equals(loginType)) {
        String serviceLoginType = "?serviceLoginType=" + loginType;
        if (authSettings != null && authSettings.isServiceProvider()) {
            return BaseBean.SAML_SP_LOGIN_AUTOSUBMIT_PAGE
                    + serviceLoginType;
        } else {
            return BaseBean.MARKETPLACE_LOGIN_PAGE + serviceLoginType;
        }
    }

    return defaultLoginPage;
}
 
Example 5
Project: jaffa-framework   File: HistoryNav.java   View Source Code Vote up 6 votes
/** This will search the request stream for the attribute 'historyNav'. If not found, it'll search for the parameter 'historyNav'.
 * This parameter is expected to be in XML format and will be decoded into a List
 * @param request The request stream.
 * @return The List containing the links for the HistoryNav.
 */
public static List obtainHistoryNav(HttpServletRequest request) {
    List historyNavList = null;

    // check to see if the List is present as an attribute in the request stream
    historyNavList = (List) request.getAttribute(HistoryNav.HISTORY_NAV_PARAMETER);
    if (historyNavList == null) {
        // now check to see if it was passed in as a parameter in the request stream
        String historyNavXml = request.getParameter(HistoryNav.HISTORY_NAV_PARAMETER);

        if (historyNavXml != null) {
            // the String will be in XML format.. so unmarshal it into a List
            historyNavList = decode(historyNavXml);
        }
    }

    return historyNavList;
}
 
Example 6
Project: JahiaDF   File: JahiaUtils.java   View Source Code Vote up 6 votes
/**
 * Resolve Template Resource by View
 * @param request This is a HttpServletRequest
 * @param resource This is a resource to resolve for template
 * @param renderContext This is a RenderContext
 * @return view
 * @throws Exception
 */
public static View resolveTemplateResourceView(HttpServletRequest request, Resource resource, RenderContext renderContext)
        throws Exception {
    View view = null;
    Script script = (Script) request.getAttribute(JAHIA_SCRIPT);
    if (script != null){
        view = script.getView();
    } else {
        RenderService service = RenderService.getInstance();
        Resource pageResource = new Resource(resource.getNode(), HTML, null, Resource.CONFIGURATION_PAGE);
        Template template = service.resolveTemplate(pageResource, renderContext);
        pageResource.setTemplate(template.getView());

        JCRNodeWrapper templateNode = pageResource.getNode().getSession().getNodeByIdentifier(template.node);
        Resource wrapperResource = new Resource(templateNode, pageResource.getTemplateType(), template.view,
                Resource.CONFIGURATION_WRAPPER);
        script = service.resolveScript(wrapperResource, renderContext);
        if (script != null){
            view = script.getView();
        }
    }

    return view;
}
 
Example 7
Project: wxcard   File: UserApi.java   View Source Code Vote up 6 votes
@RequestMapping("/insertfaq")
private @ResponseBody Map faqWxcard(HttpServletResponse resp,HttpServletRequest req) throws Exception{
	Map map = (Map) req.getAttribute("info");
	Userinfo user = (Userinfo) req.getAttribute("user");
	
	String openid = (String) map.get("openid");
	String email = (String) map.get("email");
	String description = (String) map.get("description");
	
	if(openid == null || "".equals(openid) || "null".equals(openid) || email == null || "".equals(email) || "null".equals(email) || description == null || "".equals(description) || "null".equals(description) ){
		throw new GlobalErrorInfoException(KeyvalueErrorInfoEnum.KEYVALUE_ERROR);
	}
	
	map.put("userid", user.getUserid());
	try{
		userinfoService.insertFaq(map);
	}catch(Exception e){
		throw new GlobalErrorInfoException(NodescribeErrorInfoEnum.NODESCRIBE_ERROR);
	}
	map.clear();
	map.put("code", "0");
	map.put("message", "operation success");
	return map;
}
 
Example 8
Project: oauth2-shiro-redis   File: MobileResourcesController.java   View Source Code Vote up 5 votes
/**
 * Return system time API
 *
 * @param request  HttpServletRequest
 * @param response HttpServletResponse
 * @throws Exception
 */
@RequestMapping("system_time")
@ResponseBody
public SystemTimeDto systemTime(HttpServletRequest request, HttpServletResponse response) throws Exception {

    final String clientId = (String) request.getAttribute(OAuth.OAUTH_CLIENT_ID);
    LOG.debug("Current clientId: {}", clientId);

    final String username = request.getUserPrincipal().getName();
    LOG.debug("Current username: {}", username);

    return new SystemTimeDto();
}
 
Example 9
Project: JAVA-   File: ExceptionUtil.java   View Source Code Vote up 5 votes
/**
 * 在request中获取异常类
 * 
 * @param request
 * @return
 */
public static Throwable getThrowable(HttpServletRequest request) {
	Throwable ex = null;
	if (request.getAttribute("exception") != null) {
		ex = (Throwable) request.getAttribute("exception");
	} else if (request.getAttribute("javax.servlet.error.exception") != null) {
		ex = (Throwable) request.getAttribute("javax.servlet.error.exception");
	}
	return ex;
}
 
Example 10
Project: dooo   File: UserAuth.java   View Source Code Vote up 5 votes
public static UserAuthDO getCurrentUser(HttpServletRequest request) {
    Object value = request.getAttribute("_userauth_attribute_key_");
    if (value == NULL) {
        return null;
    } else if (value == null) {
        String wxzid = getGidCookie(request);
        UserAuthDO userAuthDO = authenticate0(wxzid);
        request.setAttribute("_userauth_attribute_key_", userAuthDO == null ? NULL : userAuthDO);
        return userAuthDO;
    } else {
        return (UserAuthDO) value;
    }
}
 
Example 11
Project: springMvc4.x-project   File: DemoInterceptor.java   View Source Code Vote up 5 votes
@Override
public void postHandle(HttpServletRequest request, //③
		HttpServletResponse response, Object handler,
		ModelAndView modelAndView) throws Exception {
	long startTime = (Long) request.getAttribute("startTime");
	request.removeAttribute("startTime");
	long endTime = System.currentTimeMillis();
	System.out.println("本次请求处理时间为:" + new Long(endTime - startTime)+"ms");
	request.setAttribute("handlingTime", endTime - startTime);
}
 
Example 12
Project: karanotes   File: ArticleController.java   View Source Code Vote up 5 votes
/**
 * 文章删除
 * @Author : viakiba
 * @param req
 * @param resp
 * @return
 * @throws GlobalErrorInfoException
 * 2017-04-26
 */
@RequestMapping(value="/article/delete",method=RequestMethod.POST)
public ResultBody deleteArticle(HttpServletRequest req,HttpServletResponse resp) throws GlobalErrorInfoException{
	Map articlemap = (Map) req.getAttribute("jsoninfo");
	String article_id = (String) articlemap.get("article_id");
	if( article_id==null || "".equals("article_id") || "".equals(article_id)){
		throw new GlobalErrorInfoException(JsonKeyValueErrorInfoEnum.JSON_KEYVALUE_ERROR);
	}
	try {
		articlemap = articleServiceImpl.deleteArticle(articlemap);
	} catch (Exception e) {
		throw new GlobalErrorInfoException(NodescribeErrorInfoEnum.NO_DESCRIBE_ERROR);
	}
	return new ResultBody(new HashMap());
}
 
Example 13
Project: nixmash-blog   File: GlobalController.java   View Source Code Vote up 5 votes
@ExceptionHandler(GeoLocationException.class)
public ModelAndView handleGeoLocationException(HttpServletRequest request) {
    ModelAndView mav = new ModelAndView();
    String location = (String) request.getAttribute("location");
    String msg = webUI.getMessage(LOCATION_ERROR_MESSAGE_KEY, location);
    mav.addObject(LOCATION_ERROR_ATTRIBUTE, msg);
    mav.setViewName(PRODUCT_MAP_VIEW);
    return mav;
}
 
Example 14
Project: nifi-registry   File: X509CertificateExtractor.java   View Source Code Vote up 5 votes
/**
 * Extract the client certificate from the specified HttpServletRequest or
 * null if none is specified.
 *
 * @param request http request
 * @return cert
 */
public X509Certificate[] extractClientCertificate(HttpServletRequest request) {
    X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");

    if (certs != null && certs.length > 0) {
        return certs;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("No client certificate found in request.");
    }

    return null;
}
 
Example 15
Project: IPPR2016   File: HttpHeaderUser.java   View Source Code Vote up 5 votes
public HttpHeaderUser(final HttpServletRequest request) {
  final Claims claims = (Claims) request.getAttribute(CLAIM_ID);
  Preconditions.checkNotNull(claims);
  Preconditions.checkNotNull(claims.get(USER_ID));
  Preconditions.checkNotNull(claims.get(ROLES_ID));
  Preconditions.checkNotNull(claims.get(RULES_ID));

  final String userId = String.valueOf(claims.get(USER_ID));
  final String roles = StringUtils.join((List<String>) claims.get(ROLES_ID), ",");
  final String rules = StringUtils.join((List<String>) claims.get(RULES_ID), ",");
  this.userId = userId;
  this.roles = roles;
  this.rules = rules;
}
 
Example 16
Project: lazycat   File: ApplicationDispatcher.java   View Source Code Vote up 4 votes
/**
 * Create and return a request wrapper that has been inserted in the
 * appropriate spot in the request chain.
 */
private ServletRequest wrapRequest(State state) {

	// Locate the request we should insert in front of
	ServletRequest previous = null;
	ServletRequest current = state.outerRequest;
	while (current != null) {
		if (state.hrequest == null && (current instanceof HttpServletRequest))
			state.hrequest = (HttpServletRequest) current;
		if (!(current instanceof ServletRequestWrapper))
			break;
		if (current instanceof ApplicationHttpRequest)
			break;
		if (current instanceof ApplicationRequest)
			break;
		previous = current;
		current = ((ServletRequestWrapper) current).getRequest();
	}

	// Instantiate a new wrapper at this point and insert it in the chain
	ServletRequest wrapper = null;
	if ((current instanceof ApplicationHttpRequest) || (current instanceof Request)
			|| (current instanceof HttpServletRequest)) {
		// Compute a crossContext flag
		HttpServletRequest hcurrent = (HttpServletRequest) current;
		boolean crossContext = false;
		if ((state.outerRequest instanceof ApplicationHttpRequest) || (state.outerRequest instanceof Request)
				|| (state.outerRequest instanceof HttpServletRequest)) {
			HttpServletRequest houterRequest = (HttpServletRequest) state.outerRequest;
			Object contextPath = houterRequest.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH);
			if (contextPath == null) {
				// Forward
				contextPath = houterRequest.getContextPath();
			}
			crossContext = !(context.getPath().equals(contextPath));
		}
		wrapper = new ApplicationHttpRequest(hcurrent, context, crossContext);
	} else {
		wrapper = new ApplicationRequest(current);
	}
	if (previous == null)
		state.outerRequest = wrapper;
	else
		((ServletRequestWrapper) previous).setRequest(wrapper);
	state.wrapRequest = wrapper;
	return (wrapper);

}
 
Example 17
Project: scoold   File: ScooldUtils.java   View Source Code Vote up 4 votes
public Profile getAuthUser(HttpServletRequest req) {
	return (Profile) req.getAttribute(AUTH_USER_ATTRIBUTE);
}
 
Example 18
Project: open-kilda   File: ExecutionTimeInterceptor.java   View Source Code Vote up 4 votes
/**
 * {@inheritDoc}
 */
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception ex) {
    long executed = System.currentTimeMillis() - (long) request.getAttribute(TIMESTAMP);
    logger.debug("execution-time ms: {}", executed);
}
 
Example 19
Project: ch-inofix-timetracker   File: ImportTaskRecordsMVCActionCommand.java   View Source Code Vote up 4 votes
protected void checkExceededSizeLimit(HttpServletRequest request) throws PortalException {

        _log.info("checkExceededSizeLimit()");

        UploadException uploadException = (UploadException) request.getAttribute(WebKeys.UPLOAD_EXCEPTION);

        if (uploadException != null) {
            Throwable cause = uploadException.getCause();

            if (uploadException.isExceededFileSizeLimit() || uploadException.isExceededUploadRequestSizeLimit()) {

                throw new LARFileSizeException(cause);
            }

            throw new PortalException(cause);
        }
    }
 
Example 20
Project: lams   File: ModuleUtils.java   View Source Code Vote up 2 votes
/**
 * Return the current ModuleConfig object stored in request, if it exists,
 * null otherwise.
 * This method can be used by plugin to retrieve the current module config
 * object. If no moduleConfig is found, this means that the request haven't
 * hit the server throught the struts servlet. The appropriate module config
 * can be set and found with
 * <code>{@link RequestUtils#selectModule(HttpServletRequest, ServletContext)} </code>.
 * @param request The servlet request we are processing
 * @return the ModuleConfig object from request, or null if none is set in
 * the request.
 */
public ModuleConfig getModuleConfig(HttpServletRequest request) {
	return (ModuleConfig) request.getAttribute(Globals.MODULE_KEY);
}