com.github.yoojia.halo.HaloResponse Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of halo-core Show documentation
Show all versions of halo-core Show documentation
A FAST && THIN && HIGH SCALABLE Java web framework
package com.github.yoojia.halo;
import com.github.yoojia.halo.supports.Context;
import com.github.yoojia.halo.supports.StatusCode;
import com.github.yoojia.halo.utils.Exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author YOOJIA.CHEN ([email protected])
*/
public final class HaloResponse {
private static final Logger LOG = LoggerFactory.getLogger(HaloResponse.class);
public final HttpServletResponse httpResponse;
public HaloResponse(HttpServletResponse response) {
this.httpResponse = response;
setStatusCode(StatusCode.NOT_FOUND);
this.httpResponse.setCharacterEncoding("UTF-8");
this.httpResponse.setHeader("X-Powered-By", Context.VERSION);
}
/**
* 设置HTTP响应码
*/
public final void setStatusCode(int status){
httpResponse.setStatus(status);
}
/**
* 获取响应码
*/
public final int getStatusCode(){
return httpResponse.getStatus();
}
/**
* 设置ContentType
*/
public final void setContentType(String contentType){
if(contentType != null && !contentType.isEmpty()){
httpResponse.setContentType(contentType);
}
}
/**
* 返回服务端错误到客户端
*/
public final void sendError(Exception error){
LOG.trace("ERROR", error);
httpResponse.setStatus(StatusCode.INTERNAL_SERVER_ERROR);
writeTextSilently(Exceptions.message(error));
}
/**
* 发送文本数据到客户端
*/
public final void sendText(String text){
writeTextSilently(text);
}
/**
* 发送文本到客户端
*/
public final void sendTextThrows(String text) throws IOException {
writeTextThrows(text);
}
/**
* 发送ContextText并指定响应码
*/
public final void sendText(int statusCode, String contentText){
httpResponse.setStatus(statusCode);
writeTextSilently(contentText);
}
/**
* 重定向客户端
*/
public final void sendRedirect(String location) {
try {
sendRedirectThrows(location);
} catch (IOException e) {
LOG.trace("Response redirect error", e);
}
}
/**
* 重定向客户端
*/
public final void sendRedirectThrows(String location) throws IOException {
httpResponse.sendRedirect(location);
}
private void writeTextSilently(String text){
try {
writeTextThrows(text);
} catch (IOException e) {
LOG.trace("Response write error", e);
}
}
private void writeTextThrows(String text) throws IOException {
if(text != null && !text.isEmpty()){
httpResponse.getWriter().write(text);
}
}
}