org.luoshu.util.web.HttpKit Maven / Gradle / Ivy
package org.luoshu.util.web;
import org.luoshu.util.Assert;
import org.luoshu.util.json.JSON;
import org.luoshu.util.json.JsonDefine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author inme
* create: 2020-04-13 21:52
*/
public class HttpKit {
public static final Logger logger = LoggerFactory.getLogger(HttpKit.class);
public static HttpServletRequest getRequest(){
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
return request;
}
public static HttpServletResponse getResponse(){
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
return requestAttributes.getResponse();
}
public static HttpSession getSession(){
return getRequest().getSession();
}
/**
* 根据 cookie 的 name 获取 cookie
* @param cookieName cookie 的 name
* @return 返回 cookie
*/
public static Cookie getCookie(String cookieName){
HttpServletRequest request = getRequest();
return getCookie(request , cookieName);
}
/**
* 根据 cookie 的 name 获取 cookie
* @param cookieName cookie 的 name
* @return 返回 cookie
*/
public static Cookie getCookie(HttpServletRequest request , String cookieName){
Assert.assertNotNull(request , "request is null");
Assert.assertNotNull(cookieName , "cookie name is null");
Cookie[] cookies = request.getCookies();
if(cookies == null || cookies.length == 0){
return null;
}
for (Cookie cookie : cookies) {
String name = cookie.getName();
if(cookieName.equals(name)){
return cookie;
}
}
return null;
}
/**
* 把一个 object 对象,写入到 response 中返回
* @param response
* @param object
*/
public static void write(HttpServletResponse response, Object object) {
Assert.assertNotNull(response , "response is null");
Assert.assertNotNull(object , "write object is null");
response.setContentType("application/json;charset=UTF-8");
PrintWriter writer = null;
try {
writer = response.getWriter();
//把得到的数据,包装到Resuest中返回
writer.write(JSON.toJSONString(object));
} catch (IOException e) {
logger.error(e.getMessage() , e);
} finally {
// IOUtils.close(writer);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy