package com.hx.common; import com.hx.exception.ParamException; import com.hx.exception.ServiceException; import com.hx.mybatisTool.SqlParam; import com.hx.mybatisTool.SqlSentence; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; /**公共初始化 * @author ChenJiaHe * @Date 2020-06-11 */ public class CommonInit { /*请不要声明变量,会导致不安全,因为这个是单列*/ protected HttpServletRequest request = null; protected HttpSession session = null; //只需要加上下面这段即可,注意不能忘记注解 @InitBinder public void initBinder(WebDataBinder binder, WebRequest request) { //转换日期 注意这里的转化要和传进来的字符串的格式一直 如2015-9-9 就应该为yyyy-MM-dd DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器 } public HttpServletRequest getRequest() { //获取参数对象 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); request = attributes.getRequest(); return request; } public HttpSession getSession() { //获取参数对象 session = getRequest() .getSession(); return session; } /** * 获取request里某个属性 * @param attrName 属性名称 * @return 对象 */ public Object getRequestAttribute(String attrName) { return getRequest().getAttribute(attrName); } /** * 设置一个request属性 * @param attrName 属性名称 * @param attrObject 属性值 */ public void setRequestAttribute(String attrName, Object attrObject) { getRequest().setAttribute(attrName, attrObject); } /** * 抛出服务异常 * @param msg 错误信息 */ public void throwServiceException(String msg) { throw new ServiceException(msg); } /** * 抛出参数异常 * @param msg 错误信息 */ public void throwParamException(String msg) { throw new ParamException(msg); } }