E1ED922C1E9526DD63272D7EC5C6CB77
2020-09-27 89ac7f9b30215669a15fb4fec39d698cb1892c6d
提交 | 用户 | age
5c5945 1 package com.hx.common;
E 2
3 import com.hx.exception.ParamException;
4 import com.hx.exception.ServiceException;
5 import org.springframework.beans.propertyeditors.CustomDateEditor;
6 import org.springframework.web.bind.WebDataBinder;
7 import org.springframework.web.bind.annotation.InitBinder;
8 import org.springframework.web.context.request.RequestContextHolder;
9 import org.springframework.web.context.request.ServletRequestAttributes;
10 import org.springframework.web.context.request.WebRequest;
11
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpSession;
14 import java.text.DateFormat;
15 import java.text.SimpleDateFormat;
16 import java.util.Date;
17
18
19 /**公共初始化
20  * @author ChenJiaHe
21  * @Date 2020-06-11
22  */
23
89ac7f 24 public class BaseController {
5c5945 25
E 26     /*请不要声明变量,会导致不安全,因为这个是单列*/
27
28     //只需要加上下面这段即可,注意不能忘记注解
29     @InitBinder
30     public void initBinder(WebDataBinder binder, WebRequest request) {
31         //转换日期 注意这里的转化要和传进来的字符串的格式一直 如2015-9-9 就应该为yyyy-MM-dd
32         DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
33         binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
34     }
35
36     public HttpServletRequest getRequest() {
37         //获取参数对象
38         ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
89ac7f 39         return attributes.getRequest();
5c5945 40     }
E 41
42     public HttpSession getSession() {
43         //获取参数对象
89ac7f 44         return getRequest() .getSession();
5c5945 45     }
E 46
47     /**
48      * 获取request里某个属性
49      * @param attrName 属性名称
50      * @return 对象
51      */
52     public Object getRequestAttribute(String attrName)
53     {
54         return getRequest().getAttribute(attrName);
55     }
56
57     /**
58      * 设置一个request属性
59      * @param attrName 属性名称
60      * @param attrObject 属性值
61      */
62     public void setRequestAttribute(String attrName, Object attrObject) {
63         getRequest().setAttribute(attrName, attrObject);
64     }
65
66     /**
67      * 抛出服务异常
68      * @param msg 错误信息
69      */
70     public void throwServiceException(String msg)
71     {
72         throw new ServiceException(msg);
73     }
74
75     /**
76      * 抛出参数异常
77      * @param msg 错误信息
78      */
79     public void throwParamException(String msg)
80     {
81         throw new ParamException(msg);
82     }
83
84 }