JavaWeb小小开发框架(只有3个类)

本套代码实现功能如下:
1.请求路由功能
2.Bean注入
3.执行匿名及命名参数sql语句

[文件] WebServlet.java
package com.hongyuan.core;
 
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
 
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@SuppressWarnings("serial")
public class WebServlet extends HttpServlet {
 
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected Map<String,String> cfgParams=new HashMap<String,String>();
    protected Map<String,String> dbSqls=new HashMap<String,String>();
    protected Map<String,String> msgs=new HashMap<String,String>();
    public void init(){}
     
    @Override
    public final void init(ServletConfig config) throws ServletException {
        @SuppressWarnings("unchecked")
        Enumeration<String> names = config.getInitParameterNames();
        while(names.hasMoreElements()){
            String name=names.nextElement();
            if(name.startsWith("Bean_")){
                //为servlet注入Bean对象
                String beanName=name.substring("Bean_".length());
                String beanClass=config.getInitParameter(name);
                try {
                    Object bean = Class.forName(beanClass).newInstance();
                    bean.getClass().getMethod("setServlet",new Class[]{WebServlet.class}).invoke(bean,this);
                    this.getClass().getField(beanName).set(this,bean);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if(name.startsWith("Sql_")){
                String sqlName=name.substring("Sql_".length());
                String sql=config.getInitParameter(name);
                dbSqls.put(sqlName,sql);
            }else if(name.startsWith("Message_")){
                String msgName=name.substring("Message_".length());
                String msg=config.getInitParameter(name);
                msgs.put(msgName,msg);
            }else if(name.startsWith("Param_")){
                String paramName=name.substring("Param_".length());
                String paramVal=config.getInitParameter(name);
                cfgParams.put(paramName,paramVal);
            }
        }
    }
     
    @Override
    public final void service(HttpServletRequest request, HttpServletResponse response){
         
        this.request=request;
        this.response=response;
                 
        try {
            //根据路由参数将请求转交到指定方法执行
            String routeParam=cfgParams.get("routeParam");
            String action=this.get((routeParam==null||"".equals(routeParam))?"action":routeParam,"init");
            Method method=this.getClass().getMethod(action);
            method.invoke(this);
        } catch (Exception e) {
            this.init();
        }
             
    }
     
    /**
     * 展示指定页面
     * @param page
     */
    protected void show(String page){
        try {
            String pagePath=cfgParams.get("pagePath");
            request.getRequestDispatcher(((pagePath==null||"".equals(pagePath))?"/WEB-INF/pages/":pagePath)+page).forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
     
    /**
     * 获取指定名称的请求参数
     * @param name
     * @param def
     * @return
     */
    protected String get(String name,String def){
        String value=request.getParameter(name);
        if(value!=null&&!"".equals(value.trim())){
            return value;
        }else{
            return def;
        }
    }
     
    /**
     * 向页面输出指定参数
     * @param name
     * @param value
     */
    protected void put(String name,Object value){
        request.setAttribute(name,value);
    }
     
    /**
     * 获取指定名称的消息内容(可设置默认值)
     * @param name
     * @param def
     * @return
     */
    protected String getMsg(String name,String def){
        String msg=msgs.get(name);
        if(msg!=null&&!"".equals(msg.trim())){
            return msg;
        }else{
            return def;
        }
    }
     
    /**
     * 获取指定名称的消息内容
     * @param name
     * @param def
     * @return
     */
    protected String getMsg(String name){
        return this.getMsg(name,"");
    }
}
[文件] WebBean.java
package com.hongyuan.core;
 
public class WebBean {
 
    protected DBUtil dbUtil=new DBUtil();
    private WebServlet servlet;
 
    public WebServlet getServlet() {
        return servlet;
    }
 
    public void setServlet(WebServlet servlet) {
        this.servlet = servlet;
    }
     
    public String getSql(String sqlName){
        return servlet.dbSqls.get(sqlName);
    }
}
[文件] DBUtil.java
package com.hongyuan.core;
  
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import javax.sql.DataSource;
 
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
  
public class DBUtil {
     
    private static DataSource dataSource = null;
    static{
        /**
         * 初始化数据源,不同的数据库获取数据源的方式不同,可参考相应数据库的说明文档。
         */
        MysqlDataSource mds=new MysqlDataSource();
        mds.setURL("jdbc:mysql://localhost:3306/test");
        mds.setUser("root");
        mds.setPassword("123456");
        dataSource=mds;
    }
     
    /**
     * 获取数据库连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
  
    /**
     * 关闭数据库连接资源
     * @param conn  
     * @param s
     * @param rs
     * @throws SQLException
     */
    public static void close(Connection conn, Statement s, ResultSet rs) throws SQLException {
        if (rs != null) rs.close();
        if (s != null) s.close();
        if (conn != null) conn.close();
    }
     
    /**
     * 执行数据库查询语句
     * @param sql       查询sql,匿名参数用?表示,命名参数使用“:参数名”表示
     * @param params    查询参数
     * @return
     * @throws SQLException
     */
    @SuppressWarnings("unchecked")
    public List<Map<String,Object>> select(String sql,Object... params) throws SQLException{
        return (List<Map<String,Object>>)this.executeSql(sql,params);
    }
     
    /**
     * 执行数据库记录变更语句(增,删,改)
     * @param sql       查询sql,匿名参数用?表示,命名参数使用“:参数名”表示
     * @param params    查询参数
     * @return
     * @throws SQLException
     */
    public int update(String sql,Object... params) throws SQLException{
        return (Integer)this.executeSql(sql,params);
    }
     
    /**
     * 通用Sql执行方法
     * @param sql       查询sql,匿名参数用?表示,命名参数使用“:参数名”表示
     * @param params    命名参数
     * @return
     * @throws SQLException
     */
    public Object executeSql(String sql, Object... params) throws SQLException {
 
        //处理命名参数
        if(params!=null&&params[0] instanceof Map){
            List<Object> pList=new ArrayList<Object>();
            Map<String,Object> pMap=(Map<String, Object>)params[0];
            Matcher pMatcher = Pattern.compile(":(\\w+)").matcher(sql);
            while(pMatcher.find()){
                String pName=pMatcher.group(1);
                pList.add(pMap.get(pName));
            }
             
            sql=pMatcher.replaceAll("?");
            params=pList.toArray();
        }
         
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = DBUtil.getConnection();
            ps = conn.prepareStatement(sql);
              
            if (null != params) {
                //初始化查询参数
                for(int i=0;i<params.length;i++){
                    Object param = params[i];
                    if(param!=null){
                        ps.setObject(i+1,param);
                    }else{
                        ps.setNull(i+1,Types.NULL);
                    }
                     
                }
            }
             
            //处理结果集
            boolean isResultSet = ps.execute();
            List<Object> result = new ArrayList<Object>();
            do {
                if (isResultSet) {
                    List<Map<String,Object>> tableData=new ArrayList<Map<String,Object>>();
                    ResultSet resultSet=ps.getResultSet();
                    while(resultSet.next()){
                        Map<String,Object> rowData=new HashMap<String,Object>();
                        for(int i=1;i<=resultSet.getMetaData().getColumnCount();i++){
                            rowData.put(resultSet.getMetaData().getColumnName(i),resultSet.getObject(i));
                        }
                        tableData.add(rowData);
                    }
                    result.add(tableData);
                } else {
                    result.add(new Integer(ps.getUpdateCount()));
                }
            } while ((isResultSet = ps.getMoreResults()) == true || ps.getUpdateCount() != -1);
  
            //处理返回结果
            if (result.size() == 0) {
                return null;
            } else if (result.size() == 1) {
                return result.get(0);
            } else {
                return result;
            }
        } catch (SQLException e) {
            throw new SQLException("无法执行的sql语句!");
        } finally {
            DBUtil.close(conn, ps, rs);
        }
    }
}
[文件] web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app [
    <!ENTITY webServlet SYSTEM "web-servlets.part">
    <!ENTITY webServletMapping SYSTEM "web-servlet-mapping.part">
]>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
   
  &webServlet;
  &webServletMapping;
   
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
[文件] web-servlets.part
<servlet>
	<servlet-name>SimpleServlet</servlet-name>
	<servlet-class>com.hongyuan.test.SimpleServlet</servlet-class>
	<!-- 为servlet注入Bean实例 -->
	<init-param>
		<param-name>Bean_simpleBean</param-name>
		<param-value>com.hongyuan.test.SimpleBean</param-value>
	</init-param>
	<!-- sql语句,匿名参数 -->
	<init-param>
		<param-name>Sql_queryUserById</param-name>
		<param-value>select * from user where id=?</param-value>
	</init-param>
	<!-- sql语句,命名参数 -->
	<init-param>
		<param-name>Sql_queryUserByUserId</param-name>
		<param-value>select * from user where user_id=:userId</param-value>
	</init-param>
	<init-param>
		<param-name>Message_hello</param-name>
		<param-value>Hello Servlet!!!!</param-value>
	</init-param>
	<init-param>
		<param-name>Param_config</param-name>
		<param-value>this is a config param.</param-value>
	</init-param>
</servlet>