欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

自定义mvc

程序员文章站 2022-07-08 10:27:18
...

MVC是一种软件设计典范,用于业务逻辑处理、数据、界面显示分离
MVC全名:Model View Controller,其中Model(模型层)、View(视图层)、Controller(控制层)

目录:
1、准备工作
2、案例
3、总结
一、准备工作
1、导入jar包
自定义mvc
2、创建包
自定义mvc
二、案例(整数相加)
1、创建抽象类Action,定义抽象方法execute

public abstract class Action {
	protected abstract String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ;
		
}

2、创建HelloAction并继承抽象类Action,重写execute方法

public class HelloAction extends Action{

	@Override
	protected String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("123");
		return null;
	}

}

3、在ActionServlet中定义私有Map<String,Action>(根据不同请求路径名调用不同逻辑处理Action类)

public class ActionServlet extends HttpServlet{
	private Map<String, Action> map;
	
	

	
	
}

4、在ActionServlet中的init方法初始化Map集合
map.put(‘请求路径’,‘逻辑处理Action类’)


@Override
	public void init() throws ServletException {
		map=new HashMap<String, Action>();
	}

5、在ActionServlet中的doPost方法中处理请求

@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//获取请求路径
		String requestURI = req.getRequestURI();
		
		int start = requestURI.lastIndexOf("/");
		int end = requestURI.lastIndexOf(".action");
		
		//截取请求路径
		String actionName = requestURI.substring(start, end);
		
		//通过截取路径中的action找到对应的自控制器
		Action action = map.get(actionName);
		
		//执行execute方法
		action.execute(req, resp);
		
	}

6、在ActionServlet中的init方法中添加
map.put(’/AddAction’,new AddAction());

@Override
	public void init() throws ServletException {
		map=new HashMap<String, Action>();
		map.put("/HelloAction", new HelloAction());
		map.put("/AddAction", new AddAction());
	}

7、创建AddAction继承抽象类Action,重写execute方式,处理逻辑后,返回结果

public class AddAction extends Action{

	@Override
	protected String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String num1 = req.getParameter("num1");
		String num2 = req.getParameter("num2");
		int num3 = Integer.parseInt(num1) + Integer.parseInt(num2);
		req.setAttribute("num3", num3);
		req.getRequestDispatcher("result.jsp").forward(req, resp);
		return null;
	}
}

8、编写jsp界面
add.jsp界面

<form action="AddAction.action" method="post">
		num1:<input name="num1"><br/>
		num2:<input name="num2"><br/>
		<input type="submit" value="确定">
	</form>

result.jsp界面

<h2>${num3 }</h2>

结果:
自定义mvc
自定义mvc