首页 > 代码库 > OSChina 源码之 ActionServlet 控制类

OSChina 源码之 ActionServlet 控制类

ActionServlet 这个类在 OSChina 是负责处理表单请求的,所有以 /action 开头的请求,自己感觉还不甚满意,别拍我砖头。示例action类: FileAction
标签: OSCHINA MVC Servlet

[1].[代码] ActionServlet.java 跳至 [1]

?
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
packagemy.mvc;
 
importjava.io.*;
importjava.lang.reflect.*;
importjava.net.URLDecoder;
importjava.util.*;
 
importjavax.servlet.*;
importjavax.servlet.http.*;
 
importmy.db.DBException;
importmy.util.ResourceUtils;
 
importorg.apache.commons.lang.StringUtils;
importorg.apache.commons.lang.math.NumberUtils;
 
/**
 * 业务处理方法入口,URI的映射逻辑:
 * /action/xxxxxx/xxxx -> com.dlog4j.action.XxxxxxAction.xxxx(req,res)
 * <pre>
    林花谢了春红,
    太匆匆,
    无奈朝来寒雨晚来风。
 
    胭脂泪,
    相留醉,
    几时重,
    自是人生长恨水长东。
 * </pre>
 * @author Winter Lau (http://my.oschina.net/javayou)<br> */
publicfinal class ActionServlet extendsHttpServlet {
 
    privatefinal static String ERROR_PAGE = "error_page";
    privatefinal static String GOTO_PAGE = "goto_page";
    privatefinal static String THIS_PAGE = "this_page";
    privatefinal static String ERROR_MSG = "error_msg";
     
    privatefinal static String UTF_8 = "utf-8";   
    privateList<String> action_packages = null;
    privatefinal static ThreadLocal<Boolean> g_json_enabled = newThreadLocal<Boolean>();
     
    @Override
    publicvoid init() throwsServletException {
        String tmp = getInitParameter("packages");
        action_packages = Arrays.asList(StringUtils.split(tmp,‘,‘));
        String initial_actions = getInitParameter("initial_actions");
        for(String action : StringUtils.split(initial_actions,‘,‘))
            try{
                _LoadAction(action);
            }catch(Exception e) {
                log("Failed to initial action : " + action, e);
            }
    }
 
    @Override
    publicvoid destroy() {
        for(Object action : actions.values()){
            try{
                Method dm = action.getClass().getMethod("destroy");
                if(dm != null){
                    dm.invoke(action);
                    log("!!!!!!!!! " + action.getClass().getSimpleName() +
                        " destroy !!!!!!!!!");
                }
            }catch(NoSuchMethodException e){
            }catch(Exception e){
                log("Unabled to destroy action: " + action.getClass().getSimpleName(), e);
            }
        }
        super.destroy();
    }
     
    @Override
    protectedvoid doGet(HttpServletRequest req, HttpServletResponse resp)
            throwsServletException, IOException {
        process(RequestContext.get(),false);
    }
 
    @Override
    protectedvoid doPost(HttpServletRequest req, HttpServletResponse resp)
            throwsServletException, IOException {
        process(RequestContext.get(),true);
    }
     
    /**
     * 执行Action方法并进行返回处理、异常处理
     * @param req
     * @param resp
     * @param is_post
     * @throws ServletException
     * @throws IOException
     */
    protectedvoid process(RequestContext req, booleanis_post)
        throwsServletException, IOException
    {
        try{
            req.response().setContentType("text/html;charset=utf-8");
            if(_process(req, is_post)){
                String gp = req.param(GOTO_PAGE);
                if(StringUtils.isNotBlank(gp))
                    req.redirect(gp);
            }
        }catch(InvocationTargetException e){
            Throwable t = e.getCause();
            if(tinstanceofActionException)
                handleActionException(req, (ActionException)t);
            elseif(tinstanceofDBException)
                handleDBException(req, (DBException)t);
            else
                thrownew ServletException(t);
        }catch(ActionException t){
            handleActionException(req, t);
        }catch(IOException e){
            throwe;
        }catch(DBException e){
            handleDBException(req, e);
        }catch(Exception e){
            log("Exception in action process.", e);
            thrownew ServletException(e);
        }finally{
            g_json_enabled.remove();
        }
    }
     
    /**
     * Action业务异常
     * @param req
     * @param resp
     * @param t
     * @throws ServletException
     * @throws IOException
     */
    protectedvoid handleActionException(RequestContext req, ActionException t)
        throwsServletException, IOException
    {      
        handleException(req, t.getMessage());
    }
     
    protectedvoid handleDBException(RequestContext req, DBException e)
        throwsServletException, IOException
    {
        log("DBException in action process.", e);
        handleException(req, ResourceUtils.getString("error",
            "database_exception", e.getCause().getMessage()));
    }
     
    /**
     * URL解码
     *
     * @param url
     * @param charset
     * @return
     */
    privatestatic String _DecodeURL(String url, String charset) {
        if(StringUtils.isEmpty(url))
            return"";
        try{
            returnURLDecoder.decode(url, charset);
        }catch(Exception e) {
        }
        returnurl;
    }
 
    protectedvoid handleException(RequestContext req, String msg)
        throwsServletException, IOException
    {
        String ep = req.param(ERROR_PAGE);
        if(StringUtils.isNotBlank(ep)){
            if(ep.charAt(0)==‘%‘)
                ep = _DecodeURL(ep, UTF_8);
            ep = ep.trim();
            if(ep.charAt(0)!=‘/‘){
                req.redirect(req.contextPath()+"/");
            }
            else{
                req.request().setAttribute(ERROR_MSG, msg);
                req.forward(ep.trim());
            }
        }
        else{
            if(g_json_enabled.get())
                req.output_json("msg", msg);
            else
                req.print(msg);
        }
    }  
     
    /**
     * 业务逻辑处理
     * @param req
     * @param resp
     * @param is_post_method
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws IOException
     * @throws ServletException
     * @throws IOException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     */
    privateboolean _process(RequestContext req, booleanis_post)
             throwsInstantiationException,
                    IllegalAccessException,
                    IOException,
                    IllegalArgumentException,
                    InvocationTargetException
    {
        String requestURI = req.uri();
        String[] parts = StringUtils.split(requestURI, ‘/‘);
        if(parts.length<2){
            req.not_found();
            returnfalse;
        }
        //加载Action类
        Object action = this._LoadAction(parts[1]);
        if(action == null){
            req.not_found();
            returnfalse;
        }
        String action_method_name = (parts.length>2)?parts[2]:"index";
        Method m_action = this._GetActionMethod(action, action_method_name);
        if(m_action == null){
            req.not_found();
            returnfalse;
        }
         
        //判断action方法是否只支持POST
        if(!is_post && m_action.isAnnotationPresent(Annotation.PostMethod.class)){
            req.not_found();
            returnfalse;
        }
         
        g_json_enabled.set(m_action.isAnnotationPresent(Annotation.JSONOutputEnabled.class));
         
        if(m_action.isAnnotationPresent(Annotation.UserRoleRequired.class)){
            IUser loginUser = req.user();
            if(loginUser == null){
                String this_page = req.param(THIS_PAGE, "");
                throwreq.error("user_not_login", this_page);
            }
            if(loginUser.IsBlocked())
                throwreq.error("user_blocked");
             
            Annotation.UserRoleRequired urr = (Annotation.UserRoleRequired)
                m_action.getAnnotation(Annotation.UserRoleRequired.class);
            if(loginUser.getRole() < urr.role())
                throwreq.error("user_role_deny");         
        }
         
        //调用Action方法之准备参数
        intarg_c = m_action.getParameterTypes().length;
        switch(arg_c){
        case0:// login()
            m_action.invoke(action);
            break;
        case1:
            m_action.invoke(action, req);
            break;
        case2:// login(HttpServletRequest req, HttpServletResponse res)
            m_action.invoke(action, req.request(), req.response());
            break;
        case3:// login(HttpServletRequest req, HttpServletResponse res, String[] extParams)
            StringBuilder args = newStringBuilder();
            for(inti=3;i<parts.length;i++){
                if(StringUtils.isBlank(parts[i]))
                    continue;
                if(args.length() > 0)
                    args.append(‘/‘);
                args.append(parts[i]);
            }
            booleanisLong = m_action.getParameterTypes()[2].equals(long.class);
            m_action.invoke(action, req.request(), req.response(), isLong ? NumberUtils.toLong(
                    args.toString(), -1L) : args.toString());
            break;
        default:
            req.not_found();
            returnfalse;
        }
         
        returntrue;
    }
     
    /**
     * 加载Action类
     * @param act_name
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws ClassNotFoundException
     */
    protectedObject _LoadAction(String act_name)
        throwsInstantiationException,IllegalAccessException
    {
        Object action = actions.get(act_name);
        if(action == null){
            for(String pkg : action_packages){
                String cls = pkg + ‘.‘+ StringUtils.capitalize(act_name) + "Action";
                action = _LoadActionOfFullname(act_name, cls);
                if(action != null)
                    break;
            }
        }
        returnaction ;
    }
     
    privateObject _LoadActionOfFullname(String act_name, String cls)
        throwsIllegalAccessException, InstantiationException
    {
        Object action = null;
        try{                              
            action = Class.forName(cls).newInstance();
            try{
                Method action_init_method = action.getClass().getMethod("init", ServletContext.class);
                action_init_method.invoke(action, getServletContext());
            }catch(NoSuchMethodException e){
            }catch(InvocationTargetException excp) {
                excp.printStackTrace();
            }
            if(!actions.containsKey(act_name)){
                synchronized(actions){
                    actions.put(act_name, action);
                }
            }
        }catch(ClassNotFoundException excp) {}
        returnaction;
    }
     
    /**
     * 获取名为{method}的方法
     * @param action
     * @param method
     * @return
     */
    privateMethod _GetActionMethod(Object action, String method) {
        String key = action.getClass().getSimpleName() + ‘.‘+ method;
        Method m = methods.get(key);
        if(m != null)returnm;
        for(Method m1 : action.getClass().getMethods()){
            if(m1.getModifiers()==Modifier.PUBLIC && m1.getName().equals(method)){
                synchronized(methods){
                    methods.put(key, m1);
                }
                returnm1 ;
            }
        }
        returnnull;
    }
 
    privatefinal static HashMap<String, Object> actions = newHashMap<String, Object>();
    privatefinal static HashMap<String, Method> methods = newHashMap<String, Method>();
 
}

OSChina 源码之 ActionServlet 控制类