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

The following are Jave code examples for showing how to use removeAttribute() 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: validator-web   File: AbstractView.java   View Source Code Vote up 6 votes
/**
 * Expose the model objects in the given map as request attributes.
 * Names will be taken from the model Map.
 * This method is suitable for all resources reachable by {@link javax.servlet.RequestDispatcher}.
 * @param model Map of model objects to expose
 * @param request current HTTP request
 */
protected void exposeModelAsRequestAttributes(Map<String, Object> model, HttpServletRequest request) throws Exception {
    for (Map.Entry<String, Object> entry : model.entrySet()) {
        String modelName = entry.getKey();
        Object modelValue = entry.getValue();
        if (modelValue != null) {
            request.setAttribute(modelName, modelValue);
            if (logger.isDebugEnabled()) {
                logger.debug("Added model object '" + modelName + "' of type [" + modelValue.getClass().getName() +
                        "] to request in view");
            }
        }
        else {
            request.removeAttribute(modelName);
            if (logger.isDebugEnabled()) {
                logger.debug("Removed model object '" + modelName +
                        "' from request in view");
            }
        }
    }
}
 
Example 2
Project: Equella   File: RequestDispatchFilter.java   View Source Code Vote up 6 votes
@SuppressWarnings("unchecked")
private void runCallbacks(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
{
	List<WebFilterCallback> callbacks = (List<WebFilterCallback>) httpRequest.getAttribute(CALLBACKS_KEY);
	httpRequest.removeAttribute(CALLBACKS_KEY);
	if( callbacks != null )
	{
		// Run them in reverse, don't let one callback stop the rest from happening
		for( int i = callbacks.size() - 1; i >= 0; i-- )
		{
			try
			{
				callbacks.get(i).afterServlet(httpRequest, httpResponse);
			}
			catch( Exception e )
			{
				LOGGER.error("Error running callback", e);
			}
		}
	}
}
 
Example 3
Project: Mastering-Java-EE-Development-with-WildFly   File: EventListenerServlet.java   View Source Code Vote up 5 votes
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	response.setContentType("text/html;charset=UTF-8");
	PrintWriter out = response.getWriter();
	out.println("<!DOCTYPE html>");
	out.println("<html>");
	out.println("<head>");
	out.println("<title>Servlet Event Listeners</title>");
	out.println("</head>");
	out.println("<body>");
	out.println("<h1>Servlet Event Listeners</h1>");
	out.println("<h2>Setting, updating, and removing ServletContext Attributes</h2>");
	request.getServletContext().setAttribute("attribute1", "attribute-value1");
	request.getServletContext().setAttribute("attribute1", "attribute-updated-value1");
	request.getServletContext().removeAttribute("attribute1");
	out.println("done");
	out.println("<h2>Setting, updating, and removing HttpSession Attributes</h2>");
	request.getSession(true).setAttribute("attribute1", "attribute-value1");
	request.getSession().setAttribute("attribute1", "attribute-updated-value1");
	request.getSession().removeAttribute("attribute1");
	out.println("done");
	out.println("<h2>Setting, updating, and removing ServletRequest Attributes</h2>");
	request.setAttribute("attribute1", "attribute-value1");
	request.setAttribute("attribute1", "attribute-updated-value1");
	request.removeAttribute("attribute1");
	out.println("done");
	out.println("<h2>Invalidating session</h2>");
	request.getSession().invalidate();
	out.println("done");
	out.println("<br><br>Check output in server log");
	out.println("</body>");
	out.println("</html>");
}
 
Example 4
Project: java_springboot   File: DemoInterceptor.java   View Source Code Vote up 5 votes
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    //super.postHandle(request, response, handler, modelAndView);
    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 5
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 6
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 7
Project: lams   File: ModuleUtils.java   View Source Code Vote up 5 votes
/**
 * Select the module to which the specified request belongs, and
 * add corresponding request attributes to this request.
 *
 * @param prefix The module prefix of the desired module
 * @param request The servlet request we are processing
 * @param context The ServletContext for this web application
 */
public void selectModule(
    String prefix,
    HttpServletRequest request,
    ServletContext context) {

    // Expose the resources for this module
    ModuleConfig config = getModuleConfig(prefix, context);

    if (config != null) {
        request.setAttribute(Globals.MODULE_KEY, config);
    } else {
        request.removeAttribute(Globals.MODULE_KEY);
    }

    MessageResourcesConfig[] mrConfig = config.findMessageResourcesConfigs();
    for(int i = 0; i < mrConfig.length; i++) {
      String key = mrConfig[i].getKey();
      MessageResources resources =
        (MessageResources) context.getAttribute(key + prefix);
      if (resources != null) {
          request.setAttribute(key, resources);
      } else {
          request.removeAttribute(key);
      }
    }
}
 
Example 8
Project: lams   File: Action.java   View Source Code Vote up 5 votes
/**
 * Adds the specified messages keys into the appropriate request
 * attribute for use by the &lt;html:messages&gt; tag (if
 * messages="true" is set), if any messages are required.
 * Initialize the attribute if it has not already been.
 * Otherwise, ensure that the request attribute is not set.
 *
 * @param request   The servlet request we are processing
 * @param messages  Messages object
 * @since Struts 1.2.1
 */
protected void addMessages(
	HttpServletRequest request,
	ActionMessages messages) {

	if (messages == null){
		//	bad programmer! *slap*
		return;
	}

	// get any existing messages from the request, or make a new one
	ActionMessages requestMessages = (ActionMessages) request.getAttribute(Globals.MESSAGE_KEY);
	if (requestMessages == null){
		requestMessages = new ActionMessages();
	}
	// add incoming messages
	requestMessages.add(messages);

	// if still empty, just wipe it out from the request
	if (requestMessages.isEmpty()) {
		request.removeAttribute(Globals.MESSAGE_KEY);
		return;
	}

	// Save the messages
	request.setAttribute(Globals.MESSAGE_KEY, requestMessages);
}
 
Example 9
Project: lams   File: Action.java   View Source Code Vote up 5 votes
/**
 * Adds the specified errors keys into the appropriate request attribute
    * for use by the &lt;html:errors&gt; tag, if any messages are required.
 * Initialize the attribute if it has not already been. Otherwise, ensure
    * that the request attribute is not set.
 *
 * @param request   The servlet request we are processing
 * @param errors  Errors object
 * @since Struts 1.2.1
 */
protected void addErrors(
	HttpServletRequest request,
	ActionMessages errors) {

	if (errors == null){
		//	bad programmer! *slap*
		return;
	}

	// get any existing errors from the request, or make a new one
	ActionMessages requestErrors = (ActionMessages)request.getAttribute(Globals.ERROR_KEY);
	if (requestErrors == null){
		requestErrors = new ActionMessages();
	}
	// add incoming errors
	requestErrors.add(errors);

	// if still empty, just wipe it out from the request
	if (requestErrors.isEmpty()) {
		request.removeAttribute(Globals.ERROR_KEY);
		return;
	}

	// Save the errors
	request.setAttribute(Globals.ERROR_KEY, requestErrors);
}
 
Example 10
Project: lams   File: Action.java   View Source Code Vote up 5 votes
/**
 * <p>Save the specified error messages keys into the appropriate request
 * attribute for use by the &lt;html:errors&gt; tag, if any messages
 * are required. Otherwise, ensure that the request attribute is not
 * created.</p>
 *
 * @param request The servlet request we are processing
 * @param errors Error messages object
 * @since Struts 1.2
 */
protected void saveErrors(HttpServletRequest request, ActionMessages errors) {

    // Remove any error messages attribute if none are required
    if ((errors == null) || errors.isEmpty()) {
        request.removeAttribute(Globals.ERROR_KEY);
        return;
    }

    // Save the error messages we need
    request.setAttribute(Globals.ERROR_KEY, errors);

}
 
Example 11
Project: lams   File: Action.java   View Source Code Vote up 5 votes
/**
 * <p>Save the specified messages keys into the appropriate request
 * attribute for use by the &lt;html:messages&gt; tag (if
 * messages="true" is set), if any messages are required. Otherwise,
 * ensure that the request attribute is not created.</p>
 *
 * @param request The servlet request we are processing.
 * @param messages The messages to save. <code>null</code> or empty
 * messages removes any existing ActionMessages in the request.
 *
 * @since Struts 1.1
 */
protected void saveMessages(
    HttpServletRequest request,
    ActionMessages messages) {

    // Remove any messages attribute if none are required
    if ((messages == null) || messages.isEmpty()) {
        request.removeAttribute(Globals.MESSAGE_KEY);
        return;
    }

    // Save the messages we need
    request.setAttribute(Globals.MESSAGE_KEY, messages);
}
 
Example 12
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 13
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 14
Project: errorest-spring-boot-starter   File: SecurityErrorDataProvider.java   View Source Code Vote up 5 votes
@Override
public ErrorData getErrorData(T ex, HttpServletRequest request) {
    if (request.getAttribute(CONTROLLER_ERROR_HANDLING_ATTRIBUTE) != null) {
        request.removeAttribute(CONTROLLER_ERROR_HANDLING_ATTRIBUTE);
        throw (RuntimeException) ex;
    }
    return buildErrorData(ex, getHeadersAsText(request))
            .withRequestMethod(request.getMethod())
            .withRequestUri(request.getRequestURI())
            .build();
}
 
Example 15
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 16
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 17
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 18
Project: BasicsProject   File: SystemLogAop.java   View Source Code Vote up 4 votes
/**配置环绕通知,使用在方法aspect()上注册的切入点*/
@Around("aspect()")
public Object around(ProceedingJoinPoint pjd) {
	HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
       Object result = null;
       //执行目标方法
       try {
           //前置通知
           result = pjd.proceed();
           if(Statics.Record_System_Log){
           	if(result instanceof ReturnUtil){
           		List<JSONObject> operationLogs = ReflectHelperUtil.getInstance(result, "operation_logs");
           		if(operationLogs==null)operationLogs = new ArrayList<JSONObject>();
       			if(Statics.Record_Select_System_Log || (!Statics.Record_Select_System_Log && operationLogs.size()>0)){
           			if(request.getAttribute(Statics.SYSTEM_LOG_ID)!=null && !request.getAttribute(Statics.SYSTEM_LOG_ID).toString().equals("")){
           				//-----添加系统日志begin-----
           				JSONObject log = JSONObject.parseObject(request.getAttribute(Statics.SYSTEM_LOG_ID).toString());
           				log.put("result", JSONObject.toJSONString(result));
           				long systemLogId = Long.parseLong(AuthorityAnnotationInterceptor.myBaseService.add(null,log, "systemMapper.addSystemLog", true).getExtend_info().toString());
           				//-----添加系统日志end-----
           				JSONObject memberJson = StorageUtil.init(request.getSession()).getLoginMemberInfoJson();
           				if(memberJson!=null && operationLogs.size()>0){
           					for (int i = 0,length=operationLogs.size(); i < length; i++) {
								JSONObject operationLog = operationLogs.get(i);
								if(operationLog.getInteger("operation_type")!=3){
									//-----添加操作日志begin-----
									operationLog.put("system_log_id", systemLogId);
									operationLog.put("memberId", memberJson.getLong("id"));
									AuthorityAnnotationInterceptor.myBaseService.add(null,operationLog, "systemMapper.addOperationLog",true);
									//-----添加操作日志end-----
								}
							}
           				}
           			}
           		}
           	}
           }
           request.removeAttribute("Statics.SYSTEM_LOG_ID");
           //返回通知
       } catch (Throwable e) {
           //异常通知
       	if(result instanceof ReturnUtil){
       		result = ((ReturnUtil) result).addSeriousErrorMsg("发生异常:"+e.toString());
       	}else{
       		throw new RuntimeException(e);
       	}
       	e.printStackTrace();
       }
       //后置通知
       if(Statics.out_implement_time){
       	long implement_time =System.currentTimeMillis() - Long.parseLong(request.getAttribute("start_implement_time").toString());
       	System.out.println(request.getAttribute("implement_method_name")+"方法处理时间:"+implement_time+"毫秒。");
       }
       return result;
   }
 
Example 19
Project: oscm   File: IdPLogoutFilter.java   View Source Code Vote up 4 votes
/**
 * If the request contains a SAML 2.0 response, forward to the originally
 * requested resource is done. In case of service login, the request is
 * forwarded to an auto-submit page, to do the login in UserBean. <br/>
 * If the response does not contain a SAML 2.0 response, the next filter is
 * called. See web.xml for excluded url pattern.
 *
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain) throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    if (!httpRequest.getServletPath().matches(excludeUrlPattern)) {

        if (containsSamlResponse(httpRequest)) {
            httpRequest.setAttribute(Constants.REQ_ATTR_IS_SAML_FORWARD,
                    Boolean.TRUE);
            String samlResponse = httpRequest.getParameter("SAMLResponse");

            if (samlResponseExtractor.isFromLogout(samlResponse)) {
                try {
                    if (!samlLogoutResponseValidator.responseStatusCodeSuccessful(samlResponse)) {
                        httpRequest.setAttribute(
                                Constants.REQ_ATTR_ERROR_KEY,
                                BaseBean.ERROR_INVALID_SAML_RESPONSE_STATUS_CODE);
                        redirector.forward(httpRequest, httpResponse,
                                BaseBean.ERROR_PAGE);
                        return;
                    }
                    HttpSession currentSession = httpRequest.getSession();
                    getSsl().deletePlatformSession(currentSession.getId());
                    currentSession.invalidate();
                    httpRequest.removeAttribute("SAMLResponse");
                    httpRequest.setAttribute(Constants.REQ_ATTR_IS_SAML_FORWARD,
                            Boolean.FALSE);
                } catch (SAML2StatusCodeInvalidException e) {
                    httpRequest.setAttribute(
                            Constants.REQ_ATTR_ERROR_KEY,
                            BaseBean.ERROR_INVALID_SAML_RESPONSE);
                    redirector.forward(httpRequest, httpResponse,
                            BaseBean.ERROR_PAGE);
                    LOGGER.logError(Log4jLogger.SYSTEM_LOG, e,
                            ERROR_SAML2_INVALID_STATUS_CODE);
                    return;
                }
                String relayState = httpRequest.getParameter("RelayState");
                if (relayState != null) {
                    String forwardUrl = getForwardUrl(httpRequest, relayState);
                    ((HttpServletResponse) response).sendRedirect(forwardUrl);
                    return;
                }
                if (httpRequest
                        .getAttribute(Constants.REQ_ATTR_ERROR_KEY) != null) {
                    redirector.forward(httpRequest, httpResponse,
                            BaseBean.ERROR_PAGE);
                    return;
                }

                httpRequest.setAttribute(Constants.REQ_ATTR_IS_SAML_FORWARD,
                        Boolean.FALSE);
            }
        }
    }

    chain.doFilter(request, response);
}
 
Example 20
Project: lams   File: NestedPropertyHelper.java   View Source Code Vote up 4 votes
/**
 * Deletes the nested reference from the request object.
 * @param request object to remove the reference from
 */
public static final void deleteReference(HttpServletRequest request) {
  // delete the reference
  request.removeAttribute(NESTED_INCLUDES_KEY);
}