javax.servlet.ServletResponse Java Examples

The following examples show how to use javax.servlet.ServletResponse. 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 Project: SpringBoot-Shiro-Vue   Author: Heeexy   File: AjaxPermissionsAuthorizationFilter.java    License: MIT License 7 votes vote down vote up
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
	JSONObject jsonObject = new JSONObject();
	jsonObject.put("code", ErrorEnum.E_20011.getErrorCode());
	jsonObject.put("msg", ErrorEnum.E_20011.getErrorMsg());
	PrintWriter out = null;
	HttpServletResponse res = (HttpServletResponse) response;
	try {
		res.setCharacterEncoding("UTF-8");
		res.setContentType("application/json");
		out = response.getWriter();
		out.println(jsonObject);
	} catch (Exception e) {
	} finally {
		if (null != out) {
			out.flush();
			out.close();
		}
	}
	return false;
}
 
Example #2
Source Project: super-cloudops   Author: wl4g   File: AbstractClientIamAuthenticationFilter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * determine success redirect URL
 * 
 * @param token
 * @param subject
 * @param request
 * @param response
 * @return
 */
protected String determineSuccessRedirectUrl(AuthenticationToken token, Subject subject, ServletRequest request,
		ServletResponse response) {
	// Priority obtain redirectURL from request.
	String successUrl = getRedirectUrl(request);
	if (isBlank(successUrl)) {
		// Secondary get remembered redirectURL.
		successUrl = getClearSavedRememberUrl(toHttp(request));
		if (isBlank(successUrl)) {
			// Fallback get the configured redirectURL as the default.
			successUrl = config.getSuccessUri();
		}
	}

	// Determine successUrl.
	successUrl = configurer.decorateAuthenticateSuccessUrl(successUrl, token, subject, request, response);
	notNull(successUrl, "'successUrl' must not be null");
	return cleanURI(successUrl); // Check & cleanup.
}
 
Example #3
Source Project: quarkus-http   Author: quarkusio   File: LoginFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest)request;
    String username = req.getHeader("username");
    String password = req.getHeader("password");
    if(username == null) {
        chain.doFilter(request, response);
        return;
    }
    try {
        req.login(username, password);
        chain.doFilter(request, response);
    } catch (ServletException e) {
        ((HttpServletResponse)response).setStatus(StatusCodes.UNAUTHORIZED);
    }
}
 
Example #4
Source Project: Tomcat7.0.67   Author: tryandcatch   File: InstanceSupport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Notify all lifecycle event listeners that a particular event has
 * occurred for this Container.  The default implementation performs
 * this notification synchronously using the calling thread.
 *
 * @param type Event type
 * @param servlet The relevant Servlet for this event
 * @param request The servlet request we are processing
 * @param response The servlet response we are processing
 * @param exception Exception that occurred
 */
public void fireInstanceEvent(String type, Servlet servlet,
                              ServletRequest request,
                              ServletResponse response,
                              Throwable exception) {

    if (listeners.length == 0)
        return;

    InstanceEvent event = new InstanceEvent(wrapper, servlet, type,
                                            request, response, exception);
    InstanceListener interested[] = listeners;
    for (int i = 0; i < interested.length; i++)
        interested[i].instanceEvent(event);

}
 
Example #5
Source Project: youkefu   Author: zhangyanbo2007   File: DelegateRequestMatchingFilter.java    License: Apache License 2.0 6 votes vote down vote up
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
     HttpServletRequest request = (HttpServletRequest) req;
     boolean matchAnyRoles = false ;
     for(RequestMatcher anyRequest : ignoredRequests ){
    	 if(anyRequest.matches(request)){
    		 matchAnyRoles = true ;
    	 }
     }
     User user = (User) request.getSession().getAttribute(UKDataContext.USER_SESSION_NAME) ;
     if(matchAnyRoles){
    	 if(user !=null && "0".equals(user.getUsertype())){
    		 chain.doFilter(req,resp);
    	 }else{
     	 //重定向到 无权限执行操作的页面
     	 HttpServletResponse response = (HttpServletResponse) resp ;
     	 response.sendRedirect("/?msg=security");
    	 }
     }else{
    	 try{
    		 chain.doFilter(req,resp);
    	 }catch(ClientAbortException ex){
    		 //Tomcat异常,不做处理
    	 }
     }
}
 
Example #6
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: RequestFilter.java    License: MIT License 6 votes vote down vote up
/**
 * Perform the filtering that has been configured for this Filter, matching
 * against the specified request property.
 *
 * @param property The request property on which to filter
 * @param request The servlet request to be processed
 * @param response The servlet response to be processed
 * @param chain The filter chain
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
protected void process(String property, ServletRequest request,
        ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (isAllowed(property)) {
        chain.doFilter(request, response);
    } else {
        if (response instanceof HttpServletResponse) {
            if (getLogger().isDebugEnabled()) {
                getLogger().debug(sm.getString("requestFilter.deny",
                        ((HttpServletRequest) request).getRequestURI(), property));
            }
            ((HttpServletResponse) response).sendError(denyStatus);
        } else {
            sendErrorWhenNotHttp(response);
        }
    }
}
 
Example #7
Source Project: radar   Author: geekshop   File: AuthFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
		throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest) req;
	HttpServletResponse response = (HttpServletResponse) resp;
	String uri = request.getRequestURI();
	if (skipUri(uri)) {
		chain.doFilter(request, response);
	} else {
		try {
			Cookie cookie = CookieUtil.getCookie(request, "userSessionId");
			if (cookie == null) {
				response.sendRedirect("/login");
			} else {
				String userId = DesUtil.decrypt(cookie.getValue());
				req.setAttribute("userSessionId", userId);					
				chain.doFilter(request, response);
			}

		} catch (Exception e) {
			log.error("login fail", e);
			response.sendRedirect("/login");
		}
	}
}
 
Example #8
Source Project: ee8-sandbox   Author: hantsy   File: HiddenHttpMethodFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
        throws ServletException, IOException {
    log.log(Level.INFO, "entering HttpHiddenFilter...");
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    String paramValue = request.getParameter(this.methodParam);
    log.log(Level.INFO, "paramValue @" + paramValue);
    log.log(Level.INFO, "request method @" + request.getMethod());

    if ("POST".equals(request.getMethod()) && paramValue != null && paramValue.trim().length() > 0) {
        String method = paramValue.toUpperCase(Locale.ENGLISH);
        HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, method);
        filterChain.doFilter(wrapper, response);
    } else {
        filterChain.doFilter(request, response);
    }
}
 
Example #9
Source Project: lumongo   Author: lumongo   File: GWTCacheControlFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

	HttpServletRequest httpRequest = (HttpServletRequest) request;
	String requestURI = httpRequest.getRequestURI();

	if (requestURI.contains(".nocache.")) {
		Date now = new Date();
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		httpResponse.setDateHeader("Date", now.getTime());
		// one day old
		httpResponse.setDateHeader("Expires", now.getTime() - 86400000L);
		httpResponse.setHeader("Pragma", "no-cache");
		httpResponse.setHeader("Cache-control", "no-cache, no-store, must-revalidate");
	}

	filterChain.doFilter(request, response);
}
 
Example #10
Source Project: cassandra-reaper   Author: thelastpickle   File: ShiroJwtVerifyingFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testIsRemembered() throws Exception {
  try {
    Subject subject = Mockito.mock(Subject.class);
    Mockito.when(subject.getPrincipal()).thenReturn(Mockito.mock(Object.class));
    Mockito.when(subject.isRemembered()).thenReturn(true);
    ThreadContext.bind(subject);
    ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter();

    Assertions.assertThat(
        filter.isAccessAllowed(
            Mockito.mock(HttpServletRequest.class),
            Mockito.mock(ServletResponse.class),
            Mockito.mock(Object.class)))
        .isTrue();
  } finally {
    ThreadContext.unbindSubject();
  }
}
 
Example #11
Source Project: microservice-integration   Author: keets2012   File: CustomSecurityFilter.java    License: MIT License 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    logger.info("doFilter in Security ");

    FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain);
    //beforeInvocation会调用SecureResourceDataSource中的逻辑
    InterceptorStatusToken token = super.beforeInvocation(fi);
    try {
        fi.getChain().doFilter(fi.getRequest(), fi.getResponse());

        //执行下一个拦截器
    } finally {

        logger.info("through filter");
        super.afterInvocation(token, null);
        //throw new AccessDeniedException("no right");

    }

}
 
Example #12
Source Project: bamboobsc   Author: billchen198318   File: GreenStepBaseFormAuthenticationFilter.java    License: Apache License 2.0 6 votes vote down vote up
protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
	GreenStepBaseUsernamePasswordToken token = 
			(GreenStepBaseUsernamePasswordToken) this.createToken(request, response);
	try {
		this.doCaptchaValidate((HttpServletRequest)request, token);
		
		ShiroLoginSupport loginSupport = new ShiroLoginSupport();
		AccountVO account = loginSupport.queryUserValidate(token.getUsername());
		
		Subject subject = this.getSubject(request, response);
		subject.login(token);
		
		if (this.isLoginLdapMode() && account==null) { // is no account data in DataBase, create it.
			account = this.createUserDataLdapLoginMode(token.getUsername(), new String(token.getPassword()));
		}			
		// set session
		this.setUserSession((HttpServletRequest)request, (HttpServletResponse)response, account);
		return this.onLoginSuccess(token, subject, request, response);			
	} catch (AuthenticationException e) {
		// clear session	
		logger.warn( e.getMessage().toString() );			
		UserAccountHttpSessionSupport.remove( (HttpServletRequest)request );
		this.getSubject(request, response).logout();
		return this.onLoginFailure(token, e, request, response);
	}		
}
 
Example #13
Source Project: seata-samples   Author: seata   File: SeataFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) servletRequest;
    String xid = req.getHeader(RootContext.KEY_XID.toLowerCase());
    boolean isBind = false;
    if (StringUtils.isNotBlank(xid)) {
        RootContext.bind(xid);
        isBind = true;
    }
    try {
        filterChain.doFilter(servletRequest, servletResponse);
    } finally {
        if (isBind) {
            RootContext.unbind();
        }
    }
}
 
Example #14
Source Project: heroic   Author: spotify   File: ShutdownFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(
    final ServletRequest request, final ServletResponse response, final FilterChain chain
) throws IOException, ServletException {
    if (!stopping.get()) {
        chain.doFilter(request, response);
        return;
    }

    final HttpServletResponse httpResponse = (HttpServletResponse) response;

    final InternalErrorMessage info =
        new InternalErrorMessage("Heroic is shutting down", Status.SERVICE_UNAVAILABLE);

    httpResponse.setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode());
    httpResponse.setContentType(CONTENT_TYPE);

    // intercept request
    try (final ByteArrayOutputStream output = new ByteArrayOutputStream(4096)) {
        final OutputStreamWriter writer = new OutputStreamWriter(output, Charsets.UTF_8);
        mapper.writeValue(writer, info);
        response.setContentLength(output.size());
        output.writeTo(httpResponse.getOutputStream());
    }
}
 
Example #15
Source Project: spring-analysis-note   Author: Vip-Augus   File: WebApplicationContextUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Register web-specific scopes ("request", "session", "globalSession", "application")
 * with the given BeanFactory, as used by the WebApplicationContext.
 * @param beanFactory the BeanFactory to configure
 * @param sc the ServletContext that we're running within
 */
public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory,
		@Nullable ServletContext sc) {

	beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope());
	beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope());
	if (sc != null) {
		ServletContextScope appScope = new ServletContextScope(sc);
		beanFactory.registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope);
		// Register as ServletContext attribute, for ContextCleanupListener to detect it.
		sc.setAttribute(ServletContextScope.class.getName(), appScope);
	}

	beanFactory.registerResolvableDependency(ServletRequest.class, new RequestObjectFactory());
	beanFactory.registerResolvableDependency(ServletResponse.class, new ResponseObjectFactory());
	beanFactory.registerResolvableDependency(HttpSession.class, new SessionObjectFactory());
	beanFactory.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory());
	if (jsfPresent) {
		FacesDependencyRegistrar.registerFacesDependencies(beanFactory);
	}
}
 
Example #16
Source Project: java-technology-stack   Author: codeEngraver   File: RequestLoggingFilterTests.java    License: MIT License 6 votes vote down vote up
@Test
public void payloadInputStream() throws Exception {
	filter.setIncludePayload(true);

	final MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
	MockHttpServletResponse response = new MockHttpServletResponse();

	final byte[] requestBody = "Hello World".getBytes("UTF-8");
	request.setContent(requestBody);

	FilterChain filterChain = new FilterChain() {
		@Override
		public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse)
				throws IOException, ServletException {
			((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
			byte[] buf = FileCopyUtils.copyToByteArray(filterRequest.getInputStream());
			assertArrayEquals(requestBody, buf);
		}
	};

	filter.doFilter(request, response, filterChain);

	assertNotNull(filter.afterRequestMessage);
	assertTrue(filter.afterRequestMessage.contains("Hello World"));
}
 
Example #17
Source Project: hbase   Author: apache   File: TestStaticUserWebFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFilter() throws Exception {
  FilterConfig config = mockConfig("myuser");
  StaticUserFilter suf = new StaticUserFilter();
  suf.init(config);

  ArgumentCaptor<HttpServletRequestWrapper> wrapperArg =
    ArgumentCaptor.forClass(HttpServletRequestWrapper.class);

  FilterChain chain = mock(FilterChain.class);

  suf.doFilter(mock(HttpServletRequest.class), mock(ServletResponse.class),
      chain);

  Mockito.verify(chain).doFilter(wrapperArg.capture(), Mockito.<ServletResponse>anyObject());

  HttpServletRequestWrapper wrapper = wrapperArg.getValue();
  assertEquals("myuser", wrapper.getUserPrincipal().getName());
  assertEquals("myuser", wrapper.getRemoteUser());

  suf.destroy();
}
 
Example #18
Source Project: cassandra-reaper   Author: thelastpickle   File: ShiroJwtVerifyingFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthorization2() throws Exception {
  try {
    SecurityUtils.setSecurityManager(new DefaultSecurityManager());
    new ShiroJwtProvider(Mockito.mock(AppContext.class));
    HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
    Mockito.when(req.getHeader("Authorization")).thenReturn("Bearer eyJhbGciOiJIUzI1NiJ9");
    ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter();

    Assertions.assertThat(
        filter.isAccessAllowed(
            req,
            Mockito.mock(ServletResponse.class),
            Mockito.mock(Object.class)))
        .isFalse();
  } finally {
    ThreadContext.unbindSubject();
    ThreadContext.unbindSecurityManager();
  }
}
 
Example #19
Source Project: frpMgr   Author: Zo3i   File: FormAuthenticationFilter.java    License: MIT License 6 votes vote down vote up
/**
 * 登录成功调用事件
 */
@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {

	// 登录成功后初始化授权信息并处理登录后的操作
	authorizingRealm.onLoginSuccess((LoginInfo)subject.getPrincipal(), (HttpServletRequest) request);
	
	// 登录操作如果是Ajax操作,直接返回登录信息字符串。
	if (ServletUtils.isAjaxRequest((HttpServletRequest) request)) {
		request.getRequestDispatcher(getSuccessUrl()).forward(request, response); // AJAX不支持Redirect改用Forward
	}
	// 登录成功直接返回到首页
	else {
		String url = request.getParameter("__url");
		if (StringUtils.isNotBlank(url)) {
			WebUtils.issueRedirect(request, response, url, null, true);
		} else {
			WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true);
		}
	}
	return false;
}
 
Example #20
Source Project: cms   Author: myxzjie   File: ClientPathMatchingFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    String cid = req.getHeader(ConstantsUtils.ET_CID);

    if (cid == null) {
        cid = req.getParameter(ConstantsUtils.CID);
    }

    if (cid == null) {
        cid = ConstantsUtils.SITE_ID_DEFAULT;
    }

    String key = ConstantsUtils.SITE_ID_KEY + cid;
    Site site = SystemCacheManager.get(key, Site.class);

    if (site == null) {
        site = siteService.get(Long.parseLong(cid));
        SystemCacheManager.put(key, site);
    }

    req.setAttribute("cid", cid);
    return super.preHandle(req, res);
}
 
Example #21
Source Project: civism-sso   Author: civism   File: TokenUserFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected boolean onAccessDenied(ServletRequest req, ServletResponse resp, Object mappedValue) throws Exception {
    HttpServletResponse response = (HttpServletResponse) resp;
    PrintWriter out = null;
    try {
        out = response.getWriter();
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setContentType("application/json");
        out.write(JSON.toJSONString(new SsoResponse(ErrorType.PATH_ERROR)));
    } catch (IOException e) {
        logger.error("error onAccessDenied", e);
        return false;
    } finally {
        if (out != null) {
            out.close();
        }
    }
    return false;
}
 
Example #22
Source Project: HttpSessionReplacer   Author: AmadeusITGroup   File: TestSessionHelpers.java    License: MIT License 6 votes vote down vote up
@Test
public void testPrepareWappedRequestDifferentServletContext() {
  HttpRequestWrapper request = mock(HttpRequestWrapper.class);
  ServletResponse response = mock(HttpServletResponse.class);
  ServletContext originalServletContext = mock(ServletContext.class);
  originalServletContext.setAttribute(SessionHelpers.REQUEST_WRAPPED_ATTRIBUTE, request);
  when(originalServletContext.getAttribute(Attributes.SESSION_MANAGER)).thenReturn(sessionManager);
  ServletRequest reWrappedRequest = mock(HttpServletRequest.class);
  when(reWrappedRequest.getAttribute(SessionHelpers.REQUEST_WRAPPED_ATTRIBUTE)).thenReturn(request);
  ServletContext another = mock(ServletContext.class);
  when(another.getAttribute(SessionHelpers.SESSION_HELPERS)).thenReturn(new SessionHelpers());
  SessionManager anotherSessionManager = mock(SessionManager.class);
  SessionConfiguration anotherSessionConfiguration = new SessionConfiguration();
  when(sessionManager.getConfiguration()).thenReturn(anotherSessionConfiguration);
  when(another.getAttribute(Attributes.SESSION_MANAGER)).thenReturn(anotherSessionManager);
  when(reWrappedRequest.getServletContext()).thenReturn(another);
  ServletRequest result = SessionHelpersFacade.prepareRequest(reWrappedRequest, response, originalServletContext);
  assertNotNull(result);
  assertNotSame(reWrappedRequest, result);
  assertNotSame(request, result);
  assertTrue(result instanceof HttpRequestWrapper);
}
 
Example #23
Source Project: boubei-tss   Author: boubei-com   File: Filter2CatchException.java    License: Apache License 2.0 6 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
	
    try {
        chain.doFilter(request, response);
    } 
    catch (Exception e) {
        ExceptionEncoder.encodeException(response, e); // 捕获异常并转换成XML输出
    } 
    finally {
    	// 出现异常后,Filter3Context将没机会销毁Context,需要在此销毁Context
    	if( Context.getToken() != null ) {
    		Context.destroy(); 
			Context.setToken(null);  /* 在web环境下需要每次调用结束后重置当前线程的Token值,以免串号 */
    	}
    }
}
 
Example #24
Source Project: quarkus-http   Author: quarkusio   File: RequestDispatcherImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void forward(final ServletRequest request, final ServletResponse response) throws ServletException, IOException {
    if(System.getSecurityManager() != null) {
        try {
            AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                @Override
                public Object run() throws Exception {
                    forwardImplSetup(request, response);
                    return null;
                }
            });
        } catch (PrivilegedActionException e) {
            if(e.getCause() instanceof ServletException) {
                throw (ServletException)e.getCause();
            } else if(e.getCause() instanceof IOException) {
                throw (IOException)e.getCause();
            } else if(e.getCause() instanceof RuntimeException) {
                throw (RuntimeException)e.getCause();
            } else {
                throw new RuntimeException(e.getCause());
            }
        }
    } else {
        forwardImplSetup(request, response);
    }
}
 
Example #25
Source Project: Tomcat7.0.67   Author: tryandcatch   File: ApplicationDispatcher.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Include the response from another resource in the current response.
 * Any runtime exception, IOException, or ServletException thrown by the
 * called servlet will be propagated to the caller.
 *
 * @param request The servlet request that is including this one
 * @param response The servlet response to be appended to
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 */
@Override
public void include(ServletRequest request, ServletResponse response)
    throws ServletException, IOException
{
    if (Globals.IS_SECURITY_ENABLED) {
        try {
            PrivilegedInclude dp = new PrivilegedInclude(request,response);
            AccessController.doPrivileged(dp);
        } catch (PrivilegedActionException pe) {
            Exception e = pe.getException();

            if (e instanceof ServletException)
                throw (ServletException) e;
            throw (IOException) e;
        }
    } else {
        doInclude(request, response);
    }
}
 
Example #26
Source Project: knox   Author: apache   File: InstrumentedGatewayFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
  Timer.Context timerContext = this.timer(servletRequest).time();
  try {
    gatewayFilter.doFilter(servletRequest, servletResponse);
  } finally {
    timerContext.stop();
  }
}
 
Example #27
Source Project: seezoon-framework-all   Author: 734839030   File: UserFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
	HttpServletRequest req = (HttpServletRequest) request;
	HttpServletResponse res = (HttpServletResponse) response;
	// 跨域的options 请求直接过
	if (RequestMethod.OPTIONS.name().equalsIgnoreCase(req.getMethod())) {
		return true;
	} else {
		res.setStatus(HttpStatus.NEED_LOGIN.getValue());
		//不走后续shiro 默认逻辑
		return false;
	}
	//return super.onAccessDenied(request, response);
}
 
Example #28
Source Project: spring-analysis-note   Author: Vip-Augus   File: ServletResponseMethodArgumentResolverTests.java    License: MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
	resolver = new ServletResponseMethodArgumentResolver();
	mavContainer = new ModelAndViewContainer();
	servletResponse = new MockHttpServletResponse();
	webRequest = new ServletWebRequest(new MockHttpServletRequest(), servletResponse);

	method = getClass().getMethod("supportedParams", ServletResponse.class, OutputStream.class, Writer.class);
}
 
Example #29
Source Project: aws-serverless-java-container   Author: awslabs   File: ContextResource.java    License: Apache License 2.0 5 votes vote down vote up
public static void setCookie(ServletRequest request, ServletResponse response, String name, String value,
                             boolean set, boolean global, boolean bSecureCookie, Integer maxAge, boolean httpOnly) {
    Cookie ck = new Cookie(name, value);

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    if (httpOnly) {
        ck.setHttpOnly(true);
    }

    if (set) {
        if (maxAge != null) {
            ck.setMaxAge(maxAge.intValue());
        } else {
            ck.setMaxAge(-1);
        }
    } else {
        ck.setMaxAge(0);
    }
    ck.setPath("/");

    // for local and fngn envs., we should not set cookie as a secure cookie
    if (bSecureCookie) {
        ck.setSecure(true);
    }

    ck.setDomain(COOKIE_DOMAIN);


    ((HttpServletResponse) response).addCookie(ck);
}
 
Example #30
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: RemoteIpFilter.java    License: MIT License 5 votes vote down vote up
/**
 * Wrap the incoming <code>request</code> in a {@link XForwardedRequest} if the http header <code>x-forwarded-for</code> is not empty.
 * {@inheritDoc}
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        doFilter((HttpServletRequest)request, (HttpServletResponse)response, chain);
    } else {
        chain.doFilter(request, response);
    }
}