web.xml
action-config.xml
ActionServlet.java
Action1.java
用了dom4j解析xml配置文件,希望高手批评执教.
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>testmvc</display-name>
<servlet>
<servlet-name>actionServlet</servlet-name>
<servlet-class>mvc.ActionServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>actionServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
action-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<action-mapping>
<action id="ac1" class="action.Action1"></action>
<action id="ac2" class="action.Action2"></action>
</action-mapping>
ActionServlet.java
public class ActionServlet extends HttpServlet{
private static final String ACTION_CONFIG_NAME = "action-config.xml";
private static Document doc = null;
private static Map<String,String> actionMap = null;
@Override
public void init() throws ServletException {
try {
initConfig();
} catch (DocumentException e) {
e.printStackTrace();
System.exit(-1);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String reqUri = fomartUri(req.getContextPath(), req.getRequestURI());
if(actionMap.containsKey(reqUri)) {
try {
Class clazz = Class.forName(actionMap.get(reqUri));
clazz.getMethod("execute",HttpServletRequest.class,HttpServletResponse.class).invoke(clazz.newInstance(),req,resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void initConfig() throws DocumentException {
SAXReader reader = new SAXReader();
doc = reader.read(ActionServlet.class.getClassLoader().getResourceAsStream(ACTION_CONFIG_NAME));
actionMap = new HashMap<String, String>();
Element element = null;
for(Object obj : doc.selectNodes("/action-mapping/action")) {
element = (Element)obj;
actionMap.put(element.attributeValue("id"), element.attributeValue("class"));
}
}
// /testmvc/ac1.do
private String fomartUri(String contextPath, String str) {
return str.replaceAll(".do", "").replaceAll(contextPath + "/", "");
}
}
Action1.java
public class Action1 {
public void execute(HttpServletRequest req, HttpServletResponse resp) {
try {
resp.getWriter().println(Action1.class.getName());
} catch (IOException e) {
e.printStackTrace();
}
}
}
用了dom4j解析xml配置文件,希望高手批评执教.