什么是mvc框架
Model View Controller,是模型-视图-控制器的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个组件里,在改进和个性化定制界面的及用户交互的时候,不需要重新编写业务逻辑。mvc用于映射传统的输入、处理、输出功能在一个逻辑的图形用户界面的结构中。
先要导入架包
工具类
ActionModel类:
package com.lj.framework;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* 用来描述action标签
* @author yyj mmm
*
*/
public class ActionModel implements Serializable{
private static final long serialVersionUID = 6145949994701469663L;
private Map<String, ForwardModel> forwardModels = new HashMap<String, ForwardModel>();
private String path;
private String type;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void put(ForwardModel forwardModel){
forwardModels.put(forwardModel.getName(), forwardModel);
}
public ForwardModel get(String name){
return forwardModels.get(name);
}
}
ConfigModel类
package com.lj.framework;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
public class ConfigModel implements Serializable{
private static final long serialVersionUID = -2334963138078250952L;
private Map<String, ActionModel> actionModels = new HashMap<String, ActionModel>();
public void put(ActionModel actionModel){
actionModels.put(actionModel.getPath(), actionModel);
}
public ActionModel get(String name){
return actionModels.get(name);
}
}
ConfigModelFactory类:
package com.lj.framework;
import java.io.InputStream;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class ConfigModelFactory {
private ConfigModelFactory() {
}
private static ConfigModel configModel = null;
public static ConfigModel newInstance() throws Exception {
return newInstance("config.xml");
}
/**
* 工厂模式创建config建模对象
*
*
*
*
*/
public static ConfigModel newInstance(String path) throws Exception {
if (null != configModel) {
return configModel;
}
ConfigModel configModel = new ConfigModel();
InputStream is = ConfigModelFactory.class.getResourceAsStream(path);
SAXReader saxReader = new SAXReader();
Document doc = saxReader.read(is);
List<Element> actionEleList = doc.selectNodes("/config/action");
ActionModel actionModel = null;
ForwardModel forwardModel = null;
for (Element actionEle : actionEleList) {
actionModel = new ActionModel();
actionModel.setPath(actionEle.attributeValue("path"));
actionModel.setType(actionEle.attributeValue("type"));
List<Element> forwordEleList = actionEle.selectNodes("forward");
for (Element forwordEle : forwordEleList) {
forwardModel = new ForwardModel();
forwardModel.setName(forwordEle.attributeValue("name"));
forwardModel.setPath(forwordEle.attributeValue("path"));
forwardModel.setRedirect(forwordEle.attributeValue("redirect"));
actionModel.put(forwardModel);
}
configModel.put(actionModel);
}
return configModel;
}
public static void main(String[] args) {
try {
ConfigModel configModel = ConfigModelFactory.newInstance();
ActionModel actionModel = configModel.get("/loginAction");
ForwardModel forwardModel = actionModel.get("failed");
System.out.println(actionModel.getType());
System.out.println(forwardModel.getPath());
} catch (Exception e) {
e.printStackTrace();
}
}
}
ForwardModel类
package com.lj.framework;
import java.io.Serializable;
public class ForwardModel implements Serializable {
private static final long serialVersionUID = -8587690587750366756L;
private String name;
private String path;
private String redirect;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getRedirect() {
return redirect;
}
public void setRedirect(String redirect) {
this.redirect = redirect;
}
}
在上面这些代码的前提下增强一下,一共有5点
第一点是对存放子控制器action容器的增强
DispatcherServlet
package com.lj.framework;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
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 com.lj.web.AddCalAction;
import com.lj.web.CheCalAction;
import com.lj.web.ChuCalAction;
import com.lj.web.DelCalAction;
/**
* 中央控制器
* 作用:
* 接受用户请求,通过用户请求的url寻找指定的控制器去处理业务层
*
*
* 1.对存放子控制器action容器的增强
* ?:原来为了完成业务需求,需要不断修改框架的代码,这样设计是不合理的
* 处理方式:参照web.xml的实际方法来完成中央控制器管理子控制器的动态配置
* @author yyj mmm
*
*/
public class DispatcherServlet extends HttpServlet{
private static final long serialVersionUID = -4842215863301289197L;
private ConfigModel configModel=null;
public void init() {
try {
configModel=ConfigModelFactory.newInstance();
} 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 {
String url=req.getRequestURI();
url=url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));
ActionModel actionModel = configModel.get(url);
try {
Action action = (Action) Class.forName(actionModel.getType()).newInstance();
action.execute(req, resp);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
然后在配置
<action path="/cal_add" type="com.lj.web.AddCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
<action path="/cal_del" type="com.lj.web.DelCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
<action path="/cal_che" type="com.lj.web.CheCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
<action path="/cal_chu" type="com.lj.web.ChuCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
第二个处理结果码的跳转形式
DispatcherServlet2
package com.lj.framework;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lj.web.AddCalAction;
import com.lj.web.CheCalAction;
import com.lj.web.ChuCalAction;
import com.lj.web.DelCalAction;
/**
* 中央控制器
* 作用:
* 接受用户请求,通过用户请求的url寻找指定的控制器去处理业务层
* @author yyj mmm
*
* 1.对存放子控制器action容器的增强
* ?:原来为了完成业务需求,需要不断修改框架的代码,这样设计是不合理的
* 处理方式:参照web.xml的实际方法来完成中央控制器管理子控制器的动态配置
*
* 2.处理结果码的跳转信息
* 达到简化代码的结果
*
*
*/
public class DispatcherServlet2 extends HttpServlet{
private static final long serialVersionUID = -4842215863301289197L;
// private Map<String , Action> actionMap=new HashMap<String,Action>();
private ConfigModel configModel=null;
public void init() {
//http://localhost:8080/mvc/cal_add.action
// actionMap.put("/cal_add", new AddCalAction());
// actionMap.put("/cal_del", new DelCalAction());
// actionMap.put("/cal_chu", new ChuCalAction());
// actionMap.put("/cal_che", new CheCalAction());
try {
configModel =ConfigModelFactory.newInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
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 {
String url=req.getRequestURI();
url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
// Action action=actionMap.get(url);
ActionModel actionModel = configModel.get(url);
try {
if(actionModel==null) {
throw new RuntimeException("你没有配置指定的控制器来处理用户请求");
}
Action action=(Action) Class.forName(actionModel.getType()).newInstance();
String code = action.execute(req, resp);
ForwardModel forwardModel = actionModel.get(code);
if("false".equals(forwardModel.getRedirect())) {
req.getRequestDispatcher(forwardModel.getPath()).forward(req, resp);
}else {
// 注意:默认会缺损项目名
resp.sendRedirect(req.getContextPath()+forwardModel.getPath());
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
然后在配置
<?xml version="1.0" encoding="UTF-8"?>
<config
<action path="/cal_add" type="com.lj.web.AddCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
<action path="/cal_del" type="com.lj.web.DelCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
<action path="/cal_che" type="com.lj.web.CheCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
<action path="/cal_chu" type="com.lj.web.ChuCalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
</config>
第三个操作一组子控制器去完成
ActionSupport
package com.lj.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;
/**
* 增强版的子控制器
* @author yyj mmm
*
*/
public class ActionSupport implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 从前台传递需要调用方法名到后台,实现动态方法调用
String methodName = req.getParameter("methodName");
// 思考:
String code=null;
try {
Method m = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
m.setAccessible(true);
code=(String) m.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
package com.lj.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lj.entity.Cal;
import com.lj.framework.Action;
import com.lj.framework.ActionSupport;
import com.lj.framework.ModelDriven;
public class CalAction extends ActionSupport {
public String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
Cal cal=new Cal(num1, num2);
req.setAttribute("rs", Integer.valueOf(cal.getNum1())+Integer.valueOf(cal.getNum2()));
req.getRequestDispatcher("/rs.jsp").forward(req, resp);
return "rs";
}
public String del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
Cal cal=new Cal(num1, num2);
req.setAttribute("rs", Integer.valueOf(cal.getNum1())-Integer.valueOf(cal.getNum2()));
req.getRequestDispatcher("/rs.jsp").forward(req, resp);
return "rs";
}
public String che(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
Cal cal=new Cal(num1, num2);
req.setAttribute("rs", Integer.valueOf(cal.getNum1())*Integer.valueOf(cal.getNum2()));
req.getRequestDispatcher("/rs.jsp").forward(req, resp);
return "rs";
}
public String chu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String num1=req.getParameter("num1");
String num2=req.getParameter("num2");
Cal cal=new Cal(num1, num2);
req.setAttribute("rs", Integer.valueOf(cal.getNum1())/Integer.valueOf(cal.getNum2()));
req.getRequestDispatcher("/rs.jsp").forward(req, resp);
return "rs";
}
}
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(v){
if(v==1){
calForm.action="${pageContext.request.contextPath}/cal.action?methodName=add"
}else if(v==2){
calForm.action="${pageContext.request.contextPath}/cal.action?methodName=del"
}else if(v==3){
calForm.action="${pageContext.request.contextPath}/cal.action?methodName=che"
}else if(v==4){
calForm.action="${pageContext.request.contextPath}/cal.action?methodName=chu"
}
calForm.submit;
}
</script>
</head>
<body>
<form id="calForm" action=""method="post">
num1:<input type="text" name="num1"><br>
num2:<input type="text" name="num2"><br>
<button onclick="doSub(1)">+</button>
<button onclick="doSub(2)">-</button>
<button onclick="doSub(3)">*</button>
<button onclick="doSub(4)">/</button>
</form>
</body>
</html>
第4个处理jsp给参数封装
先定义一个接口
ModelDriven
package com.lj.framework;
/**
* 模型驱动接口
* 作用:给对应处理业务的子控制器中包含的实体类进行jsp参数封装
* @author yyj mmm
*
* @param <T>
*/
public interface ModelDriven<T> {
T getModel();
}
CalAction
package com.lj.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lj.entity.Cal;
import com.lj.framework.Action;
import com.lj.framework.ActionSupport;
import com.lj.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("rs", Integer.valueOf(cal.getNum1()) + Integer.valueOf(cal.getNum2()));
return "rs";
}
public String del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("rs", Integer.valueOf(cal.getNum1()) - Integer.valueOf(cal.getNum2()));
return "rs";
}
public String che(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("rs", Integer.valueOf(cal.getNum1()) * Integer.valueOf(cal.getNum2()));
return "rs";
}
public String chu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("rs", Integer.valueOf(cal.getNum1()) / Integer.valueOf(cal.getNum2()));
return "rs";
}
@Override
public Cal getModel() {
// TODO Auto-generated method stub
return cal;
}
}
改一下DispatcherServlet
package com.lj.framework;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
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 com.lj.web.AddCalAction;
import com.lj.web.CheCalAction;
import com.lj.web.ChuCalAction;
import com.lj.web.DelCalAction;
/**
* 中央控制器
* 作用:
* 接受用户请求,通过用户请求的url寻找指定的控制器去处理业务层
* @author yyj mmm
*
* 1.对存放子控制器action容器的增强
* ?:原来为了完成业务需求,需要不断修改框架的代码,这样设计是不合理的
* 处理方式:参照web.xml的实际方法来完成中央控制器管理子控制器的动态配置
* @author yyj mmm
*
*/
public class DispatcherServlet extends HttpServlet{
private static final long serialVersionUID = -4842215863301289197L;
// private Map<String , Action> actionMap=new HashMap<String,Action>();
private ConfigModel configModel=null;
public void init() {
//http://localhost:8080/mvc/cal_add.action
// actionMap.put("/cal_add", new AddCalAction());
// actionMap.put("/cal_del", new DelCalAction());
// actionMap.put("/cal_chu", new ChuCalAction());
// actionMap.put("/cal_che", new CheCalAction());
try {
configModel =ConfigModelFactory.newInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
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 {
String url=req.getRequestURI();
url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
// Action action=actionMap.get(url);
ActionModel actionModel = configModel.get(url);
try {
if(actionModel==null) {
throw new RuntimeException("你没有配置指定的控制器来处理用户请求");
}
Action action=(Action) Class.forName(actionModel.getType()).newInstance();
if(action instanceof ModelDriven) {
ModelDriven modelDriven=(ModelDriven) action;
Object model = modelDriven.getModel();
// 给model赋值了,意味着在调用add/del方法的时候cal不再是空的了
BeanUtils.populate(model, req.getParameterMap());
}
String code = action.execute(req, resp);
ForwardModel forwardModel = actionModel.get(code);
if("false".equals(forwardModel.getRedirect())) {
req.getRequestDispatcher(forwardModel.getPath()).forward(req, resp);
}else {
// 注意:默认会缺损项目名
resp.sendRedirect(req.getContextPath()+forwardModel.getPath());
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
第5个问题
解决框架配置文件重名冲突问题
package com.lj.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;
/**
* 中央控制器
* 作用:
* 接受用户请求,通过用户请求的url寻找指定的控制器去处理业务层
* @author yyj mmm
*
* 1.对存放子控制器action容器的增强
* ?:原来为了完成业务需求,需要不断修改框架的代码,这样设计是不合理的
* 处理方式:参照web.xml的实际方法来完成中央控制器管理子控制器的动态配置
*
* 2.处理结果码的跳转信息
* 达到简化代码的结果
*
* 3.将一组操作放到一个子控制器去完成
*
* 4.处理jsp传递到后台的参数封装
*
* 5.解决框架配置文件名冲突问题
*
* @author yyj mmm
*
*/
public class DispatcherServlet5 extends HttpServlet{
private static final long serialVersionUID = -4842215863301289197L;
// private Map<String , Action> actionMap=new HashMap<String,Action>();
private ConfigModel configModel=null;
public void init() {
//http://localhost:8080/mvc/cal_add.action
// actionMap.put("/cal_add", new AddCalAction());
// actionMap.put("/cal_del", new DelCalAction());
// actionMap.put("/cal_chu", new ChuCalAction());
// actionMap.put("/cal_che", new CheCalAction());
try {
String mvcXmlLocation=this.getInitParameter("mvcXmlLocation");
if(null==mvcXmlLocation || "".equals(mvcXmlLocation)) {
mvcXmlLocation="mvc.xml";
}
System.out.println("mvcXmlLocation:"+mvcXmlLocation);
configModel =ConfigModelFactory.newInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
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 {
String url=req.getRequestURI();
url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
// Action action=actionMap.get(url);
ActionModel actionModel = configModel.get(url);
try {
if(actionModel==null) {
throw new RuntimeException("你没有配置指定的控制器来处理用户请求");
}
Action action=(Action) Class.forName(actionModel.getType()).newInstance();
if(action instanceof ModelDriven) {
ModelDriven modelDriven=(ModelDriven) action;
Object model = modelDriven.getModel();
// 给model赋值了,意味着在调用add/del方法的时候cal不再是空的了
BeanUtils.populate(model, req.getParameterMap());
}
String code = action.execute(req, resp);
ForwardModel forwardModel = actionModel.get(code);
if("false".equals(forwardModel.getRedirect())) {
req.getRequestDispatcher(forwardModel.getPath()).forward(req, resp);
}else {
// 注意:默认会缺损项目名
resp.sendRedirect(req.getContextPath()+forwardModel.getPath());
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
最后在修改一下web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>mvc</display-name>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>com.lj.framework.DispatcherServlet4</servlet-class>
<init-param>
<param-name>mvcXmlLocation</param-name>
<param-value>/lj.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>