Java Code Examples for javax.servlet.ServletResponse#setCharacterEncoding()

The following examples show how to use javax.servlet.ServletResponse#setCharacterEncoding() . 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 File: GreenStepMobileFormAuthenticationFilter.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {  	
	if (isAjaxRequest((HttpServletRequest)request)) {
		response.setCharacterEncoding( Constants.BASE_ENCODING );
		response.setContentType("application/json");
		response.getWriter().write(Constants.NO_LOGIN_JSON_DATA);
		return;
	}
	if (this.isIframeMode((HttpServletRequest)request)) { // iframe 不要導向 login.action 因為畫面會怪怪的    		
		WebUtils.issueRedirect(request, response, "/pages/system/error_static.jsp");
		return;
	}    	
	if (this.isDojoxContentPane((HttpServletRequest)request)) { // 在 dojox.layout.ContentPane 不要出現 login.action 頁面    		
		WebUtils.issueRedirect(request, response, Constants.DOJOX_CONTENT_PANE_XHR_RE_LOGIN_PAGE);
		return;
	}
	WebUtils.issueRedirect(request, response, getLoginUrl());
}
 
Example 2
Source File: CommonUtil.java    From sureness with Apache License 2.0 6 votes vote down vote up
/**
 * description 封装response  统一json返回
 *
 * @param content 内容
 * @param response response
 */
public static void responseWrite(ResponseEntity content, ServletResponse response) {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json;charset=utf-8");
    ((HttpServletResponse)response).setStatus(content.getStatusCodeValue());
    content.getHeaders().forEach((key, value) ->
            ((HttpServletResponse) response).addHeader(key, value.get(0)));
    try (PrintWriter printWriter = response.getWriter()) {
        if (content.getBody() != null) {
            if (content.getBody() instanceof String) {
                printWriter.write(content.getBody().toString());
            } else {
                ObjectMapper objectMapper = new ObjectMapper();
                printWriter.write(objectMapper.writeValueAsString(content.getBody()));
            }
        } else {
            printWriter.flush();
        }
    } catch (IOException e) {
        logger.error("responseWrite response error: ", e);
    }
}
 
Example 3
Source File: CharsetEncodingFilter.java    From weiyunpan with 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;
	req.setCharacterEncoding("utf-8");
	resp.setCharacterEncoding("utf-8");
	
	/**
	 * 清除页面缓存
	 */
	response.setHeader("Pragma", "No-cache");
	response.setHeader("Cache-Control", "no-cache");
	response.setDateHeader("Expires", -10);
	chain.doFilter(req, resp);

}
 
Example 4
Source File: RestAuthFilter.java    From opencps-v2 with GNU Affero General Public License v3.0 6 votes vote down vote up
private void authFailure(ServletResponse servletResponse) throws IOException {
	servletResponse.setCharacterEncoding("UTF-8");
	servletResponse.setContentType("application/json; charset=utf-8");
	
	HttpServletResponse response = (HttpServletResponse) servletResponse;
	response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
	response.setContentType("application/json; charset=utf-8");
	
	PrintWriter out = response.getWriter();												
	
	OpenCPSErrorDetails error = new OpenCPSErrorDetails(new Date(), "permission denied", "");
	
	out.println(error.toString());
	out.flush();
	out.close();
}
 
Example 5
Source File: SetCharacterEncodingFilter.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Select and set (if specified) the character encoding to be used to
 * interpret request parameters for this request.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param chain The filter chain we are processing
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain)
       throws IOException, ServletException {

    // Conditionally select and set the character encoding to be used
    if ((request.getCharacterEncoding() == null)) {
        String encodingIn = selectEncoding(request);
        if (encoding != null) {
            request.setCharacterEncoding(encodingIn);
            response.setContentType("text/html; charset=" + encodingIn);
            response.setCharacterEncoding(encodingIn);
        }
    }

    // Pass control on to the next filter
    chain.doFilter(request, response);

}
 
Example 6
Source File: SetCharacterEncodingFilter.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Select and set (if specified) the character encoding to be used to
 * interpret request parameters for this request.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param chain The filter chain we are processing
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain)
       throws IOException, ServletException {

    // Conditionally select and set the character encoding to be used
    if ((request.getCharacterEncoding() == null)) {
        String encodingIn = selectEncoding(request);
        if (encoding != null) {
            request.setCharacterEncoding(encodingIn);
            response.setContentType("text/html; charset=" + encodingIn);
            response.setCharacterEncoding(encodingIn);
        }
    }

    // Pass control on to the next filter
    chain.doFilter(request, response);

}
 
Example 7
Source File: WebHelper.java    From Shiro-Action with MIT License 6 votes vote down vote up
/**
 * 输出JSON
 */
public static void writeJson(Object object, ServletResponse response) {
    PrintWriter out = null;
    try {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        out = response.getWriter();
        out.write(JSONUtil.toJsonStr(object));
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}
 
Example 8
Source File: CaptchaFormAuthenticationFilter.java    From MultimediaDesktop with Apache License 2.0 6 votes vote down vote up
/**
 * 主要是处理登入失败的方法
 */
@Override
protected boolean onLoginFailure(AuthenticationToken token,
		AuthenticationException e, ServletRequest request,
		ServletResponse response) {
	setFailureAttribute(request, e);
	if (!"XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request)
			.getHeader("X-Requested-With"))) {// 不是ajax请求
		return true;
	}
	try {
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.printf("{success:false,message:'%s'}",
				request.getAttribute(getFailureKeyAttribute()));
		out.flush();
		out.close();
	} catch (IOException e1) {
		log.fatal("异步跳转异常", e);
	}
	return false;
}
 
Example 9
Source File: SessionTimeoutFilter.java    From TourismWebsite with MIT License 5 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response,
		FilterChain chain) throws IOException, ServletException {
     HttpServletRequest req=(HttpServletRequest)request;    
     String  flag=req.getParameter("flag");
     if(((HttpServletRequest)request).getRequestURI().equals("/TLX/admin/adminLogin.jsp")||!((HttpServletRequest)request).getRequestURI().endsWith(".jsp")){
    	 chain.doFilter(request, response);
     }else{
    	 if(!"adminLogin".equals(flag)){
	    	 
	    	 HttpServletRequest httpServletRequest = (HttpServletRequest)request;
				HttpSession httpSession = httpServletRequest.getSession();
			    String account=(String)httpSession.getAttribute("account");
			    response.setCharacterEncoding("GBK");
			
				if(account == null){
					response.setCharacterEncoding("GBK");
					((HttpServletResponse)response).getWriter().write("<script>alert('����δ��¼�����ȵ�¼��ϵͳ���Զ���ת����¼ҳ��');window.top.location.href='" + ((HttpServletRequest)request).getContextPath() + "/admin/adminLogin.jsp';</script>");
				}else{
					chain.doFilter(request, response);
				}
	     }else{
	    		chain.doFilter(request, response);
	    	 
	     }
     }
     

}
 
Example 10
Source File: GreenStepBaseFormAuthenticationFilter.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
	if (isAjaxRequest((HttpServletRequest)request)) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		response.getWriter().write(Constants.NO_LOGIN_JSON_DATA);
		return;
	}
	if (this.isDojoxContentPane((HttpServletRequest)request)) { // 在 dojox.layout.ContentPane 不要出現 login.action 頁面    		
		WebUtils.issueRedirect(request, response, Constants.DOJOX_CONTENT_PANE_XHR_RE_LOGIN_PAGE);
		return;
	}
	WebUtils.issueRedirect(request, response, getLoginUrl());
}
 
Example 11
Source File: GreenStepBaseFormAuthenticationFilter.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
 	if ( !Constants.getSystem().equals( Constants.getMainSystem() ) && !isAjaxRequest((HttpServletRequest)request) ) { // 非 core-web
 		try {
	if ( this.loginUseCurrentCookieForGeneralPackage(request, response) ) { // no need to login-page
		String url = SimpleUtils.getHttpRequestUrl( (HttpServletRequest)request );
		logger.warn("URL = " + url );					
		WebUtils.issueRedirect(request, response, url);
		return;
	}
} catch (Exception e) {
	e.printStackTrace();
}
 	}    	
 	if (isAjaxRequest((HttpServletRequest)request)) {
 		response.setCharacterEncoding( Constants.BASE_ENCODING );
 		response.setContentType("application/json");
 		response.getWriter().write(Constants.NO_LOGIN_JSON_DATA);
 		return;
 	}
 	if (this.isIframeMode((HttpServletRequest)request)) { // iframe 不要導向 login.action 因為畫面會怪怪的    		
 		WebUtils.issueRedirect(request, response, "/pages/system/error_static.jsp");
 		return;
 	}    	
 	if (this.isDojoxContentPane((HttpServletRequest)request)) { // 在 dojox.layout.ContentPane 不要出現 login.action 頁面    		
 		WebUtils.issueRedirect(request, response, Constants.DOJOX_CONTENT_PANE_XHR_RE_LOGIN_PAGE);
 		return;
 	}
 	WebUtils.issueRedirect(request, response, getLoginUrl());
 }
 
Example 12
Source File: MyAuthcFilter.java    From MyBlog with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json; charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.write(JSON.toJSONString(MyResponse.createResponse(ResponseEnum.NON_AUTH)));
    return false;
}
 
Example 13
Source File: GreenStepMobileFormAuthenticationFilter.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, 
		ServletRequest request, ServletResponse response) throws Exception {
	
       HttpServletRequest httpServletRequest = (HttpServletRequest)request;
       HttpServletResponse httpServletResponse = (HttpServletResponse)response;
       if (!this.isAjaxRequest(httpServletRequest)) {
       	httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + this.getSuccessUrl());
       } else {
   		response.setCharacterEncoding( Constants.BASE_ENCODING );
   		response.setContentType("application/json");
   		response.getWriter().write(Constants.NO_AUTHZ_JSON_DATA);
       }
	return false;
}
 
Example 14
Source File: RewriteAccessDenyFilter.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		try {
			chain.doFilter(request, response);
		} catch (Exception ex) {
//			Throwable[] causeChain = throwableAnalyzer.determineCauseChain(ex);
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json;charset=utf-8");
			JsonData<Object> objectJsonData = new JsonData<>(StatusEnum.ACCESS_DENIED);
			response.getWriter().print(JsonUtil.toJsonString(objectJsonData));
		}
	}
 
Example 15
Source File: RepeatableReadAuthorizationFilter.java    From qconfig with MIT License 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
        super.doFilter(request, response, chain);
    } catch (ServletException e) {
        if (e.getCause() instanceof MaxUploadSizeExceededException) {
            response.setContentType("application/json");
            response.setCharacterEncoding("utf8");
            response.getWriter().println("{\"message\":\"文件不能超过" + AdminConstants.MAX_FILE_SIZE_IN_K + "k\",\"data\":null,\"status\":1}");
        } else {
            throw e;
        }
    }
}
 
Example 16
Source File: JsonUtil.java    From spring-cloud-yes with Apache License 2.0 5 votes vote down vote up
public static void writeJson(ServletResponse response, AjaxResult ajaxResult) {
    try {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(
                JsonMapper.defaultMapper()
                        .toJson(ajaxResult)
        );
        out.flush();
        out.close();
    } catch (IOException e) {
        log.error("发生异常。", e);
    }
}
 
Example 17
Source File: URLPathMatchingFilter.java    From SENS with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {

    //请求的url
    String requestURL = getPathWithinApplication(request);
    System.out.println("请求的url :" + requestURL);
    Subject subject = SecurityUtils.getSubject();
    if (!subject.isAuthenticated()) {
        // 如果没有登录, 进入登录流程
        WebUtils.issueRedirect(request, response, "/admin/login");
        return false;
    }

    //从session里读取当前用户的权限URL列表
    Set<String> urls = (Set<String>) subject.getSession().getAttribute("permissionUrls");
    if (urls.contains(requestURL)) {
        return true;
    }

    //没有权限
    if (isAjax((HttpServletRequest) request)) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "没有权限访问");
        writer.write(JSONObject.toJSONString(map));
    } else {
        WebUtils.issueRedirect(request, response, "/403");
    }
    return false;
}
 
Example 18
Source File: EncodingFilter.java    From unitime with Apache License 2.0 4 votes vote down vote up
/**
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
	req.setCharacterEncoding(iEncoding);
	resp.setCharacterEncoding(iEncoding);
	chain.doFilter(req, resp);
}
 
Example 19
Source File: PreviewFilter.java    From publick-sling-blog with Apache License 2.0 4 votes vote down vote up
/**
 * Handle blog posts that are not published. If the user is authenticated,
 * display a preview bar. If the user is anonymous, seve a 404.
 *
 * @param request The Sling HTTP Servlet Request.
 * @param response The Sling HTTP Servlet Response.
 * @param chain The Filter Chain to continue processin the response.
 */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain chain) throws IOException, ServletException {

    // Since this is a Sling Filter, the request and response objects are guaranteed
    // to be of types SlingHttpServletRequest and SlingHttpServletResponse.
    final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest)request;
    final SlingHttpServletResponse slingResponse = (SlingHttpServletResponse)response;

    final Resource resource = slingRequest.getResource();
    final String method = slingRequest.getMethod();
    final String resourceType = resource.getResourceType();

    response.setCharacterEncoding(CharEncoding.UTF_8);

    if ("GET".equals(method) && PublickConstants.PAGE_TYPE_BLOG.equals(resourceType)) {

        if (!resource.getValueMap().get("visible", false)) {
            final boolean authorable = userService.isAuthorable(slingRequest.getResourceResolver().adaptTo(Session.class));

            /* If user is logged in and page isn't published, inject a preview bar. */
            if (authorable) {
                PrintWriter out = response.getWriter();
                CharResponseWrapper responseWrapper = new CharResponseWrapper((HttpServletResponse)response);

                try {
                  chain.doFilter(request, responseWrapper);
                } catch (Exception e) {
                  LOGGER.error("Could not continue chain", e);
                  chain.doFilter(request, response);
                }

                final String servletResponse = new String(responseWrapper.toString());
                final String previewHeader = getPreviewHeader(slingRequest, PREVIEW_HEADER_PATH);

                /* Insert component before body close tag. Append to end if body close tag doesn't exist. */
                if (servletResponse != null && servletResponse.contains(INSERTION_TAG)) {
                    String[] html = servletResponse.split(INSERTION_TAG);

                    out.write(html[0] + INSERTION_TAG + previewHeader + html[1]);
                } else {
                    out.write(servletResponse + previewHeader);
                }
            } else {
                /* If user is not logged in and page isn't published, forward to 404. */
                slingResponse.sendError(SlingHttpServletResponse.SC_NOT_FOUND);
            }
        } else {
            chain.doFilter(request, slingResponse);
        }
    } else {
        chain.doFilter(request, slingResponse);
    }
}
 
Example 20
Source File: CharacterEncodingFilter.java    From joynr with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
                                                                                          ServletException {
    response.setCharacterEncoding("UTF-8");
    chain.doFilter(request, response);
}