📄 actionservlet.java
字号:
package com.easyjf.web;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
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.ServletContextEvent;
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.exception.MethodInvocationException;
import com.easyjf.container.Container;
import com.easyjf.container.impl.DefaultContainer;
import com.easyjf.util.StringUtils;
import com.easyjf.web.ajax.AjaxServiceContainer;
import com.easyjf.web.ajax.AjaxUtil;
import com.easyjf.web.config.DefaultWebConfig;
import com.easyjf.web.core.DefaultRequestProcessor;
import com.easyjf.web.core.FrameworkEngine;
import com.easyjf.web.core.RequestScope;
import com.easyjf.web.core.SessionScope;
import com.easyjf.web.exception.FrameworkException;
import com.easyjf.web.interceptor.IRequestInterceptor;
import com.easyjf.web.interceptor.InterceptorException;
/**
*
* <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 implements
javax.servlet.ServletContextListener {
static final long serialVersionUID = 887867880L;
private static final Logger logger =Logger.getLogger(ActionServlet.class);
public static final String DEFAULT_OUTPUT_ENCODING = "UTF-8";
public static final String EASYJWEB_CONFIGURE_KEY="easyjwebConfigLocation";
//public static final String SERVLET_CONTEXT_KEY = ServletContext.class.getName();
//
private WebConfig webConfig=new DefaultWebConfig();
private Container container;
private RequestProcessor processor;
private String defaultContentType;
private boolean warnOfOutputStreamDeprecation = true;
public void init(ServletConfig config) throws ServletException {
super.init(config);
initEasyJWeb();
this.getServletContext().setAttribute(Globals.CONTAINER_CONTEXT,container);
logger.debug("Servlet配置初始化");
}
protected void initEasyJWeb()throws ServletException
{
logger.debug("执行EasyJWeb初始化应用程序!");
Globals.APP_BASE_DIR = this.getServletContext().getRealPath("/");
webConfig.setConfigures(getConfigure());
webConfig.init();
initContainer();
FrameworkEngine.setWebConfig(webConfig);//初始化框架工具
FrameworkEngine.setContainer(container);//在引擎中安装容器
AjaxUtil.setServiceContainer(new AjaxServiceContainer(container));
initTemplate(this.getServletConfig());
invokeApps();
}
protected void initContainer()
{
DefaultContainer c=new DefaultContainer();
c.registerBeanDefinitions(webConfig.getBeanDefinitions());
c.registerScope("request",new RequestScope());
c.registerScope("session",new SessionScope());
c.refresh();
this.container=c;
}
private java.io.InputStream[] getConfigure()
{
InputStream[] is=null;
String paravalue=this.getServletContext().getInitParameter(EASYJWEB_CONFIGURE_KEY);
if(!StringUtils.hasLength(paravalue))paravalue=Globals.CONFIG_FILE;
String[] s=StringUtils.tokenizeToStringArray(paravalue,",");
is=new InputStream[s.length+1];
for(int i=0;i<s.length;i++)
{
is[i]=this.getServletContext().getResourceAsStream(s[i]);
}
is[s.length]=this.getClass().getResourceAsStream("/com/easyjf/web/easyjf-web.xml");
return is;
}
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);
}
public void destroy() {
destroyApps();
super.destroy();
}
/**
* 初始化模板
*
* @param config
* @throws ServletException
*/
protected void initTemplate(ServletConfig config) throws ServletException {
Properties p = new Properties();
p.setProperty("resource.loader","file,class");
p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
if (!StringUtils.hasLength(webConfig.getTemplateBasePath()))webConfig.setTemplateBasePath(Globals.DEFAULT_TEMPLATE_PATH);
String realTemplatePath = webConfig.getTemplateBasePath();
File file = new File(webConfig.getTemplateBasePath());
if (!file.exists())
realTemplatePath = config.getServletContext().getRealPath(webConfig.getTemplateBasePath());
p.setProperty("file.resource.loader.path", realTemplatePath);
try {
Velocity.init(p);
} catch (Exception e) {
logger.error("初始化模板错误! - " + e);
throw new ServletException(e);
}
}
/**
* 处理用户请求
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
protected void doRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 初始化Request
try {
doInitRequest(request, response);
setContentType(request, response);
if(processor==null)processor= new DefaultRequestProcessor(this,webConfig);
//RequestProcessor processor= new DefaultRequestProcessor(this,webConfig);
processor.process(request, response);
} catch (Throwable e) {
logger.error("ActionServlet出现严重错误:" + e);
if(webConfig.isDebug())error(request, response, e);
else info(request, response, e);
}
}
protected void 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.isDebug()) {// 调试模式每次都要初始化配置文件
initEasyJWeb();
}
//invokeInterceptors(response);
}
protected void doErrorHandler() throws InterceptorException
{
}
// 执行拦截操作
protected void invokeInterceptors(HttpServletResponse response)
throws Exception {
Iterator interceptors =webConfig.getInterceptors().values().iterator();
if (interceptors != null) {
while (interceptors.hasNext()) {
IRequestInterceptor interceptor = (IRequestInterceptor) interceptors
.next();
Object result = interceptor.doIntercept();
if (result instanceof Page) {
response.sendRedirect(((Page) result).getUrl());
}
// else if(result instanceof )
}
}
}
protected void setContentType(HttpServletRequest request,
HttpServletResponse response) {
response.setContentType(defaultContentType);
}
// 在应用启动的时候启动一些配置好的应用;比如后台的监控线程等;
protected void invokeApps() {
List apps = webConfig.getInitApps();
for (int i = 0; i < apps.size(); i++) {
try {
Map app = (Map) apps.get(i);
Method init = (Method) app.get("init-method");
if (init != null) {
init.invoke(app.get("classname"), null);
}
} catch (Exception e) {
throw new FrameworkException("初始化程序运行出现异常!",e);
}
}
}
// 停止启动的应用;
protected void destroyApps() {
List apps = webConfig.getInitApps();
for (int i = 0; i < apps.size(); i++) {
try {
Map app = (Map) apps.get(i);
Method des = (Method) app.get("destroy-method");
if (des != null) {
des.invoke(app.get("classname"), null);
}
} catch (Exception e) {
throw new FrameworkException("初始化程序结束出现异常!",e);
}
}
}
/**
* 输出系统框架错误信息提示
*
* @param request
* @param response
* @param e
* @throws ServletException
*/
protected void error(HttpServletRequest request,
HttpServletResponse response, Throwable 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,Throwable 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);
}
}
public 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 void contextDestroyed(ServletContextEvent sce) {
}
public void contextInitialized(ServletContextEvent sce) {
try{
init(this.getServletConfig());
}
catch(Exception e)
{
throw new java.lang.RuntimeException("系统初始化错误!");
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -