常用工具类
Posted zys2019
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常用工具类相关的知识,希望对你有一定的参考价值。
1.htmlUtil向页面输入String,会自动转为json格式
1)类HtmlUtil:向页面输出String
package com.zys.training.util; import com.fasterxml.jackson.databind.ObjectMapper; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * 向页面输出String * @author yushizhong */ public class HtmlUtil { /** * 输出string * @param response * @param jsonStr */ public static void writerJson(HttpServletResponse response, String jsonStr) { writer(response, jsonStr); } public static void writerJson(HttpServletResponse response, Object object) throws Exception { ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(object) ; writer(response, jsonString); } private static void writer(HttpServletResponse response, String str) { try { // 设置页面不缓存 response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Access-Control-Allow-Origin","*"); response.setCharacterEncoding("UTF-8"); PrintWriter out = null; out = response.getWriter(); out.print(str); out.flush(); out.close(); } catch ( Exception ex){ ex.printStackTrace(); } } public static Map<String, String> getParameterMap(HttpServletRequest request) { // 参数Map Map properties = request.getParameterMap(); // 返回值Map Map<String, String> returnMap = new HashMap<String, String>(); Iterator entries = properties.entrySet().iterator(); Map.Entry entry; String name = ""; String value = ""; while (entries.hasNext()) { entry = (Map.Entry) entries.next(); name = (String) entry.getKey(); Object valueObj = entry.getValue(); if (null == valueObj) { value = ""; } else if (valueObj instanceof String[]) { String[] values = (String[]) valueObj; for (int i = 0; i < values.length; i++) { value = values[i] + ","; } value = value.substring(0, value.length() - 1); } else { value = valueObj.toString(); } returnMap.put(name, value); } return returnMap; } }
具体用法
@RequestMapping("/get") public void get(HttpServletResponse response){ response.setContentType("application/json"); HtmlUtil.writerJson(response, "hello"); }
以上是关于常用工具类的主要内容,如果未能解决你的问题,请参考以下文章