实现简单配置的servlet单入口

更新:这个方法跟重不重启并没有关系,修改后的class要reload之后才会生效,这个可在tomcat的后台里reload,不用重启整个服务器。

用servlet做一些游戏的后台挺不错,不过每个servlet都要在web.xml中配置路径映射也很麻烦。其实如果我们实现servlet单入口,即只定义一个Servlet,然后在这个Servlet中处理转发,就可以免去这些麻烦了。下面是一些步骤。

1、定义处理器接口IAction。真正的处理器都继承自这个接口,接口很简单,只有一个方法,
import javax.servlet.http.HttpServletRequest;

/**
 * Action接口,用于执行真正的处理操作
 */
public interface IAction {
    public String execute(HttpServletRequest request);
}
2、编写调度的Servlet,主要代码:
// Action后缀,如/First对应FirstAction类
private static final String ACTION_EXT="Action";
// 自定义Action处理器所在的包名
private static final String PACKAGE_NAME="com.xxx.";

-----------------

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    // 根据url找到对应的action
    String uri=request.getRequestURI();
    String path=request.getContextPath();
    String actionName=uri.substring(path.length()+1)+ACTION_EXT;
    String fullActionName=PACKAGE_NAME+actionName;
    IAction action=null;
    try {
        Class<?> ref=Class.forName(fullActionName);
        action=(IAction)ref.newInstance();
    }
    catch (Exception e)
    {
    }
    if (action!=null)
    {
        out.println(action.execute(request));
    }
    else
    {
        out.println("Error: "+actionName+" not found.");
    }
}
3、配置,
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>lib.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>
让DispatcherServlet接管所有的url。

之后编写的Action就可以不用在XML中配置了, 很灵活。

转载于:https://my.oschina.net/lonewolf/blog/348210

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值