本文整理汇总了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);
}
示例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);
}
}
示例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;
}
}
}
示例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());
}
示例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);
}
}
示例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);
}
}
}
示例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);
}
示例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);
}
示例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);
}
示例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();
}
}
示例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);
}
}
示例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();
}
示例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));
}
示例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);
}
}
示例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.");
}