Custom mvc framework (medium)

 

                                       1. Review of the previous section

In the previous section, we learned about:

1. What is the MVC framework?

2. Extensive use of mvc framework in enterprises

3. What is the difference between the MVC framework and the three-tier architecture?

4. Analyze the mvc framework code and defects

5. Use the custom mvc framework to optimize the three-tier architecture!

So have you learned it?

                                   2. Continue to optimize the mvc framework

1.. Make the Action container in the central controller controllable!

Disadvantages : The loading of the central controller cannot be flexibly configured

1.1 Old version method

First of all, our first problem is the initial configuration of the sub-controller . I demonstrated in the last version "Reflection Enhanced Version" in the previous article that if you need to operate other tables in the project, you must write controller . Through this operation, the container in the action can be easily activated, which can be adapted to various uses

1.2 new version method

In the new version , we use the method of XML modeling to realize the original written dead and make it alive!

Then the build method (through which our xml file is called) is shown as

xml file 

 Modify at the typr location , the path is the way you implement the servelt

Some documents corresponding to 1.3

1.3.1 Central controller

package com.lz.fraamework;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.lz.fraamework.model.ActionModel;
import com.lz.fraamework.model.ConfigModel;
import com.lz.fraamework.model.ConfigModelFactory;
import com.lz.fraamework.model.ForwardModel;
import com.lz.servelt.OederAction;
import com.lz.servelt.bookAction;

/**
 * 对应图中的 ActionServelt:中央控制器 调用反射代码块
 * 
 * @author lzzxq
 *
 */
@WebServlet("*.action")
public class DispathServelt extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ConfigModel configModel;
	@Override
	// 服务器启动就启用
	public void init() throws ServletException {
		try {
			configModel = ConfigModelFactory.build();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		@SuppressWarnings("unused")
		// jsp传递的参数
		String methodName = request.getParameter("methodName");
		// 获取浏览器路径的book
		String uri = request.getRequestURI();
		uri = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));
		// Action action = actionMap.get(uri);

		// 通过 uri= 在configModel寻找
		ActionModel actionmodel = configModel.pop(uri);
		if (actionmodel == null) {
			throw new RuntimeException("action not config");
		}
		String type = actionmodel.getType();
		// bookAction bk=new bookAction();
		Action action;
		try {
			action = (Action) Class.forName(type).newInstance();
			if(action instanceof ModelDriver) {
				ModelDriver md = (ModelDriver) action;
				Object bean = md.getModel();
				BeanUtils.populate(bean, request.getParameterMap());
			}
			// 具体业务代码返回值 增加,删除,修改,查看 tolist list
			String res = action.ececute(request, response);
			// 通过此方法 获取返回值
			ForwardModel forwardModel = actionmodel.pop(res);
			if (forwardModel != null) {
				boolean redirect = forwardModel.isRedirect();
				String path = forwardModel.getPath();
				if (redirect) {
					response.sendRedirect(request.getContextPath() + "/" + path);
				} else {
					request.getRequestDispatcher(path).forward(request, response);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

1.3.2 The xml file that needs to be configured

<?xml version="1.0" encoding="UTF-8"?>

<config>
	<action path="/order" type="com.lz.servelt.OederAction">
		<forward name="failed" path="/reg.jsp" redirect="false" />
		<forward name="success" path="/login.jsp" redirect="true" />
	</action>

	<action path="/book" type="com.lz.servelt.bookAction">
		<forward name="list" path="/res.jsp" redirect="false" />
		<forward name="toList" path="/res.jsp" redirect="true" />
	</action>
</config>

 1.3.3 The method of realizing servlet

package com.lz.servelt;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lz.fraamework.Action;

public class OederAction extends  Action{
	/**
	 * 在此实现Orderservelt的方法
	 * @param request
	 * @param response
	 */
	private void Ck(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("ck....订单方法....刘兵小狗狗");
		
	}

	private void upd(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("upd....订单方法");
		
	}

	private void del(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("del....订单方法");
		
	}

	private void add(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("add....订单方法");
		
	}


}
package com.lz.servelt;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lz.entity.Book;
import com.lz.fraamework.Action;
import com.lz.fraamework.ModelDriver;

public class bookAction extends  Action implements  ModelDriver<Book>{
	private Book book = new Book();
	/**
	 * 在此实现servelt的方法
	 * @param request
	 * @param response
	 * @throws Exception 
	 * @throws ServletException 
	 */
	private String add(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, String[]> parameterMap = request.getParameterMap();
		/* 1.要有表对应的类属性对象 Book book
		 * 2.获取到所有的参数 及参数 
		 * 3.将参数值封装到表对应的对象中
		 * 4.要做到所有子控制器通用
		 */
//		String bid = request.getParameter("bid");
//		String bname = request.getParameter("bname");
//		String price = request.getParameter("price");
//		Book book = new Book();
//		book.setBid(Integer.valueOf(bid));
//		book.setBname(bname);
//		book.setPrice(Float.valueOf(price));
		System.out.println("add....方法");
		//request.getRequestDispatcher("res.jsp").forward(request, response);
		request.setAttribute("content", "送快递盒饭");
		return  "toList";
		
	}
	
	
	private String Ck(HttpServletRequest request, HttpServletResponse response) throws ServletException, Exception {
		System.out.println("ck....方法....刘兵小狗狗");
	//	response.sendRedirect("res.jsp");
		request.setAttribute("content", "送快递盒饭");
		return  "List";
		
		
	}

	private  String upd(HttpServletRequest request, HttpServletResponse response) throws Exception {
		System.out.println("upd....方法");
//		request.getRequestDispatcher("res.jsp").forward(request, response);
		request.setAttribute("content", "送快递盒饭");
		return  "toList";
		
	}

	private String del(HttpServletRequest request, HttpServletResponse response) throws Exception {
		System.out.println("del....方法");
	//	request.getRequestDispatcher("res.jsp").forward(request, response);	
		request.setAttribute("content", "送快递盒饭");
		return  "toList";
	}


	@Override
	public Book getModel() {
		// TODO Auto-generated method stub
		return book;
	}




}

2. Invoking business code for reflection, the final page jumps 

1. The page jump of the old version

request.getRequestDispatcher("res.jsp").forward(request, response);    

response.sendRedirect("res.jsp");

It is nothing more than jumping to the cover through these two methods, but using this kind of page jumping requires writing on every page, which is a repetitive code

2. New version

 Implementation idea: define a res, use it to accept our m.invoke method and change our method from void to String

Return res in a return

Secondly:

 Turn our servlet method void into String and return "List" or "toList" (query) in a return to prepare for the subsequent configuration xml

 Change the name attribute to list or ltoist and then change the path path to the page we want to jump to!

Then make an if to judge whether to forward or redirect?

 


3. There are too many code optimization fields in the background of jsp page parameter transfer!

3.1 Encapsulation entity of the old version, get parameters

Disadvantages: There are relatively few field names. If there are too many field names, the number of codes will increase, and it is easy to make mistakes when coding, which is time-consuming

3.2 new version

Model-driven interface replacement Book book = new Book();

 Define a collection to hold the stored data

Map<String, String[]> parameterMap = request.getParameterMap();

Determine whether to implement the interface in DispathServelt

 

                          3. Summary of these methods

<p>Version 5</p>

Common sense: queries must be forwarded, and redirection is used for additions, deletions, and modifications

Disadvantage: the action container loading in the central controller cannot be flexibly configured

<hr>

<a href="book.action?methodName=add">增加</a>

<a href="book.action?methodName=del">删除</a>

<a href="book.action?methodName=upd">修改</a>

<a href="book.action?methodName=list">查询</a>

<p>Version 6</p>

Disadvantages: jsp is passed to the background, and there are too many codes encapsulated into entity classes

<hr>

<a href="book.action?methodName=add&bid=1&bname=nb&price=9.9">增加</a>

<a href="book.action?methodName=del">删除</a>

<a href="book.action?methodName=upd">修改</a>

<a href="book.action?methodName=list">查询</a>

<p>Version 7</p>

<hr>

<a href="book.action?methodName=add&bid=1&bname=nb&price=9.9">增加</a>

<a href="book.action?methodName=del">删除</a>

<a href="book.action?methodName=upd">修改</a>

<a href="book.action?methodName=list">查询</a>

</body>

</html>

So have you learned it?

Guess you like

Origin blog.csdn.net/lz17267861157/article/details/131499656