依赖类:
https://blog.csdn.net/Lxinccode/article/details/82839955
https://blog.csdn.net/Lxinccode/article/details/79414138
https://blog.csdn.net/Lxinccode/article/details/79414399
使用场景 : 请求转发、同一 URL 接口任意参数
import com.aliyun.et.industry.device.api.enums.ResultCodeEnum;
import com.aliyun.et.industry.device.api.exception.DeviceException;
import com.aliyun.et.industry.templateboot.service.common.util.CheckCharacterCoding;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* @Auther: liyue
* @Date: 2018/10/24 14:43
* @Description:
*/
public class RequestUtil {
/**
* 请求参数反序列化
* @param request
* @param clazzT
* @param <T>
* @return
*/
private static <T> T paramsHandleCenter(HttpServletRequest request, Class<T> clazzT) {
List<String> attributeNames = ReflexUtil.getObjectAttributeNames(clazzT);
StringBuffer json = new StringBuffer();
json.append("{");
for (String str : attributeNames) {
String value = request.getParameter(str);
if (value == null) {
continue;
}
if (CheckCharacterCoding.checkISO(value)) {
try {
value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
} catch (Exception e) {
}
}
if (value == null) {
throw new DeviceException(ResultCodeEnum.ARGUMENT_ERROR);
}
json.append("\"").append(str).append("\":\"").append(value).append("\"").append(",");
}
json.delete(json.length() - 1, json.length());
json.append("}");
T t = JsonUtils.jsonToPojo(json.toString(), clazzT);
return t;
}
}
示例
请求 : http://127.0.0.1:8080/test?name=张三&age=14
首先得存在含有 name 与 age 的类并实现序列化接口,例如:
import java.io.Serializable;
/**
* @Auther: liyue
* @Date: 2018/10/24 14:55
* @Description:
*/
public class User implements Serializable {
private static final long serialVersionUID = -2509731965245043361L;
private String name;
private Integer age;
public User() {
}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Controller
@RequestMapping(value = "/test")
public User test(HttpServletRequest httpServletRequest) {
User user = RequestUtil.paramsHandleCenter(httpServletRequest, User.class);
return user;
}
END。