实现一个Controller分发器工具类

一. 设计逻辑

我们设计一个分发器,对于不同的操作,进入不同的方法,但是他们的请求的是同一个servlet,只是参数不同

1. 删除操作:news?action=del
2. 查询:	news?action=list
3. 增加:	news?action=add
4. 修改:  	news?action=toUpdate

那么:对于参数 action对应的value的不同我们可以调用对应的方法

二. 简单设计:

进入这个servlet的请求,经过service,分发到对应的方法方法名与请求的value要相同
需要注意,请求必须是post,要不然数据会丢失

@WebServlet("/news")
public class NewsServlet extends BaseServlet {
	private NewsService service = new NewsService();
	public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("=========添加=======");
	}
	public void del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("=========删除=======");
	}
	/**
	 * 修改
	 */
	public void mod(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("=========提交修改=======");
	}
	/**
	 * 查询记录并转发到修改页面
	 */
	public void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("=========去修改=======");
	} 
	/**
	 * 查看详情
	 */
	public void detail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("=========明细=======");
	}
	/**
	 * 	新闻列表  带分页
	 * 	news?action=list
	 */
	public void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("=========明细=======");
	}
}

三. BaseServlet 的 service()的设计


public class BaseServlet extends HttpServlet{
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String methodName = request.getParameter("action");

		//反射 方法:方法名,参数列表  (确定唯一的方法)
		try {
			Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			//执行对应方法 调用
			method.invoke(this, request,response);
//			对象方法调用时
//			this.add(request,response);
		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值