自定义mvc增删查改代码

DBAccess

package com.util;

import java.io.InputStream;
import java.security.KeyStore.ProtectionParameter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 提供了一组获得或关闭数据库对象的方法
 * 
 */
public class DBAccess {
	private static String driver;
	private static String url;
	private static String user;
	private static String password;

	static {// 静态块执行一次,加载 驱动一次
		try {
			InputStream is = DBAccess.class
					.getResourceAsStream("config.properties");

			Properties properties = new Properties();
			properties.load(is);

			driver = properties.getProperty("driver");
			url = properties.getProperty("url");
			user = properties.getProperty("user");
			password = properties.getProperty("pwd");

			Class.forName(driver);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	/**
	 * 获得数据连接对象
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		try {
			Connection conn = DriverManager.getConnection(url, user, password);
			return conn;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public static void close(ResultSet rs) {
		if (null != rs) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public static void close(PreparedStatement ps) {
		if (null != ps) {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public static void close(Connection conn) {
		if (null != conn) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public static void close(Connection con, PreparedStatement ps, ResultSet rs) {
		close(rs);
		close(ps);
		close(con);
	}

	public static boolean isOracle() {
		return "oracle.jdbc.driver.OracleDriver".equals(driver);
	}

	public static boolean isSQLServer() {
		return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver);
	}
	
	public static boolean isMysql() {
		return "com.mysql.cj.jdbc.Driver".equals(driver);
	}

	public static void main(String[] args) {
		Connection conn = DBAccess.getConnection();
		DBAccess.close(conn);
		System.out.println("isOracle:" + isOracle());
		System.out.println("isSQLServer:" + isSQLServer());
		System.out.println("isMysql:" + isMysql());
		System.out.println("数据库连接(关闭)成功");
	}
}


实体类

package com.entity;

public class Student {
	private int sid;
	private String sname;
	private String shobby;
	private int tid;
	private int cid;
	
	public int getTid() {
		return tid;
	}
	public void setTid(int tid) {
		this.tid = tid;
	}
	public int getCid() {
		return cid;
	}
	public void setCid(int cid) {
		this.cid = cid;
	}
	public void setSid(int sid) {
		this.sid = sid;
	}
	public int getSid() {
		return sid;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	public String getShobby() {
		return shobby;
	}
	public void setShobby(String shobby) {
		this.shobby = shobby;
	}
	public Student() {
		super();
	}
	public Student(int sid, String sname, String shobby, int tid, int cid) {
		super();
		this.sid = sid;
		this.sname = sname;
		this.shobby = shobby;
		this.tid = tid;
		this.cid = cid;
	}
	@Override
	public String toString() {
		return "Student [sid=" + sid + ", sname=" + sname + ", shobby=" + shobby + ", t=" + tid + ", c=" + cid + "]";
	}
	
}


package com.entity;

public class Teacher {
	
	private int tid;
	private String tname;
	public int getTid() {
		return tid;
	}
	public void setTid(int tid) {
		this.tid = tid;
	}
	public String getTname() {
		return tname;
	}
	public void setTname(String tname) {
		this.tname = tname;
	}
	
	public Teacher() {}
	public Teacher(int tid, String tname) {
		super();
		this.tid = tid;
		this.tname = tname;
	}
}


package com.entity;

public class Clas {
	
	private int cid;
	private String cname;
	public int getCid() {
		return cid;
	}
	public void setCid(int cid) {
		this.cid = cid;
	}
	public String getCname() {
		return cname;
	}
	public void setCname(String cname) {
		this.cname = cname;
	}
	public Clas() {}
	public Clas(int cid, String cname) {
		super();
		this.cid = cid;
		this.cname = cname;
	}
}


BaseDao

package com.ly.pagination.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.util.DBAccess;
import com.util.PageBean;


public class BaseDao<T> {
	
	public static interface CallBack<E>{
		//遍历ResultSet结果集
		public List<E> forEach(ResultSet rs) throws SQLException, Exception;
	}

	/**
	 * 分页查询
	 * @param sql 普通的sql
	 * @param pageBean 
	 * @return
	 */
	public List<T> executeQuery(String sql,PageBean pageBean,CallBack<T> callBack){
		Connection conn=null;
		PreparedStatement stmt=null;
		ResultSet rs=null;
		try {
			conn=DBAccess.getConnection();
			//判断是否分页
			if(null!=pageBean&&pageBean.isPagination()) {
				//第一次查询总记录数
				String countSql=this.getCountSql(sql);
				stmt=conn.prepareStatement(countSql);
				rs=stmt.executeQuery();
				if(rs.next()) {
					Object obj = rs.getObject(1);
					pageBean.setTotal(Integer.parseInt(obj.toString()));
				}
				//DBHelper.close(conn, stmt, rs);
				//第二次满足条件的分页数据集
				sql=this.getPagerSql(sql, pageBean);
			}
			stmt=conn.prepareStatement(sql);
			rs=stmt.executeQuery();
			//处理结果集
			return callBack.forEach(rs);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBAccess.close(conn, stmt, rs);
		}
		return null;
	}
	
	/**
	 * 将普通的Sql语句转换成查总记录数的Sql语句
	 * 例如:sql=="select * from t_book where bookname='123'"
	 * @param sql
	 * @return
	 */
	private String getCountSql(String sql) {
		return "select count(1) from ("+sql+") t1";
	}
	
	/**
	 * 将普通Sql语句转换成查询分页的Sql语句
	 * 例如:sql=="select * from t_book where bookname='123'"
	 * @param sql
	 * @param pageBean
	 * @return
	 */
	private String getPagerSql(String sql,PageBean pageBean) {
		return sql+" Limit "+pageBean.getStartIndex()+","+
					pageBean.getRows();
	}
}

dao层

package com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.entity.Clas;
import com.entity.Student;
import com.entity.Teacher;
import com.util.CommonUtils;
import com.util.DBAccess;
import com.util.PageBean;
import com.util.StringUtils;
import com.zking.pagination.dao.BaseDao;

public class StuDao extends BaseDao<Student> implements IStuDao  {
	
	Connection con=null;
	PreparedStatement ps=null;
	ResultSet rs=null;
	
	
	/**
	 * 分页查询
	 * @param pageIndex
	 * @param pageSize
	 * @param str
	 * @param colName
	 * @return
	 */
	public List<Student> getAll(int pageIndex,int pageSize,String str){
		List<Student> ls=new ArrayList<>();
		try {
			con=DBAccess.getConnection();
			ps=con.prepareStatement("select * from tb_stu "+str+" limit "+(pageIndex-1)*pageSize+","+pageSize+"");
		 	ResultSet rs=ps.executeQuery();
			while(rs.next()) {
				Student stu=new Student();
				stu.setSid(rs.getInt(1));
				stu.setSname(rs.getString(2));
				stu.setShobby(rs.getString(3));
				stu.setTid(rs.getInt(4));
				stu.setCid(rs.getInt(5));
				ls.add(stu);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBAccess.close(con, ps, rs);
		}
		return ls;
	}
	public List<Student> List(Student stu,PageBean pageBean) throws InstantiationException, IllegalAccessException, IllegalArgumentException, SQLException {
		String sql="select * from tb_stu where 1=1 ";		
		if(StringUtils.isBlank(stu.getSname())) {
			sql+=" and sname like '%"+stu.getSname()+"%'";
		}
			return super.executeQuery(sql, pageBean,new CallBack<Student>() {

				@Override
				public java.util.List<Student> forEach(ResultSet rs) throws Exception {
						return CommonUtils.toList(rs,Student.class);
				}
			});
	}
	
	
	/**
	 * 查出所有教员
	 * @return
	 */
	public List<Teacher> getTid(){
		List<Teacher> ls=new ArrayList<>();
		try {
			con=DBAccess.getConnection();
			ps=con.prepareStatement("select * from tb_teacher");
			rs=ps.executeQuery();
			while(rs.next()) {
				Teacher t=new Teacher();
				t.setTid(rs.getInt(1));
				t.setTname(rs.getString(2));
				ls.add(t);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBAccess.close(con, ps, rs);
		}
		return ls;
	}
	
	
	/**
	 * 查出所有班级
	 * @return
	 */
	public List<Clas> getCid(){
		List<Clas> ls=new ArrayList<>();
		try {
			con=DBAccess.getConnection();
			ps=con.prepareStatement("select * from tb_class");
			rs=ps.executeQuery();
			while(rs.next()) {
				Clas c=new Clas();
				c.setCid(rs.getInt(1));
				c.setCname(rs.getString(2));
				ls.add(c);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBAccess.close(con, ps, rs);
		}
		return ls;
	}


	@Override
	public int add(Student stu) {
		int n=0;
		try {
			con=DBAccess.getConnection();
			ps=con.prepareStatement("insert into tb_stu values(?,?,?,?,?)");
			ps.setInt(1, stu.getSid());
			ps.setString(2, stu.getSname());
			ps.setString(3, stu.getShobby());
			ps.setInt(4, stu.getTid());
			ps.setInt(5, stu.getCid());
			n=ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBAccess.close(con, ps, rs);
		}
		return n;
	}


	@Override
	public int update(Student stu, int sid) {
		int n=0;
		try {
			con=DBAccess.getConnection();
			ps=con.prepareStatement("update tb_stu set sid=?,sname=?,shobby=?,tid=?,cid=? where sid=?");
			ps.setInt(1, stu.getSid());
			ps.setString(2, stu.getSname());
			ps.setString(3, stu.getShobby());
			ps.setInt(4, stu.getTid());
			ps.setInt(5, stu.getCid());
			ps.setInt(6, sid);
			n=ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBAccess.close(con, ps, rs);
		}
		return n;
	}

	@Override
	public int del(int sid) {
		int n=0;
		try {
			con=DBAccess.getConnection();
			ps=con.prepareStatement("delete from tb_stu where sid="+sid);
			n=ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBAccess.close(con, ps, rs);
		}
		return n;
	}


	@Override
	public Student getBySid(int sid) {
		String sql="select * from tb_stu where sid=?";
		List<Student> list = super.executeQuery(sql, null, new CallBack<Student>() {

			@Override
			public java.util.List<Student> forEach(ResultSet rs) throws SQLException, Exception {
				return CommonUtils.toList(rs, Student.class);
			}
		});
		if(null!=list||0!=list.size()) {
			return list.get(0);
		}
		else {
			return null;
		}
	}


	@Override
	public int getSid() {
		// TODO Auto-generated method stub
		return 0;
	}
	
	/**
	 * 获取最大行数
	 * @param str
	 * @return
	 */
	public int getRows(String str){
		int n = 0;
		try {
			con=DBAccess.getConnection();
			ps=con.prepareStatement("select count(*) from tb_stu "+str+"");
			rs = ps.executeQuery();
			if(rs.next()){
				n = rs.getInt(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			DBAccess.close(con, ps, rs);
		}
		return n;
	}
	
	
	public Clas getC(int cid) {
		Clas c=new Clas();
		try {
			con=DBAccess.getConnection();
			ps=con.prepareStatement("select * from tb_class where cid="+cid);
			rs=ps.executeQuery();
			if(rs.next()) {
				c.setCid(rs.getInt(1));
				c.setCname(rs.getString(2));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBAccess.close(con, ps, rs);
		}
		return c;
	}
	
	
	public Teacher getT(int tid) {
		Teacher t=new Teacher();
		try {
			con=DBAccess.getConnection();
			ps=con.prepareStatement("select * from tb_teacher where tid="+tid);
			rs=ps.executeQuery();
			if(rs.next()) {
				t.setTid(rs.getInt(1));
				t.setTname(rs.getString(2));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBAccess.close(con, ps, rs);
		}
		return t;
	}
	
	public List<Student> getAllName(){
		List<Student> ls=new ArrayList<>();
		try {
			con=DBAccess.getConnection();
			ps=con.prepareStatement("select sname from tb_stu");
		 	ResultSet rs=ps.executeQuery();
			while(rs.next()) {
				Student stu=new Student();
				stu.setSname(rs.getString(1));
				ls.add(stu);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBAccess.close(con, ps, rs);
		}
		return ls;
	}
}


PageBean

package com.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 分页工具类
 *
 */
public class PageBean {

	private int page = 1;// 页码

	private int rows = 10;// 页大小

	private int total = 0;// 总记录数

	private boolean pagination = true;// 是否分页

	private String url;
	private Map<String, String[]> paramMap = new HashMap<>();

//	定义初始化方法,存入上一次请求的值
	public void setRequest(HttpServletRequest req) {
		this.setPage(req.getParameter("page"));
		this.setRows(req.getParameter("rows"));
		this.setPagination(req.getParameter("pagination"));
		// getRequestURL获取到浏览器请求的全路径
		this.setUrl(req.getRequestURL().toString());
		// getParameterMap可以获取到一次url请求所携带的所有参数
		this.setParamMap(req.getParameterMap());

	}

	public void setPagination(String pagination) {
		if (StringUtils.isNotBlank(pagination)) {
			this.setPagination(!"false".equals(pagination));
		}
	}

	public void setRows(String rows) {
		if (StringUtils.isNotBlank(rows))
			this.setRows(Integer.valueOf(rows));

	}

	public void setPage(String page) {
		if (StringUtils.isNotBlank(page)) {
			this.setPage(Integer.valueOf(page));
		}
	}

	public PageBean() {
		super();
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Map<String, String[]> getParamMap() {
		return paramMap;
	}

	public void setParamMap(Map<String, String[]> paramMap) {
		this.paramMap = paramMap;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public void setTotal(String total) {
		this.total = Integer.parseInt(total);
	}

	public boolean isPagination() {
		return pagination;
	}

	public void setPagination(boolean pagination) {
		this.pagination = pagination;
	}

	/**
	 * 获得起始记录的下标
	 * 
	 * @return
	 */
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
	}

	/**
	 * 获取到总页数
	 * @return
	 */
	public int getMaxPage() {
		return this.total % this.rows == 0 ? 
				this.total / this.rows : 
					(this.total / this.rows) + 1;
	}
	
	/**
	 * 获取下一页页码
	 * @return
	 */
	public int getNextPage() {
		return this.page < this.getMaxPage() ? this.page+1 : this.page;
	}
	
	/**
	 * 获取上一页页码
	 * @return
	 */
	public int getPreviousPage() {
		return this.page > 1 ? this.page-1 : this.page;
	}

}


配置

#oracle9i
#driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@localhost:1521:ora9
#user=test
#pwd=test


#sql2005
#driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
#url=jdbc:sqlserver://localhost:1423;DatabaseName=test
#user=sa
#pwd=sa


#sql2000
#driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
#url=jdbc:microsoft:sqlserver://localhost:1433;databaseName=unit6DB
#user=sa
#pwd=888888


#mysql5
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost/db_0524?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
user=mysql
pwd=123

控制器

package com.framework;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 子控制器
 * 		专门用来处理业务逻辑
 * @author 86135
 *
 */
public interface Action {
	
	String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ;

}


package com.framework;

import java.util.HashMap;
import java.util.Map;

public class ActionModel {
	
	private String path;
	private String type;
	private Map<String, ForwardModel> fMap=new HashMap<>();
	
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	
	public void push(ForwardModel forwardmodel) {
		fMap.put(forwardmodel.getName(),forwardmodel);
	}
	
	public ForwardModel pop(String name) {
		return fMap.get(name);
	}
}


package com.framework;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 之前的Action只能处理一个实体类的业务
 * 
 *  现在这个是增加版的子控制器
 *  凡是这个实体类的操作,对应方法都可以写在当前增强版的子控制器来完成
 * @author 86135
 *
 */
public class ActionSupport implements Action {

	@Override
	public final String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String methodName = req.getParameter("methodName");
		String code=null;
		try {
			//获取到类对象,再获取方法
			Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			method.setAccessible(true);
			//具体调用了你自己所写的子控制器的方法来处理浏览器请求
			code=(String)method.invoke(this, req,resp);
		} catch (NoSuchMethodException | SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return code;
	}
}

ConfigModel

package com.framework;

import java.util.HashMap;
import java.util.Map;

public class ConfigModel {
	private Map<String, ActionModel> acmap=new HashMap<>();
	
	public void push(ActionModel actionmodel) {
		acmap.put(actionmodel.getPath(), actionmodel);
	}	
	public ActionModel pop(String path) {
		return acmap.get(path);
	}
}

ConfigModelFatory

package com.framework;

import java.io.InputStream;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;import com.sun.corba.se.spi.orbutil.fsm.Action;

public class ConfigModelFatory {
	
	public static ConfigModel build() throws Exception {
		return build("config.xml");
	}

	public static ConfigModel build(String string) throws Exception {
		ConfigModel configmodel=new ConfigModel();
		InputStream in = ConfigModelFatory.class.getResourceAsStream("config.xml");
		SAXReader reader=new SAXReader();
		Document doc = reader.read(in);
		ActionModel actionmodel=null;
		ForwardModel forwardmodel=null;
		List<Element> actionEles = doc.selectNodes("/config/action");
		for (Element actionEle : actionEles) {
			actionmodel=new ActionModel();
			//接下来需要往actionModel中填充内容
			actionmodel.setPath(actionEle.attributeValue("path"));
			actionmodel.setType(actionEle.attributeValue("type"));
			//拿到foward
			List<Element> forword = actionEle.selectNodes("forward");
			for (Element forwardEle : forword) {
				forwardmodel=new ForwardModel();
				//往forwardModel中填充内容
				forwardmodel.setName(forwardEle.attributeValue("name"));
				forwardmodel.setPath(forwardEle.attributeValue("path"));
				forwardmodel.setRedirect(!"false".equals(forwardEle.attributeValue("redirect")));
				actionmodel.push(forwardmodel);
			}
			configmodel.push(actionmodel);//调用存值方法
		}
		
		return configmodel;
	}
}

package com.framework;

public class ForwardModel {

private String name;
private String path;
private boolean redirect;
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public String getPath() {
	return path;
}
public void setPath(String path) {
	this.path = path;
}
public boolean isRedirect() {
	return redirect;
}
public void setRedirect(boolean redirect) {
	this.redirect = redirect;
}

}

package com.framework;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;

import org.apache.commons.beanutils.BeanUtils;


/**
 * 主控制器
 * @author 86135
 *
 */
public class DispatcherServlet extends HttpServlet {

	private static final long serialVersionUID = -7094025920085803724L;
	
	private ConfigModel configModel = null;
	
	
	//初始化方法
	public void init() {
		
		try {
			//将原来的读取框架的默认配置文件转变成读取可配置路径的配置文件
			String xmlPath = this.getInitParameter("xmlPath");
			if(xmlPath == null || "".equals(xmlPath)) {
				configModel = ConfigModelFatory.build();
			}
			else {
				configModel = ConfigModelFatory.build(xmlPath);
				}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		init();//初始化
		String url = req.getRequestURI();//Mvc/xxx.action
		url = url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
		
		//根据路径获取action的模型
		ActionModel actionModel = configModel.pop(url);
		if(actionModel==null) {
			throw new RuntimeException("你没有配置对应的子控制器Action!!!");
		}
		try {
			//原来子控制器的来源是map集合,这样的话子控制器被写死再map容器中,代码不够灵活
			//现在将子控制器配置方式存放再config.xml中,未来可以通过改变config.xml中的内容
			//随意给中央控制器添加子控制器
			Action action = (Action)Class.forName(actionModel.getType()).newInstance();
			
//			调用模型驱动接口,获取所需要操作的实体类,然后将jsp传递过来的参数,封装到实体类中
			if(action instanceof ModelDriver) {
				ModelDriver modelDriver=(ModelDriver)action;
				Object model = modelDriver.getModel();
				//封装属性
				BeanUtils.populate(model, req.getParameterMap());
			}
			
//			每个子控制器,都需要对结果进行对应的处理,要么重定向,要么转发,代码重复量较大
//			针对于这一现象,将其交给配置文件来处理
//			调用了增强版的子控制器来处理业务逻辑
			String code = action.execute(req, resp);
			ForwardModel forwardModel = actionModel.pop(code);
			if(forwardModel ==null) {
				throw new RuntimeException("你没有配置对应的子控制器Action的处理方式Forward!!!");
			}
			String jspPath = forwardModel.getPath();
			if(forwardModel.isRedirect()) {
				resp.sendRedirect(req.getContextPath()+jspPath);//拼接上路径,相当于绝对路径
			}
			else {
				req.getRequestDispatcher(jspPath).forward(req, resp);
			}
		} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
}


tld


<taglib 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-jsptaglibrary_2_0.xsd"
    version="2.0">
    
  <description>xuyang 1.1 core library</description>
  <display-name>xuyang core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>z</short-name>
  <uri>/xuyang</uri><!-- 这是你引入标签库的语句 -->

 <tag>
    <name>checkbox</name>
    <tag-class>com.tag.CheckboxTag</tag-class>
    <body-content>JSP</body-content>
    
     <attribute>
        <name>textKey</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
     </attribute>
     <attribute>
        <name>textVal</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
     </attribute>
      <attribute>
        <name>item</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
     </attribute>
     <attribute>
        <name>checkedVal</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
     </attribute>
  </tag>
  
   <tag>
    <name>select</name>
    <tag-class>com.tag.SelectTag</tag-class>
    <body-content>JSP</body-content>
    
    <attribute>
        <name>id</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
     <attribute>
        <name>name</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
     </attribute>
     <attribute>
        <name>items</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
     </attribute>
     <attribute>
        <name>textKey</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
     </attribute>
     <attribute>
        <name>textVal</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
     </attribute>
     <attribute>
        <name>selectedVal</name>
        <required>false</required>
        <rtexprvalue>true</rtexprvalue>
     </attribute>
     <attribute>
        <name>headerTextKey</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
     </attribute>
     <attribute>
        <name>headerTextVal</name>
        <required>false</required>
        <rtexprvalue>false</rtexprvalue>
     </attribute>
  </tag>
</taglib>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值