更新:这个方法跟重不重启并无关系,修改后的class要reload以后才会生效,这个可在tomcat的后台里reload,不用重启整个服务器。
用servlet作一些游戏的后台挺不错,不过每一个servlet都要在web.xml中配置路径映射也很麻烦。其实若是咱们实现servlet单入口,即只定义一个Servlet,而后在这个Servlet中处理转发,就能够免去这些麻烦了。下面是一些步骤。
一、定义处理器接口IAction。真正的处理器都继承自这个接口,接口很简单,只有一个方法,
import javax.servlet.http.HttpServletRequest;
/**
* Action接口,用于执行真正的处理操做
*/
public interface IAction {
public String execute(HttpServletRequest request);
}
二、编写调度的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.");
}
}
三、配置,
<?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中配置了,
很灵活。