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