configure.xml文件:
该文件主要是框架的配置文件,包括Action,Form(本来准备把JDBC连接池和类Spring IOC的内容也添上的,不过没什么时间了)
有点类似struts-config.xml文件,我写这个的时候,考虑了一下Struts2.x,form-bean干脆改成了pojo了,只需要配置需要填充的属性,这样就比较轻了。然后pojo又可以做持久化对象使用,复用性也比较好。(后来我写了一个Leave Message的实例,可以看看)
配置文件就这么多了。
view plain
1. <?xml version="1.0" encoding="utf-8"?>
2. <view-config>
3. >
4. <jdbc-config>
5. <driver-class-name>com.mysql.jdbc.Driver</driver-class-name>
6. <url>jdbc:mysql://localhost:3306/westdream</url>
7. <user>root</user>
8. <password>123456</password>
9. <max-active>20</max-active>
10. <max-wait>3600</max-wait>
11. </jdbc-config>
12. <view>
13. <forms>
14. <form name="userInfo" class="com.westdream.pojo.Userinfo" >
15. <property name="userName" type="java.lang.String" />
16. <property name="userPwd" type="java.lang.String" />
17. </form>
18. <form name="message" class="com.westdream.pojo.Message" >
19. <property name="title" type="java.lang.String" />
20. <property name="content" type="java.lang.String" />
21. </form>
22. </forms>
23. <action name="userInfo" path="/user" class="com.westdream.action.UserAction" >
24. <result name="success" type="true" path="/success.jsp" />
25. <result name="failure" type="true" path="/failure.jsp" />
26. </action>
27. <action name="message" path="/msg" class="com.westdream.action.MessageAction" >
28. <result name="success" type="true" path="/listMsg.go" />
29. <result name="failure" type="true" path="/failure.jsp" />
30. </action>
31. <action path="/listMsg" class="com.westdream.action.ListMessageAction" >
32. <result name="list" type="true" path="/list.jsp" />
33. </action>
34. </view>
35. </view-config>
ActionServlet.java文件:
ActionServlet的工作主要是加载配置文件,处理请求,根据请求转发到相应的Action上,然后根据Action返回的值,跳转到相应jsp页面。ActionServlet在init方法中调用initConfig方法加载configure.xml到内存(使用JDOM,后面介绍),doGet,doPost内执行同一个方法process。现在具体看一下process方法,截取request URI再从ActionConfig中找到相应的Action,执行Action中的execute方法,根据返回值进行转发。整个过程比较简单,这里还有一点bug,就是跳转类型只有一个forward(redirect忘记处理了,但加载了相应的配置)。这里不多说了
view plain
1. package com.westdream;
2.
3. import java.io.IOException;
4. import java.lang.reflect.InvocationTargetException;
5. import java.lang.reflect.Method;
6. import java.util.List;
7.
8. import javax.servlet.ServletException;
9. import javax.servlet.http.HttpServlet;
10. import javax.servlet.http.HttpServletRequest;
11. import javax.servlet.http.HttpServletResponse;
12.
13.
14. import com.westdream.action.Action;
15. import com.westdream.config.ActionConfig;
16. import com.westdream.config.Configuration;
17. import com.westdream.config.FormConfig;
18. import com.westdream.config.PropertyConfig;
19. import com.westdream.config.ResultConfig;
20.
21.
22. public class ActionServlet extends HttpServlet {
23.
24. private static final long serialVersionUID = 5852463410268904006L;
25. /** 配置文件,默认为CLASSPATH **/
26. public static final String CONFIG_FILE = "configure.xml";
27. private Configuration config = null;
28.
29. public ActionServlet() {
30.
31. }
32.
33. protected void doGet(HttpServletRequest request,
34. throws ServletException, IOException {
35. process(request, response);
36. }
37.
38. protected void doPost(HttpServletRequest request,
39. throws ServletException, IOException {
40. process(request, response);
41. }
42.
43. @Override
44. public void init() throws ServletException {
45. initConfig();
46. }
47.
48. protected void process(HttpServletRequest request,
49. throws ServletException, IOException {
50. String requestURI = request.getRequestURI();
51. ActionConfig actionConfig = config.getActionMappings().get(parseURI(requestURI));
52. try {
53. Action act = (Action)Class.forName(actionConfig.getClassName()).newInstance();
54. null;
55. if(actionConfig.getName() != null) {
56. data = getFormObject(config.getFormMappings().get(actionConfig.getName()),request);
57. }
58. String result = act.execute(request, response, data);
59. ResultConfig resultConfig = actionConfig.getResults().get(result);
60. request.getRequestDispatcher(resultConfig.getPath()).forward(request, response);
61. catch (ClassNotFoundException e) {
62. e.printStackTrace();
63. catch (InstantiationException e) {
64. e.printStackTrace();
65. catch (IllegalAccessException e) {
66. e.printStackTrace();
67. catch (IllegalArgumentException e) {
68. e.printStackTrace();
69. }
70. }
71.
72. protected void initConfig() {
73. config = Configuration.newInstance().configure(getServletContext());
74. }
75.
76. @Override
77. public void destroy() {
78.
79. }
80.
81. /** 解析URI **/
82. protected String parseURI(String uri) {
83. return uri.substring(0, uri.lastIndexOf("."));
84. }
85.
86. /** 将form表单的数据封装成相应的Object **/
87. protected Object getFormObject(FormConfig formConfig, HttpServletRequest request) {
88. /** 如果配置相应的表单,则返回空 **/
89. if(formConfig == null)
90. return null;
91. List<PropertyConfig> props = formConfig.getProperties();
92. null;
93. try {
94. obj = Class.forName(formConfig.getClassName()).newInstance();
95. for(PropertyConfig prop : props) {
96. new StringBuilder("set" + prop.getName());
97. 3, Character.toUpperCase(methodName.charAt(3)));
98. Class<?> typeClass = Class.forName(prop.getType());
99. Method method = obj.getClass().getMethod(methodName.toString(), typeClass);
100. new Object[]{request.getParameter(prop.getName())});
101. }
102. catch (ClassNotFoundException e) {
103. e.printStackTrace();
104. catch (SecurityException e) {
105. e.printStackTrace();
106. catch (NoSuchMethodException e) {
107. e.printStackTrace();
108. catch (IllegalArgumentException e) {
109. e.printStackTrace();
110. catch (IllegalAccessException e) {
111. e.printStackTrace();
112. catch (InvocationTargetException e) {
113. e.printStackTrace();
114. catch (InstantiationException e) {
115. e.printStackTrace();
116. }
117. return obj;
118. }
119. }
Configuration.java文件:
Configuration类主要是利用SAX解析configure.xml,然后加载到相应的配置类中,如ActionConfig,FormConfig等,这里用了JDOM
的包,看看源代码就知道了,很简单。
view plain
1. package com.westdream.config;
2.
3. import java.io.IOException;
4. import java.io.Serializable;
5. import java.util.HashMap;
6. import java.util.List;
7.
8. import javax.servlet.ServletContext;
9.
10. import org.jdom.Attribute;
11. import org.jdom.Document;
12. import org.jdom.Element;
13. import org.jdom.JDOMException;
14. import org.jdom.input.SAXBuilder;
15. import org.jdom.xpath.XPath;
16.
17. public class Configuration implements Serializable, ConfigConstant {
18.
19. private static final long serialVersionUID = -8572272649468107517L;
20.
21. private static Configuration config = null;
22. private HashMap<String, ActionConfig> actionMappings = new HashMap<String, ActionConfig>();
23. private HashMap<String, FormConfig> formMappings = new HashMap<String, FormConfig>();
24. private JDBCConfig jdbcConfig = null;
25.
26. public HashMap<String, FormConfig> getFormMappings() {
27. return formMappings;
28. }
29.
30. private Configuration() {
31.
32. }
33.
34. public static Configuration newInstance() {
35. if (null == config) {
36. new Configuration();
37. }
38. return config;
39. }
40.
41. public Configuration configure(final ServletContext context) {
42. return configure(DEFAULT_CONFIG_FILE, context);
43. }
44.
45. @SuppressWarnings("unchecked")
46. public Configuration configure(final String cfg , final ServletContext context)
47. throws ConfigurationException {
48. if (null == cfg | "".equals(cfg.trim()))
49. throw new ConfigurationException("Configuration file is required.");
50. /** 使用JDOM的SAX解析配置文件 **/
51. new SAXBuilder();
52. try {
53. Document document = saxBuilder.build(Thread.currentThread()
54. .getContextClassLoader().getResourceAsStream(cfg));
55. Element root = document.getRootElement();
56. List<Element> actionElmts = (List<Element>)XPath.selectNodes(root, VIEW_ACTION);
57. for(Element actionElmt : actionElmts) {
58. new ActionConfig();
59. /** 将配置文件的Action属性装配到ActionConfig **/
60. actionConfig.setPath(context.getContextPath() + actionElmt.getAttributeValue(ACTION_ATTRIB_PATH));
61. actionConfig.setClassName(actionElmt.getAttributeValue(ACTION_ATTRIB_CLASS));
62. actionConfig.setName(actionElmt.getAttributeValue(ACTION_ATTRIB_NAME));
63.
64. /** 将配置文件的Action的result子节点装配到ActionConfig **/
65. List<Element> resultElmts = actionElmt.getChildren(ACTION_CHILDREN_RESULT);
66. for(Element resultElmt : resultElmts) {
67. new ResultConfig();
68. Attribute nameAttrib = resultElmt.getAttribute(ACTION_CHILDREN_RESULT_NAME);
69. Attribute pathAttrib = resultElmt.getAttribute(ACTION_CHILDREN_RESULT_PATH);
70. Attribute typeAttrib = resultElmt.getAttribute(ACTION_CHILDREN_RESULT_TYPE);
71. resultConfig.setName(nameAttrib.getValue());
72. resultConfig.setForward(typeAttrib.getBooleanValue());
73. resultConfig.setPath(pathAttrib.getValue());
74. actionConfig.getResults().put(resultConfig.getName(), resultConfig);
75. }
76. /** 将ActionConfig装配到Configuration **/
77. actionMappings.put(actionConfig.getPath(), actionConfig);
78. }
79.
80. /** 将配置文件的form属性装配到FormConfig **/
81. List<Element> formElmts = (List<Element>)XPath.selectNodes(root, VIEW_FORMS_FORM);
82. for(Element formElmt : formElmts) {
83. new FormConfig();
84. formConfig.setName(formElmt.getAttributeValue(FORM_ATTRIB_NAME));
85. formConfig.setClassName(formElmt.getAttributeValue(FORM_ATTRIB_CLASS));
86.
87. List<Element> propertyElmts = formElmt.getChildren(FORM_CHILDREN_PROP);
88. for(Element propertyElmt : propertyElmts) {
89. new PropertyConfig();
90. propertyConfig.setName(propertyElmt.getAttributeValue(FORM_CHILDREN_PROP_NAME));
91. propertyConfig.setType(propertyElmt.getAttributeValue(FORM_CHILDREN_PROP_TYPE));
92. propertyConfig.setValue(propertyElmt.getAttributeValue(FORM_CHILDREN_PROP_VALUE));
93. formConfig.getProperties().add(propertyConfig);
94. }
95. formMappings.put(formConfig.getName(), formConfig);
96. }
97.
98. /** 配置JDBC **/
99. Element driverClassNameElmt = (Element)XPath.selectSingleNode(root, JDBC_DRIVER_CLASS_NAME);
100. Element urlElmt = (Element)XPath.selectSingleNode(root, JDBC_URL);
101. Element userElmt = (Element)XPath.selectSingleNode(root, JDBC_USER);
102. Element passwordElmt = (Element)XPath.selectSingleNode(root, JDBC_PASSWORD);
103. Element maxActiveElmt = (Element)XPath.selectSingleNode(root, JDBC_MAX_ACTIVE);
104. Element maxWaitElmt = (Element)XPath.selectSingleNode(root, JDBC_MAX_WAIT);
105. new JDBCConfig();
106. jdbcConfig.setDriverClassName(driverClassNameElmt.getText());
107. jdbcConfig.setUrl(urlElmt.getText());
108. jdbcConfig.setUser(userElmt.getText());
109. jdbcConfig.setPassword(passwordElmt.getText());
110. jdbcConfig.setMaxActive(Integer.valueOf(maxActiveElmt.getText()));
111. jdbcConfig.setMaxWait(Integer.valueOf(maxWaitElmt.getText()));
112.
113. catch (JDOMException e) {
114. e.printStackTrace();
115. catch (IOException e) {
116. e.printStackTrace();
117. }
118. return config;
119. }
120.
121. public HashMap<String, ActionConfig> getActionMappings() {
122. return actionMappings;
123. }
124.
125. public JDBCConfig getJdbcConfig() {
126. return jdbcConfig;
127. }
128. }
Action.java文件:
Action为抽象类,所有的Action都必须继承该Action基类。
view plain
1. package com.westdream.action;
2.
3. import java.io.IOException;
4.
5. import javax.servlet.ServletException;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8.
9. public abstract class Action {
10.
11. public Action() {
12.
13. }
14.
15. public String execute(HttpServletRequest request,
16. throws ServletException, IOException {
17. return null;
18. }
19. }
CharsetFilter.java文件:
处理中文乱码,默认为uft8
view plain
1. package com.westdream.filter.charset;
2.
3. import java.io.IOException;
4.
5. import javax.servlet.Filter;
6. import javax.servlet.FilterChain;
7. import javax.servlet.FilterConfig;
8. import javax.servlet.ServletException;
9. import javax.servlet.ServletRequest;
10. import javax.servlet.ServletResponse;
11.
12. public class CharsetFilter implements Filter {
13.
14. private static final long serialVersionUID = -3476217771259063866L;
15.
16. private String charset = "utf-8";
17.
18. public void doFilter(ServletRequest request, ServletResponse response,
19. throws IOException, ServletException {
20. request.setCharacterEncoding(charset);
21. request.setCharacterEncoding(charset);
22. chain.doFilter(request, response);
23. }
24.
25. public void init(FilterConfig config) throws ServletException {
26. if(config.getInitParameter("charset") != null) {
27. "charset");
28. }
29. }
30.
31. public void destroy() {
32.
33. }
34.
35. }
web.xml文件:
注意这里我使用的是.go不是.do,呵呵
view plain
1. <?xml version="1.0" encoding="UTF-8"?>
2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
5. <welcome-file-list>
6. <welcome-file>index.jsp</welcome-file>
7. </welcome-file-list>
8. <servlet>
9. <servlet-name>action</servlet-name>
10. <servlet-class>com.westdream.ActionServlet</servlet-class>
11. </servlet>
12. <servlet-mapping>
13. <servlet-name>action</servlet-name>
14. <url-pattern>*.go</url-pattern>
15. </servlet-mapping>
16.
17. <filter>
18. <filter-name>CharsetFilter</filter-name>
19. <filter-class>com.westdream.filter.charset.CharsetFilter</filter-class>
20. <init-param>
21. <param-name>charset</param-name>
22. <param-value>utf-8</param-value>
23. </init-param>
24. </filter>
25. <filter-mapping>
26. <filter-name>CharsetFilter</filter-name>
27. <url-pattern>/*</url-pattern>
28. </filter-mapping>
29. <login-config>
30. <auth-method>BASIC</auth-method>
31. </login-config>
32. </web-app>