HttpServletResponse工具类和HttpServletRequest工具类,前台参数接收方式和后台返回(JSON)数据格式
RequestUtils.java 操作类
package cn.utils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.UrlPathHelper; import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer; /**
* HttpServletRequest 工具类
*/
public class RequestUtils { private static final Logger log = LoggerFactory
.getLogger(RequestUtils.class); /**
* HTTP POST请求
*/
public static final String POST = "POST"; /**
* UTF-8编码
*/
public static final String UTF8 = "UTF-8"; /**
* 获取QueryString的参数,并使用URLDecoder以UTF-8格式转码。如果请求是以post方法提交的,
* 那么将通过HttpServletRequest#getParameter获取。
*
* @param request
* web请求
* @param name
* 参数名称
* @return
*/
public static String getQueryParam(HttpServletRequest request, String name) {
if (StringUtils.isBlank(name)) {
return null;
}
if (request.getMethod().equalsIgnoreCase(POST)) {
return request.getParameter(name);
}
String s = request.getQueryString();
if (StringUtils.isBlank(s)) {
return null;
}
try {
s = URLDecoder.decode(s, UTF8);
} catch (UnsupportedEncodingException e) {
log.error("encoding " + UTF8 + " not support?", e);
}
String[] values = parseQueryString(s).get(name);
if (values != null && values.length > 0) {
return values[values.length - 1];
} else {
return null;
}
} @SuppressWarnings("unchecked")
public static Map<String, Object> getQueryParams(HttpServletRequest request) {
Map<String, String[]> map;
if (request.getMethod().equalsIgnoreCase(POST)) {
map = request.getParameterMap();
} else {
String s = request.getQueryString();
if (StringUtils.isBlank(s)) {
return new HashMap<String, Object>();
}
try {
s = URLDecoder.decode(s, UTF8);
} catch (UnsupportedEncodingException e) {
log.error("encoding " + UTF8 + " not support?", e);
}
map = parseQueryString(s);
} Map<String, Object> params = new HashMap<String, Object>(map.size());
int len;
for (Map.Entry<String, String[]> entry : map.entrySet()) {
len = entry.getValue().length;
if (len == 1) {
params.put(entry.getKey(), entry.getValue()[0]);
} else if (len > 1) {
params.put(entry.getKey(), entry.getValue());
}
}
return params;
} /**
*
* Parses a query string passed from the client to the server and builds a
* <code>HashTable</code> object with key-value pairs. The query string
* should be in the form of a string packaged by the GET or POST method,
* that is, it should have key-value pairs in the form <i>key=value</i>,
* with each pair separated from the next by a & character.
*
* <p>
* A key can appear more than once in the query string with different
* values. However, the key appears only once in the hashtable, with its
* value being an array of strings containing the multiple values sent by
* the query string.
*
* <p>
* The keys and values in the hashtable are stored in their decoded form, so
* any + characters are converted to spaces, and characters sent in
* hexadecimal notation (like <i>%xx</i>) are converted to ASCII characters.
*
* @param s
* a string containing the query to be parsed
*
* @return a <code>HashTable</code> object built from the parsed key-value
* pairs
*
* @exception IllegalArgumentException
* if the query string is invalid
*
*/
public static Map<String, String[]> parseQueryString(String s) {
String valArray[] = null;
if (s == null) {
throw new IllegalArgumentException();
}
Map<String, String[]> ht = new HashMap<String, String[]>();
StringTokenizer st = new StringTokenizer(s, "&");
while (st.hasMoreTokens()) {
String pair = (String) st.nextToken();
int pos = pair.indexOf('=');
if (pos == -1) {
continue;
}
String key = pair.substring(0, pos);
String val = pair.substring(pos + 1, pair.length());
if (ht.containsKey(key)) {
String oldVals[] = (String[]) ht.get(key);
valArray = new String[oldVals.length + 1];
for (int i = 0; i < oldVals.length; i++) {
valArray[i] = oldVals[i];
}
valArray[oldVals.length] = val;
} else {
valArray = new String[1];
valArray[0] = val;
}
ht.put(key, valArray);
}
return ht;
} public static Map<String, String> getRequestMap(HttpServletRequest request,
String prefix) {
return getRequestMap(request, prefix, false);
} public static Map<String, String> getRequestMapWithPrefix(
HttpServletRequest request, String prefix) {
return getRequestMap(request, prefix, true);
} @SuppressWarnings("unchecked")
private static Map<String, String> getRequestMap(
HttpServletRequest request, String prefix, boolean nameWithPrefix) {
Map<String, String> map = new HashMap<String, String>();
Enumeration<String> names = request.getParameterNames();
String name, key, value;
while (names.hasMoreElements()) {
name = names.nextElement();
if (name.startsWith(prefix)) {
key = nameWithPrefix ? name : name.substring(prefix.length());
value = StringUtils.join(request.getParameterValues(name), ',');
map.put(key, value);
}
}
return map;
} /**
* 获取访问者IP
*
* 在一般情况下使用Request.getRemoteAddr()即可,但是经过nginx等反向代理软件后,这个方法会失效。
*
* 本方法先从Header中获取X-Real-IP,如果不存在再从X-Forwarded-For获得第一个IP(用,分割),
* 如果还不存在则调用Request .getRemoteAddr()。
*
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("X-Real-IP");
if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
if(ip.contains("../")||ip.contains("..\\")){
return "";
}
return ip;
}
ip = request.getHeader("X-Forwarded-For");
if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
// 多次反向代理后会有多个IP值,第一个为真实IP。
int index = ip.indexOf(',');
if (index != -1) {
ip= ip.substring(0, index);
}
if(ip.contains("../")||ip.contains("..\\")){
return "";
}
return ip;
} else {
ip=request.getRemoteAddr();
if(ip.contains("../")||ip.contains("..\\")){
return "";
}
if(ip.equals("0:0:0:0:0:0:0:1")){
ip="127.0.0.1";
}
return ip;
} } /**
* 获得当的访问路径
*
* HttpServletRequest.getRequestURL+"?"+HttpServletRequest.getQueryString
*
* @param request
* @return
*/
public static String getLocation(HttpServletRequest request) {
UrlPathHelper helper = new UrlPathHelper();
StringBuffer buff = request.getRequestURL();
String uri = request.getRequestURI();
String origUri = helper.getOriginatingRequestUri(request);
buff.replace(buff.length() - uri.length(), buff.length(), origUri);
String queryString = helper.getOriginatingQueryString(request);
if (queryString != null) {
buff.append("?").append(queryString);
}
return buff.toString();
} public static Map<String,String> getSignMap(HttpServletRequest request){
Map<String,String>param=new HashMap<String, String>();
Enumeration penum=(Enumeration) request.getParameterNames();
while(penum.hasMoreElements()){
String pKey=(String) penum.nextElement();
String value=request.getParameter(pKey);
//sign和uploadFile不参与 值为空也不参与
if(!pKey.equals("sign")&&!pKey.equals("uploadFile")
&&StringUtils.isNotBlank(value)){
param.put(pKey,value);
}
}
return param;
} public static void main(String[] args) {
}
}
ResponseUtils.java 操作类
package cn.utils; import java.io.IOException; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* HttpServletResponse 工具类
*/
public final class ResponseUtils {
public static final Logger log = LoggerFactory
.getLogger(ResponseUtils.class); /**
* 发送文本。使用UTF-8编码。
*
* @param response
* HttpServletResponse
* @param text
* 发送的字符串
*/
public static void renderText(HttpServletResponse response, String text) {
render(response, "text/plain;charset=UTF-8", text);
} /**
* 发送json。使用UTF-8编码。
*
* @param response
* HttpServletResponse
* @param text
* 发送的字符串
*/
public static void renderJson(HttpServletResponse response, String text) {
render(response, "application/json;charset=UTF-8", text);
} /**
* 发送xml。使用UTF-8编码。
*
* @param response
* HttpServletResponse
* @param text
* 发送的字符串
*/
public static void renderXml(HttpServletResponse response, String text) {
render(response, "text/xml;charset=UTF-8", text);
} /**
* 发送内容。使用UTF-8编码。
*
* @param response
* @param contentType
* @param text
*/
public static void render(HttpServletResponse response, String contentType,
String text) {
response.setContentType(contentType);
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
try {
response.getWriter().write(text);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
} public static void renderApiJson(HttpServletResponse response,
HttpServletRequest request,ApiResponse apiResult) {
//js跨域请求
String callback = request.getParameter("callback");
if(StringUtils.isNotBlank(callback)){
ResponseUtils.renderJson(response,callback+"(" + apiResult.toString() + ")" );
}else{
ResponseUtils.renderJson(response, apiResult.toString());
}
}
}
ApiResponse.java
package cn.utils; public class ApiResponse { public ApiResponse(String body, String message, String status) {
super();
this.body = body;
this.message = message;
this.status = status;
} /**
* 返回信息主体
*/
public String getBody() {
return body;
} public void setBody(String body) {
this.body = body;
} /**
* API调用提示信息
*/
public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} /**
* API接口调用状态
*/
public String getStatus() {
return status;
} public void setStatus(String status) {
this.status = status;
} @Override
public String toString() {
return "{\"body\":" + body + ", \"message\":" + message + ",\"status\":" + status + "}";
} private String body;
private String message;
private String status;
}
HttpServletResponse工具类和HttpServletRequest工具类,前台参数接收方式和后台返回(JSON)数据格式的更多相关文章
- .net mvc前台如何接收和解析后台的字典类型的数据 二分搜索算法 window.onunload中使用HTTP请求 网页关闭 OpenCvSharp尝试 简单爬虫
.net mvc前台如何接收和解析后台的字典类型的数据 很久没有写博客了,最近做了一个公司门户网站的小项目,其中接触到了一些我不会的知识点,今日事情少,便记录一下,当时想在网上搜索相关的内容,但是 ...
- spring boot 解决后台返回 json 到前台中文乱码之后出现返回json数据报错 500:no convertter for return value of type
问题描述 spring Boot 中文返回给浏览器乱码 解析成问号?? fastJson jackJson spring boot 新增配置解决后台返回 json 到前台中文乱码之后,出现返回json ...
- 后台返回json数据,前台显示代码
List list = "从DAL获取的数据集合" //取出分页标签html int pageIndex = context.Request["pageIndex&quo ...
- Struts2中的JSON问题——后台返回JSON字符串到前台
最近做一个项目遇到一个比较棘手的问题,项目后台采用struts2+Hibernate3+Spring3,前台采用ExtJs4.笔者目前仍是一名大二学生吗,后台框架完全是毫无任何基础,从零学,现学现用. ...
- .net mvc前台如何接收和解析后台的字典类型的数据
很久没有写博客了,最近做了一个公司门户网站的小项目,其中接触到了一些我不会的知识点,今日事情少,便记录一下,当时想在网上搜索相关的内容,但是没有找到. 今天想记录一下这样一个小的需求的做法.先说一下我 ...
- SSM获取前台参数的方式
1.直接把表单的参数写在Controller相应的方法的形参中,适用于get方式提交,不适用于post方式提交.若"Content-Type"="application/ ...
- SpringMVC通过实体类返回json格式的字符串,并在前端显示
一.除了搭建springmvc框架需要的jar包外,还需要这两个jar包 jackson-core-asl-1.9.2.jar和jackson-mapper-asl-1.9.2.jar 二.web,. ...
- JAVA工具类获取HttpServletRequest、HttpServletResponse 对象
添加依赖 <!-- Spring Web --> <dependency> <groupId>org.springframework</groupId> ...
- jdbc工具类的封装,以及表单验证数据提交后台
在之前已经写过了jdbc的工具类,不过最近学习了新的方法,所以在这里重新写一遍,为后面的javaEE做铺垫: 首先我们要了解javaEE项目中,文件构成,新建一个javaEE项目,在项目中,有一个we ...
随机推荐
- NOIOL #2 爆零记
没有假是真的爆零了,原因:万恶的文操.不管怎样写份题解吧. T1: 做题经历:看了下题发现:不是 edu 的原题吗?兴奋地拿出赛中写的程序搞上去. 大约比赛开始 30min 后开始发现 \(k\) 可 ...
- Atcoder Regular Contest 096 C - Everything on It(组合数学)
Atcoder 题面传送门 & 洛谷题面传送门 简单题,由于这场 arc 的 F 是 jxd 作业而我不会做,所以只好来把这场的 E 水掉了. 我们记 \(f(i)\) 为钦定 \(i\) 个 ...
- Pysam 处理bam文件
Pysam可用来处理bam文件 安装: 用 pip 或者 conda即可 使用: Pysam的函数有很多,主要的读取函数有: AlignmentFile:读取BAM/CRAM/SAM文件 Varian ...
- eclipse不自动弹出提示的解决办法(eclipse alt+/快捷键失效)
转载:http://yuncode.net/article/a_53bf6888b6f5065 我的问题:在jsp中使用"alt+/"不能够自动导入java包.利用3,4解决问题 ...
- 40-3Sum Closest
3Sum Closest My Submissions QuestionEditorial Solution Total Accepted: 76185 Total Submissions: 2621 ...
- C++类虚函数内存分布(这个 你必须懂)
转自:http://www.cnblogs.com/jerry19880126/p/3616999.html C++类内存分布 书上类继承相关章节到这里就结束了,这里不妨说下C++内存分布结构,我们来 ...
- Jumpserver堡垒机容器化部署
JumpServer 是符合 4A 的专业运维安全审计系统. 前提条件 已部署docker Jumpserver 对外需要开放 80 443 和 2222 端口 服务器.数据库.redis 等依赖组件 ...
- day17 常用模块的应用
day17 常用模块的应用 老师博客园地址:https://www.cnblogs.com/linhaifeng/articles/6384466.html#_label11 一.time与datet ...
- 容器之分类与各种测试(四)——multimap
multiset和multimap的具体区别在于,前者的key值就是自己存储的value,后者的key与value是分开的不相关的. 例程 #include<stdexcept> #inc ...
- 阿里云esc 登录时的相关提示
1. 如果该ecs 未绑定密钥对,可以通过常规的用户名密码登录 2. 如果该 ecs 绑定了密钥对,则需要通过私钥进行登录 3. 如果使用 比如 securityCRT 登录时报 " A p ...