在一些老的系统中,需要新增后台servlet,但又不想动配置,害怕配置越来越多的时候,可以考虑使用以下技巧。
1:创建一个action接口类
public interface AbstractAction {
public abstract void execute() throws IOException, ServletException;
}
2:创建一个servlet类
public class ServiceAction extends HttpServlet {
private static final String strContentType = "text/html; charset=UTF-8";
protected final Log logger = LogFactory.getLog(getClass());
public ServiceAction() {}
public void destroy() {}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType(strContentType);
// response.setCharacterEncoding("UTF-8");
String strRequestURI = request.getRequestURI();// 取得完整的请求URL
// *******取出请求URL中所包含的相关 Action 类的信息,并存入 strRequestType
// 变量中(start)*******//
int index = strRequestURI.lastIndexOf("/");
int index2 = strRequestURI.indexOf("?");
String strRequestType;
if (index2 == -1){
strRequestType = strRequestURI.substring(index + 1);
}else{
strRequestType = strRequestURI.substring(index2 - 1);
}
AbstractAction objAbstractAction = null;// 所有 Action 类需实现的接口的声明
if (strRequestType == null || strRequestType.equalsIgnoreCase("")) return;
// *******取出请求URL中所包含的相关 Action 类的信息,并存入 strRequestType
// 变量中(end)*******//
try {
// *******根据 strRequestType 变量中包含的信息创建相应的 Action 类(start)*******//
Class clazz = Class.forName(strRequestType);
Constructor ctor = clazz.getConstructor(new Class[] {
HttpServletRequest.class, HttpServletResponse.class });
objAbstractAction = (AbstractAction) ctor.newInstance(new Object[] {
request, response });
// *******根据 strRequestType 变量中包含的信息创建相应的 Action 类(end)*******//
} catch (Exception ex) {
logger.error(
new StringBuffer("Could not Instance ")
.append(strRequestType).append(" Class").toString(),
ex);
}
if (objAbstractAction != null)
objAbstractAction.execute();// 执行相应的 Action 类中的方法
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public void init() throws ServletException {}
}
3.配置web.xml
<servlet>
<servlet-name>ServiceAction</servlet-name>
<servlet-class>xxx.xxxx.xxxxx.ServiceAction</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServiceAction</servlet-name>
<url-pattern>/ServiceAction/*</url-pattern>
</servlet-mapping>
注:xxx.xxxx.xxxxx.ServiceAction 请改为实际ServiceAction所在路径
4.完成啦!后续新增servlet的话,直接写一个action类实现AbstractAction就可以啦
示例:TestAction
public class TestAction implements AbstractAction{
private HttpServletRequest request;
private HttpServletResponse response;
public TestAction(HttpServletRequest request,HttpServletResponse response){
this.request = request;
this.response = response;
}
@Override
public void execute() throws IOException, ServletException {
response.getWriter().write("测试action");
response.getWriter().close();
}
}
访问后台TestAction 的路径:/ServiceAction/xxx.xxxx.xxxxx.TestAction?action=xxx
这种方法仅适合针对于一些老的系统,不方便使用spring注解等手段的,也算是减少配置增加的一种方式了。