当前位置: 首页>>代码示例>>Java>>正文


Java ServletResponse类代码示例

本文整理汇总了Java中javax.servlet.ServletResponse的典型用法代码示例。如果您正苦于以下问题:Java ServletResponse类的具体用法?Java ServletResponse怎么用?Java ServletResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ServletResponse类属于javax.servlet包,在下文中一共展示了ServletResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: doFilter

import javax.servlet.ServletResponse; //导入依赖的package包/类
@Override
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
    throws IOException, ServletException {
  final HttpServletRequest request = (HttpServletRequest) req;

  final String authHeader = request.getHeader("Authorization");
  if (authHeader == null || !authHeader.startsWith("Bearer ")) {
    ExceptionUtils.createUnauthorizedException("Missing or invalid Authorization header.", res);
    return;
  }

  try {
    final String token = authHeader.substring(7); // The part after "Bearer "
    final Claims claims =
        Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody();
    request.setAttribute("claims", claims);
  } catch (final Exception e) {
    ExceptionUtils.createUnauthorizedException("Invalid token", res);
    return;
  }

  chain.doFilter(req, res);
}
 
开发者ID:stefanstaniAIM,项目名称:IPPR2016,代码行数:24,代码来源:JwtFilter.java

示例2: doFilter

import javax.servlet.ServletResponse; //导入依赖的package包/类
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;

    request.setCharacterEncoding(encoding);
    response.setCharacterEncoding(encoding);

    String target = request.getRequestURI();
    if (contextPathLength != 0) {
        target = target.substring(contextPathLength);
    }

    boolean handle = actionHandler.handle(target, request, response);

    if (!handle) {// 没有处理则放行
        chain.doFilter(request, response);
    }
}
 
开发者ID:Xlongshu,项目名称:EasyController,代码行数:20,代码来源:ActionDispatcherFilter.java

示例3: doFilter

import javax.servlet.ServletResponse; //导入依赖的package包/类
public void doFilter(ServletRequest request, ServletResponse response,
		FilterChain chain) throws IOException, ServletException {
	try {
		getDelegateShrioFilter().doFilter(request, response, chain);
	} catch (UnknownSessionException e) {
		System.out.println(e);
		if(HttpUtils.isAsynRequest((HttpServletRequest) request)){
			Result<Object> result = new Result<Object>();
			result.setSuccess(false);
			result.setMessage("对不起,您的会话已过期,请重新登录!");
			HttpUtils.asynOutputResponse((HttpServletResponse) response, ContentType.APPLICATION_JSON, JsonUtils.object2Json(result));
		}else{
			throw e;
		}
	}
}
 
开发者ID:penggle,项目名称:xproject,代码行数:17,代码来源:DynamicUrlPermissionsShiroFilter.java

示例4: doFilter

import javax.servlet.ServletResponse; //导入依赖的package包/类
@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
		final FilterChain chain) throws IOException, ServletException {
	if (request instanceof HttpServletRequest) {
		final HttpServletRequest req = ((HttpServletRequest) request);
		final HttpServletResponse res = ((HttpServletResponse) response);
		final String header = req.getHeader(SimpleAuth.HTTP_HEADER);
		if (header != null) {
			final String[] sp = header.split(" ");
			// Authentication: torch TOKEN
			if (sp.length == 2) {
				final String scheme = sp[0], param = sp[1];
				if (SimpleAuth.SCHEME.equals(scheme)) {
					if (sa.verify(param)) {
						chain.doFilter(request, response);
						return;
					}
				}
			}
		}
		if (!res.isCommitted()) {
			final String err = "FORBIDDEN\r\n";
			res.reset();
			res.setStatus(HttpServletResponse.SC_FORBIDDEN);
			res.setContentLength(err.length());
			res.setContentType("text/plain");
			res.setCharacterEncoding("ISO-8859-1");
			res.setHeader("Pragma", "no-cache");
			res.setHeader("Cache-Control", "private, no-cache, no-store, must-revalidate");
			res.setHeader(getClass().getSimpleName(), "deny");
			res.getWriter().print(err);
			return;
		}
	}
	if (!response.isCommitted()) {
		response.reset();
	}
	throw new ServletException(new UnsupportedOperationException());
}
 
开发者ID:ggrandes,项目名称:simpleauth,代码行数:40,代码来源:SimpleAuthFilter.java

示例5: doFilter

import javax.servlet.ServletResponse; //导入依赖的package包/类
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
    throws IOException, ServletException {
    try {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String jwt = resolveToken(httpServletRequest);
        if (StringUtils.hasText(jwt)) {
            if (this.tokenProvider.validateToken(jwt)) {
                Authentication authentication = this.tokenProvider.getAuthentication(jwt);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    } catch (ExpiredJwtException eje) {
        log.info("Security exception for user {} - {}", eje.getClaims().getSubject(), eje.getMessage());
        ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
开发者ID:klask-io,项目名称:klask-io,代码行数:19,代码来源:JWTFilter.java

示例6: doFilter

import javax.servlet.ServletResponse; //导入依赖的package包/类
public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest) servletRequest;
	if (isWhiteReq(request.getRequestURI())) {
		chain.doFilter(request, response);
	} else {
		String token = request.getHeader("token");
		if (StringUtils.isNotBlank(token)) {
			try {
				Token tokenInfo = TokenUtil.getTokenInfo(token);
				if (tokenInfo != null) {
					Long now = System.currentTimeMillis();
					if (now - tokenInfo.getTime() < 1000 * 60 * 30) {
						String value = tokenInfo.getValue();
						TokenUtil.setTokenInfo(token, value);
						WebUtil.saveCurrentUser(request, value);
					}
				}
			} catch (Exception e) {
				logger.error("token检查发生异常:", e);
			}
		}
		// 响应
		if (DataUtil.isEmpty(WebUtil.getCurrentUser(request))) {
			response.setContentType("text/html; charset=UTF-8");
			Map<String, Object> modelMap = InstanceUtil.newLinkedHashMap();
			modelMap.put("httpCode", HttpCode.UNAUTHORIZED.value());
			modelMap.put("msg", HttpCode.UNAUTHORIZED.msg());
			modelMap.put("timestamp", System.currentTimeMillis());
			PrintWriter out = response.getWriter();
			out.println(JSON.toJSONString(modelMap));
			out.flush();
			out.close();
		} else {
			chain.doFilter(request, response);
		}
	}
}
 
开发者ID:guokezheng,项目名称:automat,代码行数:39,代码来源:TokenFilter.java

示例7: service

import javax.servlet.ServletResponse; //导入依赖的package包/类
/**
 * Will accept requests only from build manager.
 */
public void service(final ServletRequest request, final ServletResponse response) throws IOException, ServletException {

  // Prohibit non-remote manager address
  final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
  final String remoteAddr = httpServletRequest.getRemoteAddr();
  if (!DISABLE_SOURCE_IP_ADDRESS_CHECK && !remoteAddr.equals(BUILD_MANAGER_ADDRESS)) {
    final HttpServletResponse httpServletResponce = (HttpServletResponse) response;
    httpServletResponce.setStatus(HttpServletResponse.SC_FORBIDDEN);
    IoUtils.closeHard(request.getInputStream());
    IoUtils.closeHard(response.getOutputStream());
    return;
  }

  // Execute normally
  super.service(request, response);
}
 
开发者ID:parabuild-ci,项目名称:parabuild-ci,代码行数:20,代码来源:AgentManagerServlet.java

示例8: doFilter

import javax.servlet.ServletResponse; //导入依赖的package包/类
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest)request;
    String ori = req.getHeader("Origin");
    if (ori != null && allowedOrigins.contains(ori)) {
        HttpServletResponse res = (HttpServletResponse)response;
        res.setHeader("Access-Control-Allow-Origin", ori);
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        res.setHeader("Access-Control-Max-Age", "3600");
        res.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        res.setHeader("Access-Control-Allow-Credentials", "true");
    }
    chain.doFilter(request, response);
}
 
开发者ID:AwesomeTickets,项目名称:ServiceServer,代码行数:15,代码来源:CORSFilter.java

示例9: testNoHttp

import javax.servlet.ServletResponse; //导入依赖的package包/类
/** Test.
 * @throws ServletException e
 * @throws IOException e */
@Test
public void testNoHttp() throws ServletException, IOException {
	// non http
	final FilterChain servletChain = createNiceMock(FilterChain.class);
	final ServletRequest servletRequest = createNiceMock(ServletRequest.class);
	final ServletResponse servletResponse = createNiceMock(ServletResponse.class);
	replay(config);
	replay(context);
	replay(servletRequest);
	replay(servletResponse);
	replay(servletChain);
	jiraMonitoringFilter.init(config);
	jiraMonitoringFilter.doFilter(servletRequest, servletResponse, servletChain);
	verify(config);
	verify(context);
	verify(servletRequest);
	verify(servletResponse);
	verify(servletChain);
}
 
开发者ID:javamelody,项目名称:jira-confluence-javamelody,代码行数:23,代码来源:TestJiraMonitoringFilter.java

示例10: postFilter

import javax.servlet.ServletResponse; //导入依赖的package包/类
public void postFilter(ServletRequest request, ServletResponse response) {
    Segment segment = recorder.getCurrentSegment();
    if (null != segment) {
        HttpServletResponse httpServletResponse = castServletResponse(response);

        if (null != httpServletResponse) {
            Map<String, Object> responseAttributes = new HashMap<String, Object>();

            int responseCode = httpServletResponse.getStatus();
            switch (responseCode/100) {
                case 4:
                    segment.setError(true);
                    if (responseCode == 429) {
                        segment.setThrottle(true);
                    }
                    break;
                case 5:
                    segment.setFault(true);
                    break;
                default:
                    break;
            }
            responseAttributes.put("status", responseCode);


            Optional<Integer> contentLength = getContentLength(httpServletResponse);
            if (contentLength.isPresent()) {
                responseAttributes.put("content_length", contentLength.get());
            }

            segment.putHttp("response", responseAttributes);
        }

        recorder.endSegment();
    }
}
 
开发者ID:aws,项目名称:aws-xray-sdk-java,代码行数:37,代码来源:AWSXRayServletFilter.java

示例11: onTimeout

import javax.servlet.ServletResponse; //导入依赖的package包/类
@Override
public void onTimeout(AsyncEvent event) throws IOException {
  // in this time, maybe:
  // 1.invocation in executor's queue
  // 2.already executing in executor
  // 3.already send response
  // to avoid concurrent, must lock request
  ServletRequest request = event.getSuppliedRequest();
  HttpServletRequestEx requestEx = (HttpServletRequestEx) request.getAttribute(RestConst.REST_REQUEST);

  synchronized (requestEx) {
    ServletResponse response = event.getAsyncContext().getResponse();
    if (!response.isCommitted()) {
      LOGGER.error("Rest request timeout, method {}, path {}.", requestEx.getMethod(), requestEx.getRequestURI());
      // invocation in executor's queue
      response.setContentType(MediaType.APPLICATION_JSON);

      // we don't know if developers declared one statusCode in contract
      // so we use cse inner statusCode here
      ((HttpServletResponse) response).setStatus(ExceptionFactory.PRODUCER_INNER_STATUS_CODE);
      PrintWriter out = response.getWriter();
      out.write(TIMEOUT_MESSAGE);
      response.flushBuffer();
    }

    request.removeAttribute(RestConst.REST_REQUEST);
  }
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:29,代码来源:RestAsyncListener.java

示例12: isAccessAllowed

import javax.servlet.ServletResponse; //导入依赖的package包/类
@Override
protected boolean isAccessAllowed(ServletRequest request,
		ServletResponse response, Object mappedValue) {
	Subject subject = getSubject(request, response);

	// 如果 isAuthenticated 为 false 证明不是登录过的,同时 isRememberd 为true 证明是没登陆直接通过记住我功能进来的
	if (!subject.isAuthenticated() && subject.isRemembered()) {
		// 获取session的USERSESSION属性来看session是不是空的
		if(null == ShiroAuthenticationManager.getSessionAttribute(ShiroUtils.USERSESSION))
		{
			// 初始化
			UserEntity userEntity = (UserEntity) subject.getPrincipal();
			ShiroAuthenticationManager.setSessionAttribute(ShiroUtils.USERSESSION, userEntity);
		}
	}

	// 这个方法本来只返回 subject.isAuthenticated() 现在我们加上 subject.isRemembered()
	// 让它同时也兼容remember这种情况
	return subject.isAuthenticated() || subject.isRemembered();
}
 
开发者ID:wjggwm,项目名称:webside,代码行数:21,代码来源:RememberMeFilter.java

示例13: handleChangeUserPasswordRequest_errorAccountNotLocked

import javax.servlet.ServletResponse; //导入依赖的package包/类
@Test
public void handleChangeUserPasswordRequest_errorAccountNotLocked()
        throws Exception {
    // given
    doReturn(Boolean.TRUE).when(authReqDataMock).isRequestedToChangePwd();
    doReturn("secret").when(authReqDataMock).getNewPassword();
    doReturn("secret").when(authReqDataMock).getNewPassword2();
    doReturn(userDetails).when(identityServiceMock).getUser(
            any(VOUser.class));
    doReturn("error.changePassword").when(requestMock).getAttribute(
            Constants.REQ_ATTR_ERROR_KEY);

    // when
    boolean result = authFilter
            .handleChangeUserPasswordRequest(chainMock, requestMock,
                    responseMock, authReqDataMock, identityServiceMock);

    // then
    assertFalse("Unsuccessful password change", result);
    verify(authFilter, never()).sendRedirect(any(HttpServletRequest.class),
            any(HttpServletResponse.class), anyString());
    verify(chainMock, times(2)).doFilter(any(ServletRequest.class),
            any(ServletResponse.class));
}
 
开发者ID:servicecatalog,项目名称:oscm,代码行数:25,代码来源:AuthorizationFilterTest.java

示例14: doFilterInternal

import javax.servlet.ServletResponse; //导入依赖的package包/类
@Override
public void doFilterInternal(ServletRequest servletRequest, ServletResponse servletResponse,
		FilterChain chain)
		throws ServletException, IOException {
	HttpServletRequest request = (HttpServletRequest)servletRequest;
	String str = request.getRequestURI().toLowerCase();
	boolean flag = true;
	int idx = 0;
	if ((idx = str.indexOf(".")) > 0){
		str = str.substring(idx);
		if (ignoreExt.contains(str.toLowerCase())){
			flag = false;
		}
	}
	if (flag){
		super.doFilterInternal(servletRequest, servletResponse, chain);
	} else {
		chain.doFilter(servletRequest, servletResponse);
	}
}
 
开发者ID:hsj-xiaokang,项目名称:springboot-shiro-cas-mybatis,代码行数:21,代码来源:MyShiroFilterFactoryBean.java

示例15: testService

import javax.servlet.ServletResponse; //导入依赖的package包/类
@Test
public void testService() throws ServletException, IOException {
    this.safeServlet.init(this.mockConfig);

    ServletRequest mockRequest = new MockHttpServletRequest();
    ServletResponse mockResponse = new MockHttpServletResponse();

    try {
        this.safeServlet.service(mockRequest, mockResponse);
    } catch (final ApplicationContextException ace) {
        // good, threw the exception we expected.
        return;
    }

    fail("Should have thrown ApplicationContextException since init() failed.");
}
 
开发者ID:luotuo,项目名称:cas4.0.x-server-wechat,代码行数:17,代码来源:SafeDispatcherServletTests.java


注:本文中的javax.servlet.ServletResponse类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。