提交 | 用户 | 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; |
5c5945
|
30 |
/*请不要声明变量,会导致不安全,因为这个是单列*/ |
E |
31 |
|
|
32 |
//只需要加上下面这段即可,注意不能忘记注解 |
|
33 |
@InitBinder |
|
34 |
public void initBinder(WebDataBinder binder, WebRequest request) { |
|
35 |
//转换日期 注意这里的转化要和传进来的字符串的格式一直 如2015-9-9 就应该为yyyy-MM-dd |
|
36 |
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); |
|
37 |
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器 |
|
38 |
} |
|
39 |
|
|
40 |
public HttpServletRequest getRequest() { |
|
41 |
//获取参数对象 |
|
42 |
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); |
89ac7f
|
43 |
return attributes.getRequest(); |
5c5945
|
44 |
} |
E |
45 |
|
|
46 |
public HttpSession getSession() { |
|
47 |
//获取参数对象 |
89ac7f
|
48 |
return getRequest() .getSession(); |
5c5945
|
49 |
} |
E |
50 |
|
|
51 |
/** |
|
52 |
* 获取request里某个属性 |
|
53 |
* @param attrName 属性名称 |
|
54 |
* @return 对象 |
|
55 |
*/ |
|
56 |
public Object getRequestAttribute(String attrName) |
|
57 |
{ |
|
58 |
return getRequest().getAttribute(attrName); |
|
59 |
} |
|
60 |
|
|
61 |
/** |
|
62 |
* 设置一个request属性 |
|
63 |
* @param attrName 属性名称 |
|
64 |
* @param attrObject 属性值 |
|
65 |
*/ |
|
66 |
public void setRequestAttribute(String attrName, Object attrObject) { |
|
67 |
getRequest().setAttribute(attrName, attrObject); |
|
68 |
} |
|
69 |
|
|
70 |
/** |
|
71 |
* 抛出服务异常 |
|
72 |
* @param msg 错误信息 |
|
73 |
*/ |
|
74 |
public void throwServiceException(String msg) |
|
75 |
{ |
|
76 |
throw new ServiceException(msg); |
|
77 |
} |
|
78 |
|
|
79 |
/** |
|
80 |
* 抛出参数异常 |
|
81 |
* @param msg 错误信息 |
|
82 |
*/ |
|
83 |
public void throwParamException(String msg) |
|
84 |
{ |
|
85 |
throw new ParamException(msg); |
|
86 |
} |
|
87 |
|
|
88 |
} |