标签:substring htm null iter lse closed entryset play access
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"); }
标签:substring htm null iter lse closed entryset play access
原文地址:https://www.cnblogs.com/zys2019/p/12085327.html