BaseController.java
2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package com.diligrp.website.util.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.diligrp.website.util.web.exception.WebException;
/**
* BaseController
*
*/
public class BaseController extends VelocitySupport {
protected final static String DEFAULT_CHARTSET = "UTF-8";
protected final static String DEFAULT_JSON_CONTENT_TYPE = "application/json;charset="
+ DEFAULT_CHARTSET;
/**
* 输出文本
*
* @param txt
* @param contextType
*/
protected void write(HttpServletResponse response, String txt,
String contextType) {
try {
if (StringUtils.isEmpty(txt)) {
return;
}
response.setContentType(contextType);
response.getOutputStream().write(txt.getBytes(DEFAULT_CHARTSET));
} catch (Exception ex) {
throw new WebException(ex);
}
}
/**
* 输出JSON对象
*
* @param model
*/
protected void writeJSON(HttpServletResponse response, Object model) {
write(response, JSON.toJSONString(model), DEFAULT_JSON_CONTENT_TYPE);
}
protected Map<String, Object> getDefaultContext() {
Map<String, Object> context = new HashMap<String, Object>();
return context;
}
protected ViewBuilder toView(String template) {
ViewBuilder vb = new ViewBuilder(template, this);
return vb;
}
/**
* java bean to json
*
* @param object
* @return
*/
protected String objectToJSON(Object object) {
// try {
// return new ObjectMapper().writeValueAsString(object);
// } catch (JsonGenerationException e) {
// e.printStackTrace();
// } catch (JsonMappingException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
return "";
}
/**
* json to java bean
*
* @param <T>
* @param jsonStr
* @param t
* @return
*/
protected <T> T JSONToObject(String jsonStr, Class<T> t) {
// try {
// return new ObjectMapper().readValue(jsonStr, t);
// } catch (JsonParseException e) {
// e.printStackTrace();
// } catch (JsonMappingException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
return null;
}
protected void writeStringToResponse(HttpServletResponse response,
String text) throws IOException {
response.setContentType("text/plain;charset=UTF-8");
PrintWriter out = response.getWriter();
out.write(text);
}
}