用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中配置了, 很灵活。