ServletUtils.java 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package cn.iocoder.dashboard.util.servlet;
  2. import cn.hutool.core.io.IoUtil;
  3. import cn.hutool.extra.servlet.ServletUtil;
  4. import com.alibaba.fastjson.JSON;
  5. import org.springframework.http.MediaType;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.io.IOException;
  9. import java.net.URLEncoder;
  10. /**
  11. * 客户端工具类
  12. *
  13. * @author 芋道源码
  14. */
  15. public class ServletUtils {
  16. /**
  17. * 返回 JSON 字符串
  18. *
  19. * @param response 响应
  20. * @param object 对象,会序列化成 JSON 字符串
  21. */
  22. @SuppressWarnings("deprecation") // 必须使用 APPLICATION_JSON_UTF8_VALUE,否则会乱码
  23. public static void writeJSON(HttpServletResponse response, Object object) {
  24. String content = JSON.toJSONString(object);
  25. ServletUtil.write(response, content, MediaType.APPLICATION_JSON_UTF8_VALUE);
  26. }
  27. /**
  28. * 返回附件
  29. *
  30. * @param response 响应
  31. * @param filename 文件名
  32. * @param content 附件内容
  33. * @throws IOException
  34. */
  35. public static void writeAttachment(HttpServletResponse response, String filename, byte[] content) throws IOException {
  36. // 设置 header 和 contentType
  37. response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
  38. response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
  39. // 输出附件
  40. IoUtil.write(response.getOutputStream(), false, content);
  41. }
  42. /**
  43. * @param request 请求
  44. * @return ua
  45. */
  46. public static String getUserAgent(HttpServletRequest request) {
  47. String ua = request.getHeader("User-Agent");
  48. return ua != null ? ua : "";
  49. }
  50. }