configure.xml文件:
该文件主要是框架的配置文件,包括Action,Form(本来准备把JDBC连接池和类Spring IOC的内容也添上的,不过没什么时间了)
有点类似struts-config.xml文件,我写这个的时候,考虑了一下Struts2.x,form-bean干脆改成了pojo了,只需要配置需要填充的属性,这样就比较轻了。然后pojo又可以做持久化对象使用,复用性也比较好。(后来我写了一个Leave Message的实例,可以看看)
配置文件就这么多了。
- <?xml version="1.0" encoding="utf-8"?>
- <view-config>
- <!本来是为Connection Pool用的,时间关系,没写连接池了。-->
- <jdbc-config>
- <driver-class-name>com.mysql.jdbc.Driver</driver-class-name>
- <url>jdbc:mysql://localhost:3306/westdream</url>
- <user>root</user>
- <password>123456</password>
- <max-active>20</max-active>
- <max-wait>3600</max-wait>
- </jdbc-config>
- <view>
- <forms>
- <form name="userInfo" class="com.westdream.pojo.Userinfo" >
- <property name="userName" type="java.lang.String" />
- <property name="userPwd" type="java.lang.String" />
- </form>
- <form name="message" class="com.westdream.pojo.Message" >
- <property name="title" type="java.lang.String" />
- <property name="content" type="java.lang.String" />
- </form>
- </forms>
- <action name="userInfo" path="/user" class="com.westdream.action.UserAction" >
- <result name="success" type="true" path="/success.jsp" />
- <result name="failure" type="true" path="/failure.jsp" />
- </action>
- <action name="message" path="/msg" class="com.westdream.action.MessageAction" >
- <result name="success" type="true" path="/listMsg.go" />
- <result name="failure" type="true" path="/failure.jsp" />
- </action>
- <action path="/listMsg" class="com.westdream.action.ListMessageAction" >
- <result name="list" type="true" path="/list.jsp" />
- </action>
- </view>
- </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忘记处理了,但加载了相应的配置)。这里不多说了
- package com.westdream;
- import java.io.IOException;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.util.List;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import com.westdream.action.Action;
- import com.westdream.config.ActionConfig;
- import com.westdream.config.Configuration;
- import com.westdream.config.FormConfig;
- import com.westdream.config.PropertyConfig;
- import com.westdream.config.ResultConfig;
- public class ActionServlet extends HttpServlet {
- private static final long serialVersionUID = 5852463410268904006L;
- /** 配置文件,默认为CLASSPATH **/
- public static final String CONFIG_FILE = "configure.xml";
- private Configuration config = null;
- public ActionServlet() {
- }
- protected void doGet(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- process(request, response);
- }
- protected void doPost(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- process(request, response);
- }
- @Override
- public void init() throws ServletException {
- initConfig();
- }
- protected void process(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- String requestURI = request.getRequestURI();
- ActionConfig actionConfig = config.getActionMappings().get(parseURI(requestURI));
- try {
- Action act = (Action)Class.forName(actionConfig.getClassName()).newInstance();
- Object data = null;
- if(actionConfig.getName() != null) {
- data = getFormObject(config.getFormMappings().get(actionConfig.getName()),request);
- }
- String result = act.execute(request, response, data);
- ResultConfig resultConfig = actionConfig.getResults().get(result);
- request.getRequestDispatcher(resultConfig.getPath()).forward(request, response);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (InstantiationException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- }
- }
- protected void initConfig() {
- config = Configuration.newInstance().configure(getServletContext());
- }
- @Override
- public void destroy() {
- }
- /** 解析URI **/
- protected String parseURI(String uri) {
- return uri.substring(0, uri.lastIndexOf("."));
- }
- /** 将form表单的数据封装成相应的Object **/
- protected Object getFormObject(FormConfig formConfig, HttpServletRequest request) {
- /** 如果配置相应的表单,则返回空 **/
- if(formConfig == null)
- return null;
- List<PropertyConfig> props = formConfig.getProperties();
- Object obj = null;
- try {
- obj = Class.forName(formConfig.getClassName()).newInstance();
- for(PropertyConfig prop : props) {
- StringBuilder methodName = new StringBuilder("set" + prop.getName());
- methodName.setCharAt(3, Character.toUpperCase(methodName.charAt(3)));
- Class<?> typeClass = Class.forName(prop.getType());
- Method method = obj.getClass().getMethod(methodName.toString(), typeClass);
- method.invoke(obj, new Object[]{request.getParameter(prop.getName())});
- }
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SecurityException e) {
- e.printStackTrace();
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- } catch (InstantiationException e) {
- e.printStackTrace();
- }
- return obj;
- }
- }
Configuration.java文件:
Configuration类主要是利用SAX解析configure.xml,然后加载到相应的配置类中,如ActionConfig,FormConfig等,这里用了JDOM
的包,看看源代码就知道了,很简单。
- package com.westdream.config;
- import java.io.IOException;
- import java.io.Serializable;
- import java.util.HashMap;
- import java.util.List;
- import javax.servlet.ServletContext;
- import org.jdom.Attribute;
- import org.jdom.Document;
- import org.jdom.Element;
- import org.jdom.JDOMException;
- import org.jdom.input.SAXBuilder;
- import org.jdom.xpath.XPath;
- public class Configuration implements Serializable, ConfigConstant {
- private static final long serialVersionUID = -8572272649468107517L;
- private static Configuration config = null;
- private HashMap<String, ActionConfig> actionMappings = new HashMap<String, ActionConfig>();
- private HashMap<String, FormConfig> formMappings = new HashMap<String, FormConfig>();
- private JDBCConfig jdbcConfig = null;
- public HashMap<String, FormConfig> getFormMappings() {
- return formMappings;
- }
- private Configuration() {
- }
- public static Configuration newInstance() {
- if (null == config) {
- config = new Configuration();
- }
- return config;
- }
- public Configuration configure(final ServletContext context) {
- return configure(DEFAULT_CONFIG_FILE, context);
- }
- @SuppressWarnings("unchecked")
- public Configuration configure(final String cfg , final ServletContext context)
- throws ConfigurationException {
- if (null == cfg | "".equals(cfg.trim()))
- throw new ConfigurationException("Configuration file is required.");
- /** 使用JDOM的SAX解析配置文件 **/
- SAXBuilder saxBuilder = new SAXBuilder();
- try {
- Document document = saxBuilder.build(Thread.currentThread()
- .getContextClassLoader().getResourceAsStream(cfg));
- Element root = document.getRootElement();
- List<Element> actionElmts = (List<Element>)XPath.selectNodes(root, VIEW_ACTION);
- for(Element actionElmt : actionElmts) {
- ActionConfig actionConfig = new ActionConfig();
- /** 将配置文件的Action属性装配到ActionConfig **/
- actionConfig.setPath(context.getContextPath() + actionElmt.getAttributeValue(ACTION_ATTRIB_PATH));
- actionConfig.setClassName(actionElmt.getAttributeValue(ACTION_ATTRIB_CLASS));
- actionConfig.setName(actionElmt.getAttributeValue(ACTION_ATTRIB_NAME));
- /** 将配置文件的Action的result子节点装配到ActionConfig **/
- List<Element> resultElmts = actionElmt.getChildren(ACTION_CHILDREN_RESULT);
- for(Element resultElmt : resultElmts) {
- ResultConfig resultConfig = new ResultConfig();
- Attribute nameAttrib = resultElmt.getAttribute(ACTION_CHILDREN_RESULT_NAME);
- Attribute pathAttrib = resultElmt.getAttribute(ACTION_CHILDREN_RESULT_PATH);
- Attribute typeAttrib = resultElmt.getAttribute(ACTION_CHILDREN_RESULT_TYPE);
- resultConfig.setName(nameAttrib.getValue());
- resultConfig.setForward(typeAttrib.getBooleanValue());
- resultConfig.setPath(pathAttrib.getValue());
- actionConfig.getResults().put(resultConfig.getName(), resultConfig);
- }
- /** 将ActionConfig装配到Configuration **/
- actionMappings.put(actionConfig.getPath(), actionConfig);
- }
- /** 将配置文件的form属性装配到FormConfig **/
- List<Element> formElmts = (List<Element>)XPath.selectNodes(root, VIEW_FORMS_FORM);
- for(Element formElmt : formElmts) {
- FormConfig formConfig = new FormConfig();
- formConfig.setName(formElmt.getAttributeValue(FORM_ATTRIB_NAME));
- formConfig.setClassName(formElmt.getAttributeValue(FORM_ATTRIB_CLASS));
- List<Element> propertyElmts = formElmt.getChildren(FORM_CHILDREN_PROP);
- for(Element propertyElmt : propertyElmts) {
- PropertyConfig propertyConfig = new PropertyConfig();
- propertyConfig.setName(propertyElmt.getAttributeValue(FORM_CHILDREN_PROP_NAME));
- propertyConfig.setType(propertyElmt.getAttributeValue(FORM_CHILDREN_PROP_TYPE));
- propertyConfig.setValue(propertyElmt.getAttributeValue(FORM_CHILDREN_PROP_VALUE));
- formConfig.getProperties().add(propertyConfig);
- }
- formMappings.put(formConfig.getName(), formConfig);
- }
- /** 配置JDBC **/
- Element driverClassNameElmt = (Element)XPath.selectSingleNode(root, JDBC_DRIVER_CLASS_NAME);
- Element urlElmt = (Element)XPath.selectSingleNode(root, JDBC_URL);
- Element userElmt = (Element)XPath.selectSingleNode(root, JDBC_USER);
- Element passwordElmt = (Element)XPath.selectSingleNode(root, JDBC_PASSWORD);
- Element maxActiveElmt = (Element)XPath.selectSingleNode(root, JDBC_MAX_ACTIVE);
- Element maxWaitElmt = (Element)XPath.selectSingleNode(root, JDBC_MAX_WAIT);
- jdbcConfig = new JDBCConfig();
- jdbcConfig.setDriverClassName(driverClassNameElmt.getText());
- jdbcConfig.setUrl(urlElmt.getText());
- jdbcConfig.setUser(userElmt.getText());
- jdbcConfig.setPassword(passwordElmt.getText());
- jdbcConfig.setMaxActive(Integer.valueOf(maxActiveElmt.getText()));
- jdbcConfig.setMaxWait(Integer.valueOf(maxWaitElmt.getText()));
- } catch (JDOMException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return config;
- }
- public HashMap<String, ActionConfig> getActionMappings() {
- return actionMappings;
- }
- public JDBCConfig getJdbcConfig() {
- return jdbcConfig;
- }
- }
Action.java文件:
Action为抽象类,所有的Action都必须继承该Action基类。
- package com.westdream.action;
- import java.io.IOException;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public abstract class Action {
- public Action() {
- }
- public String execute(HttpServletRequest request,
- HttpServletResponse response, Object data) throws ServletException, IOException {
- return null;
- }
- }
CharsetFilter.java文件:
处理中文乱码,默认为uft8
- package com.westdream.filter.charset;
- import java.io.IOException;
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- public class CharsetFilter implements Filter {
- private static final long serialVersionUID = -3476217771259063866L;
- private String charset = "utf-8";
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- request.setCharacterEncoding(charset);
- request.setCharacterEncoding(charset);
- chain.doFilter(request, response);
- }
- public void init(FilterConfig config) throws ServletException {
- if(config.getInitParameter("charset") != null) {
- charset = config.getInitParameter("charset");
- }
- }
- public void destroy() {
- }
- }
web.xml文件:
注意这里我使用的是.go不是.do,呵呵
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <servlet>
- <servlet-name>action</servlet-name>
- <servlet-class>com.westdream.ActionServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>action</servlet-name>
- <url-pattern>*.go</url-pattern>
- </servlet-mapping>
- <filter>
- <filter-name>CharsetFilter</filter-name>
- <filter-class>com.westdream.filter.charset.CharsetFilter</filter-class>
- <init-param>
- <param-name>charset</param-name>
- <param-value>utf-8</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>CharsetFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <login-config>
- <auth-method>BASIC</auth-method>
- </login-config>
- </web-app>