?? actionservlet.java
字號:
package com.easyjf.web;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.util.SimplePool;
import com.easyjf.web.config.WebConfig;
/**
*
* <p>
* Title:EasyJWeb核心Servlet
* </p>
* <p>
* Description: EasyJWeb核心Servlet,所有的.ejf訪問都將由該Servlet處理
* 用戶必須在web.xml文件指定擴展名為.ejf的訪問都指向該類或其子類。
* </p>
* <p>
* Copyright: Copyright (c) 2006
* </p>
* <p>
* Company: www.easyjf.com
* </p>
*
* @author 蔡世友
* @version 1.0
*/
public class ActionServlet extends HttpServlet {
static final long serialVersionUID = 8880L;
private static final Logger logger = (Logger) Logger
.getLogger(ActionServlet.class.getName());
public static final String DEFAULT_OUTPUT_ENCODING = "UTF-8";
public static final String SERVLET_CONTEXT_KEY = ServletContext.class
.getName();
private static SimplePool writerPool = new SimplePool(60);
private String defaultContentType;
private boolean warnOfOutputStreamDeprecation = true;
public void init(ServletConfig config) throws ServletException {
super.init(config);
Globals.CONFIG_FILE_FULL_PATH = getServletConfig().getServletContext()
.getRealPath(Globals.CONFIG_FILE);
Globals.APP_BASE_DIR = getServletConfig().getServletContext()
.getRealPath("/");
// logger.info("init");
WebConfig.getInstance().init();
// logger.info("do init apps");
List apps = WebConfig.getInstance().getInitApps();
// logger.info("apps.size:"+apps.size());
for (int i = 0; i < apps.size(); i++) {
try {
Map app = (Map) apps.get(i);
Method init = (Method) app.get("init");
if (init != null) {
init.invoke(app.get("classname"), null);
// logger.info("init app:"+init.getClass().getName()+"init
// method"+init.getName());
}
} catch (Exception e) {
}
}
initTemplate(config);
}
public void destroy() {
// TODO Auto-generated method stub
List apps = WebConfig.getInstance().getInitApps();
for (int i = 0; i < apps.size(); i++) {
try {
Map app = (Map) apps.get(i);
Method des = (Method) app.get("destroy");
if (des != null) {
des.invoke(app.get("classname"), null);
System.out.println("destroy app:"
+ des.getClass().getName() + "destroy method"
+ des.getName());
}
} catch (Exception e) {
}
}
super.destroy();
}
/**
* 初始化模板
*
* @param config
* @throws ServletException
*/
protected void initTemplate(ServletConfig config) throws ServletException {
Velocity.setApplicationAttribute(SERVLET_CONTEXT_KEY,
getServletContext());
Properties p = new Properties();
if (WebConfig.getInstance().getTemplateBasePath() == null
|| WebConfig.getInstance().getTemplateBasePath().equals(""))
WebConfig.getInstance().setTemplateBasePath(
Globals.DEFAULT_TEMPLATE_PATH);
String realTemplatePath = WebConfig.getInstance().getTemplateBasePath();
File file = new File(WebConfig.getInstance().getTemplateBasePath());
if (!file.exists())
realTemplatePath = config.getServletContext().getRealPath(
WebConfig.getInstance().getTemplateBasePath());
p.setProperty("file.resource.loader.path", realTemplatePath);
// System.out.println(realTemplatePath);
try {
Velocity.init(p);
} catch (Exception e) {
logger.error("ActionServlet: PANIC! unable to init() - " + e);
throw new ServletException(e);
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doRequest(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doRequest(request, response);
}
/**
* 處理用戶請求
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
protected void doRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 初始化Request
try {
doInitRequest(request, response);
} catch (Exception e) {
info(request, response, e);
return;
}
Context context = null;
try {
setContentType(request, response);
RequestProcessor rp = new RequestProcessor(this);
rp.process(request, response);
} catch (Exception e) {
logger.error("ActionServlet出現嚴重錯誤:" + e);
error(request, response, e);
} finally {
requestCleanup(request, response, context);
}
}
protected boolean doInitRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
Map map = new HashMap();
map.put(ActionContext.HTTP_REQUEST, request);
map.put(ActionContext.HTTP_RESPONSE, response);
ActionContext.setContext(new ActionContext(map));
if (WebConfig.getInstance().isDebug()) {// 調試模式每次都要初始化配置文件
WebConfig.getInstance().init();// 初始化配置文件
initTemplate(getServletConfig()); // 初始化模版
}
// 執行攔截操作
Iterator interceptors = FrameworkEngine.getRequestInterceptors();
if (interceptors != null) {
while (interceptors.hasNext()) {
IRequestInterceptor interceptor = (IRequestInterceptor) interceptors
.next();
Object result = interceptor.doIntercept();
if (result instanceof Page) {
response.sendRedirect(((Page) result).getUrl());
return false;
}
// else if(result instanceof )
}
}
return true;
}
// 清除request中的相關資料,此處為空
protected void requestCleanup(HttpServletRequest request,
HttpServletResponse response, Context context) {
}
protected void setContentType(HttpServletRequest request,
HttpServletResponse response) {
response.setContentType(defaultContentType);
}
/**
* 輸出系統框架錯誤信息提示
*
* @param request
* @param response
* @param e
* @throws ServletException
*/
protected void error(HttpServletRequest request,
HttpServletResponse response, Exception e) throws ServletException {
try {
StringBuffer html = new StringBuffer();
String title = request.getCharacterEncoding() != null ? "EasyJWeb框架錯誤"
: "EasyJWeb Framework error";
html.append("<html>\n");
html.append("<head><title>" + title + "</title></head>\n");
html.append("<body>\n");
html.append(title + ":\n<br>");
Throwable cause = e;
String why = cause.getMessage();
html.append("<font color=red>");
if (why != null && why.trim().length() > 0) {
html.append(why);
html
.append("\n<br>詳細請查詢<a href='http://www.easyjf.com/' target='_blank'>http://www.easyjf.com</a>\n");
}
if (cause instanceof MethodInvocationException) {
cause = ((MethodInvocationException) cause)
.getWrappedThrowable();
}
html.append("</font>");
StringWriter sw = new StringWriter();
cause.printStackTrace(new PrintWriter(sw));
html.append("<pre>\n");
html.append(sw.toString());
html.append("</pre>\n");
html.append("</body>\n");
html.append("</html>");
if (request.getCharacterEncoding() != null)
response.setContentType("text/html; charset="
+ request.getCharacterEncoding());
getResponseWriter(response).write(html.toString());
} catch (Exception e2) {
logger
.error("ActionServlet: Exception while printing error screen: "
+ e2);
throw new ServletException(e);
}
}
protected void info(HttpServletRequest request,
HttpServletResponse response, Exception e) throws ServletException {
try {
StringBuffer html = new StringBuffer();
String title = request.getCharacterEncoding() != null ? "EasyJWeb框架友情提示!:-)"
: "EasyJWeb Framework Friendly Info!";
html.append("<html>\n");
html.append("<head><title>" + title + "</title></head>\n");
html.append("<body>\n");
html.append(title + ":\n<br>");
Throwable cause = e;
String why = cause.getMessage();
html.append("<font color=red>");
if (why != null && why.trim().length() > 0) {
html.append(why);
html
.append("\n<br>詳細請查詢<a href='http://www.easyjf.com/' target='_blank'>http://www.easyjf.com</a>\n");
}
if (cause instanceof MethodInvocationException) {
cause = ((MethodInvocationException) cause)
.getWrappedThrowable();
}
html.append("</font>");
html.append("</body>\n");
html.append("</html>");
if (request.getCharacterEncoding() != null)
response.setContentType("text/html; charset="
+ request.getCharacterEncoding());
getResponseWriter(response).write(html.toString());
} catch (Exception e2) {
logger
.error("ActionServlet: Exception while printing error screen: "
+ e2);
throw new ServletException(e);
}
}
protected Writer getResponseWriter(HttpServletResponse response)
throws UnsupportedEncodingException, IOException {
Writer writer = null;
try {
writer = response.getWriter();
} catch (IllegalStateException e) {
if (this.warnOfOutputStreamDeprecation) {
this.warnOfOutputStreamDeprecation = false;
}
String encoding = response.getCharacterEncoding();
if (encoding == null) {
encoding = DEFAULT_OUTPUT_ENCODING;
}
writer = new OutputStreamWriter(response.getOutputStream(),
encoding);
}
return writer;
}
public static SimplePool getWriterPool() {
return writerPool;
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -