com.feingto.cloud.kit.ServletKit Maven / Gradle / Ivy
package com.feingto.cloud.kit;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
/**
* Servlet 工具类.
*
* @author longfei
*/
public class ServletKit {
/**
* 设置让浏览器弹出下载对话框的Header, 不同浏览器使用不同的编码方式
*
* @param fileName 下载后的文件名
*/
@SneakyThrows
public static void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
String agent = request.getHeader(HttpHeaders.USER_AGENT);
String encodedfileName = null;
if (StringUtils.hasText(agent)) {
agent = agent.toLowerCase();
if (agent.contains("firefox") || agent.contains("chrome") || agent.contains("safari")) {
encodedfileName = "filename=\"" + new String(fileName.getBytes(), "ISO8859-1") + "\"";
} else if (agent.contains("msie")) {
encodedfileName = "filename=\"" + EncodeKit.urlEncode(fileName) + "\"";
} else if (agent.contains("opera")) {
encodedfileName = "filename*=\"" + StandardCharsets.UTF_8.name() + fileName + "\"";
} else {
encodedfileName = "filename=\"" + EncodeKit.urlEncode(fileName) + "\"";
}
}
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; " + encodedfileName);
}
/**
* 输出文本
*/
public static void renderText(HttpServletResponse response, Object text) {
render(response, text, MediaType.TEXT_PLAIN_VALUE);
}
/**
* 输出Json
*/
public static void renderJson(HttpServletResponse response, Object json) {
render(response, json, MediaType.APPLICATION_JSON_VALUE);
}
/**
* 输出Xml
*/
public static void renderXml(HttpServletResponse response, Object xml) {
render(response, xml, MediaType.TEXT_XML_VALUE);
}
public static void render(HttpServletResponse response, Object output, String contentType) {
if (Objects.isNull(response.getCharacterEncoding())) {
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
}
response.setContentType(StringUtils.isEmpty(contentType) ? MediaType.TEXT_PLAIN_VALUE : contentType);
try (PrintWriter writer = response.getWriter()) {
writer.print(output);
writer.flush();
} catch (IOException ignored) {
}
}
}