今天的任务:通过XML对自定义mvc框架进行增强
1、 将Action的信息配置到xml(反射实例化)
2 、通过结果码控制页面的跳转
3 、将一组相关的操作放到一个Action中(反射调用方法)
4 、利用ModelDriver接口对Java对象进行赋值(反射读写方法)
5、 使得框架的配置文件可变
下面进行对昨天加减乘除案例进行增强:
所需jar包:
核心代码如下:
模型驱动接口 ModelDriven.java:
package com.liyi.framework;
/**
* 模型驱动接口
* 是用来处理jsp页面传递过来的参数,将所有的参数自动封装到实体类T中
* @author 224李毅
* @param <T>
*/
public interface ModelDriven<T> {
T getModel();
}
主控制器DispatcherServlet.java:
package com.liyi.framework;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.dom4j.DocumentException;
/**
* 主控制器
* @author 224李毅
*
*/
public class DispatcherServlet extends HttpServlet{
private static final long serialVersionUID = -7500451840558220628L;
private ConfigModel configModel = null;
public void init() {
try {
//将原有的读取框架的默认配置文件转变成读取可配置路径的配置文件
String xmlPath = this.getInitParameter("xmlPath");
if(xmlPath==null||"".equals(xmlPath)) {
configModel = ConfigModelFactory.newInstance();
}
else {
configModel = ConfigModelFactory.newInstance(xmlPath);
}
} catch (DocumentException e) {
e.printStackTrace();
} 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();
url = url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
ActionModel actionModel = configModel.get(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 ModelDriven) {
ModelDriven modelDriven = (ModelDriven)action;
Object model = modelDriven.getModel();
// Map<String, String[]> map = req.getParameterMap();
// for(Map.Entry<String, String[]> entry : map.entrySet()) {
// //可以获取到类对应的属性,获取到类所对应的属性值
// }
BeanUtils.populate(model, req.getParameterMap());
}
//每个子控制器,都需要对结果进行对应的处理,也就是说要么转发,要么重定向,代码重复量较大
//针对这一现象,将其叫给配置文件来处理
// 调用了增强版的子控制器来处理业务逻辑
String code = action.execute(req, resp);
ForwardModel forwardModel = actionModel.get(code);
if(forwardModel==null) {
throw new RuntimeException("你没有配置对应的子控制器Action的处理方式Forward");
}
String jspPath = forwardModel.getPath();
if(forwardModel.getRedirect().equals("true")) {
resp.sendRedirect(req.getContextPath()+jspPath);
}else {
req.getRequestDispatcher(jspPath).forward(req, resp);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
子控制器: Action.java:
package com.liyi.framework;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 子控制器
* 专门用来处理业务逻辑的
* @author 224李毅
*
*/
public interface Action {
String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
}
增强版的子控制器: ActionSupport.java:
package com.liyi.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 224李毅
*/
public class ActionSupport implements Action{
@Override
public final String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String methodName = req.getParameter("methodName");
String code = "";
try {
Method method = this.getClass().getDeclaredMethod(methodName,
HttpServletRequest.class,
HttpServletResponse.class
);
method.setAccessible(true);
//具体调用了你自己所写的子控制器中的方法来处理浏览器请求
code = (String) method.invoke(this, req,resp);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return code;
}
}
CalAction.java:
package com.liyi.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.liyi.entity.Cal;
import com.liyi.framework.ActionSupport;
import com.liyi.framework.ModelDriven;
public class CalAction extends ActionSupport implements ModelDriven<Cal>{
private Cal cal = new Cal();
public String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("res", Integer.parseInt(cal.getNum1()) + Integer.parseInt(cal.getNum2()));
return "claRes";
}
public String del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("res", Integer.parseInt(cal.getNum1()) - Integer.parseInt(cal.getNum2()));
return "claRes";
}
public String chen(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("res", Integer.parseInt(cal.getNum1()) * Integer.parseInt(cal.getNum2()));
return "claRes";
}
public String chu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("res", Integer.parseInt(cal.getNum1()) / Integer.parseInt(cal.getNum2()));
return "claRes";
}
@Override
public Cal getModel() {
return cal;
}
}
cal.jsp界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function doSub(val){
if(val == 1){
calForm.methodName.value="add";
}
else if(val == 2){
calForm.methodName.value="del";
}
else if(val == 3){
calForm.methodName.value="chen";
}
else if(val == 4){
calForm.methodName.value="chu";
}
calForm.submit();
}
</script>
</head>
<body>
<form id="calForm" name="calForm" action="${pageContext.request.contextPath }/cal.action " method="post">
num1:<iwebput name="num1"><br>
num2:<input name="num2"><br>
<input type="hidden" name="methodName">
<button onclick="doSub(1)">+</button>
<button onclick="doSub(2)">-</button>
<button onclick="doSub(3)">*</button>
<button onclick="doSub(4)">/</button>
</form>
</body>
</html>
结果界面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
结果:${res }
</body>
</html>
使得框架的配置文件可变:
web.xml:
好啦今天的更新到此结束,喜欢点赞+转发~