一步一步写一个java web开发框架(4)

本文详细介绍了一步步构建自定义JavaWeb开发框架的过程,从获取自定义Action开始,到匹配用户请求并执行相应Action,最终通过ResponseWrapper输出结果。深入探讨了StrutsFilter的doFilter方法修改及ActionMapper的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一步一步写一个java web开发框架(1)

一步一步写一个java web开发框架(2)

一步一步写一个java web开发框架(3)

承接上文,所有自定义的Action都已经获取到了,那么下一步做什么呢?

找到与用户输入链接相匹配的Action,然后执行Action的method方法,就可以输出结果了。

修改StrutsFilter的doFilter方法

@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// 设置编码
		request.setCharacterEncoding(STR.ENCODING_UTF8);
		response.setCharacterEncoding(STR.ENCODING_UTF8);

		HttpServletRequest req = (HttpServletRequest) request;
		String path = req.getServletPath();
		ActionMapper action = this.context.getActionMapper(path);
		if (action != null) {
			logger.debug("Find the action " + path);
			action.execute(req, (HttpServletResponse) response);
		} else {
			logger.debug("Not found the action " + path);
			chain.doFilter(request, response);
		}
	}

StrutsContext里查找Action的函数

public ActionMapper getActionMapper(String path) {
		return actionList.get(path);
	}

这样找到ActionMapper然后执行execute函数,就会输出结果

public class ActionMapper {
	private static final Logger logger = Logger.getLogger(ActionMapper.class);

	private Method method;

	public ActionMapper(Method method) {
		this.method = method;
	}

	public void execute(HttpServletRequest request, HttpServletResponse response) {
		try {
			Object bean = this.method.getDeclaringClass().newInstance();
			Object result = this.method.invoke(bean);
			if (result != null) {
				ResponseWrapper wrapper = new ResponseWrapper(request, response);
				wrapper.doResponse(result);
			}
		} catch (Exception e) {
			logger.error("Execute action faild", e);
		}
	}

}

那么execute中的ResponseWrapper是干什么的呢,我们去下一节。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值