什么是MVC
1: MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,
它是一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码
Model1 jsp+jdbc
Model2 ->MVC
2:核心思想:各司其职
2(1):思路图
3: MVC结构
V
jsp/ios/android
C
servlet/action
M
实体域模型(名词)
过程域模型(动词)
4(普通mvc框架):
4(1):实体类
package com.Liuyujian.entity;
public class Cla {
private String umb1;
private String nub2;
private String nub3;
public String getUmb1() {
return umb1;
}
public void setUmb1(String umb1) {
this.umb1 = umb1;
}
public String getNub2() {
return nub2;
}
public void setNub2(String nub2) {
this.nub2 = nub2;
}
public String getNub3() {
return nub3;
}
public void setNub3(String nub3) {
this.nub3 = nub3;
}
public Cla(String umb1, String nub2, String nub3) {
this.umb1 = umb1;
this.nub2 = nub2;
this.nub3 = nub3;
}
public Cla() {
}
}
4(2):ActionServlet主控制器化名: Dispatcherservlet
package com.Liuyujian.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.Liuyujian.web.AddcalAction;
import com.Liuyujian.web.ChenAction;
import com.Liuyujian.web.ChuAction;
import com.Liuyujian.web.DeletecalAction;
import sun.net.www.content.text.plain;
public class Dispatcherservlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 333239976281186001L;
private Map<String, Action> actionmap=new HashMap<>();
public void init() {
actionmap.put("/addcal",new AddcalAction() );
actionmap.put("/delecal",new DeletecalAction() );
actionmap.put("/chencal",new ChenAction() );
actionmap.put("/chucal",new ChuAction() );
}
@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();//com.Liuyujian.xxxx.action
url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
Action action=actionmap.get(url);
action.execute(req, resp);
}
}
2.1配置主控制器Dispatcherservlet
<?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>web-09</display-name>
<servlet>
<servlet-name>dispatcherservlet</servlet-name>
<servlet-class>com.Liuyujian.framework.Dispatcherservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherservlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
4(3)jsp页面调用
3.1:这个页面用来操作加减乘除:Liuyujian.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>
</head>
<script type="text/javascript">
function myc(var1) {
if(var1==1){
a.action="${pageContext.request.contextPath}/addcal.action"
}else if(var1==2){
a.action="${pageContext.request.contextPath}/delecal.action"
}else if(var1==3){
a.action="${pageContext.request.contextPath}/chencal.action"
}else if(var1==4){
a.action="${pageContext.request.contextPath}/chucal.action"
}
}
</script>
<body>
<form name="a" method="post">
nub1:<input type="text" name="nub1">
nub2:<input type="text" name="nub2">
<button onclick="myc(1)">+</button>
<button onclick="myc(2)">-</button>
<button onclick="myc(3)">*</button>
<button onclick="myc(4)">/</button>
</form>
</body>
</html>
3.2:这个页面用来显示结果:cha.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>
</head>
<body>
结果:${res}
<a href="Liuyujian.jsp">返回</a>
</body>
</html>
**4(4):子控制器包中定义一个子控制器Action
包中定义一个子控制器Action
package com.Liuyujian.framework;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface Action {
String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ;
}
实现于子控制器Action加减乘除
4.1:加
package com.Liuyujian.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.Liuyujian.framework.Action;
public class AddcalAction implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String nub1=req.getParameter("nub1");
String nub2=req.getParameter("nub2");
req.setAttribute("res", Integer.parseInt(nub1)+Integer.parseInt(nub2));
req.getRequestDispatcher("cha.jsp").forward(req, resp);
return null;
}
}
运行:
运行结果:
4(2):减
package com.Liuyujian.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.Liuyujian.framework.Action;
public class DeletecalAction implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String nub1=req.getParameter("nub1");
String nub2=req.getParameter("nub2");
req.setAttribute("res", Integer.parseInt(nub1)-Integer.parseInt(nub2));
req.getRequestDispatcher("cha.jsp").forward(req, resp);
return null;
}
}
运行:
运行结果:
4(3)乘
package com.Liuyujian.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.Liuyujian.framework.Action;
public class ChenAction implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String nub1=req.getParameter("nub1");
String nub2=req.getParameter("nub2");
req.setAttribute("res", Integer.parseInt(nub1)*Integer.parseInt(nub2));
req.getRequestDispatcher("cha.jsp").forward(req, resp);
return null;
}
}
运行:
运行结果:
4.(4)除
package com.Liuyujian.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.Liuyujian.framework.Action;
public class ChuAction implements Action {
@Override
public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String nub1=req.getParameter("nub1");
String nub2=req.getParameter("nub2");
req.setAttribute("res", Integer.parseInt(nub1)/Integer.parseInt(nub2));
req.getRequestDispatcher("cha.jsp").forward(req, resp);
return null;
}
}
运行
运行结果:‘
通过普通mvc框架进行的补充与增强了最主要的还是优化代码
1.将Action的信息配置到xml(反射实例化)以便于完成客户需求
解决了在框架代码中去改动
优化init方法:
private ConfigModel configModel;
public void init() {
// actionMap.put("/addCal", new AddCalAtion());
// actionMap.put("/delCal", new DelCalAtion());
// actionMap.put("/chengCal", new ChengCalAtion());
// actionMap.put("/chuCal", new ChuCalAtion());
try {
configModel=ConfigModelFactory.newInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2增强版子控制器
package com.Liuyujian.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;
public class Actionsuppor implements Action {
//增强版的子控制器,原来的只能做一个用户请求,有时候用户请求是多个,
//增强版就是将一组相关的的操作放在同一个Action中
@Override
public final String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
//传方法名过来
String name=req.getParameter("methidname");
String code=null;
//this在这里指的是Action它的一个类实列
try {
Method m=this.getClass().getDeclaredMethod(name, HttpServletRequest.class,HttpServletResponse.class);
try {
m.setAccessible(true);
code=(String)m.invoke(this, req,resp);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (NoSuchMethodException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return code;
}
}
实现于增强子控制器Actionsuppor加减乘除优化代码在同类中实现方法
(1)首先定义ModelDriver接口Java对象进行赋值(反射读写属性)
package com.Liuyujian.framework;
//作用将jsp所有传递过来的参数以及参数值自动封装到浏览器所要操作的实体类中
public interface ModelDrivern<T> {
T getModel();
}
package com.Liuyujian.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.Liuyujian.entity.Cla;
import com.Liuyujian.framework.Actionsuppor;
import com.Liuyujian.framework.ModelDrivern;
//利用ModelDriver接口对Java对象进行赋值(反射读写属性)
public class CalAticon extends Actionsuppor implements ModelDrivern<Cla> {
private Cla cal=new Cla();
public String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// String nub1=req.getParameter("nub1");
// String nub2=req.getParameter("nub2");
req.setAttribute("res", cal.getUmb1()+cal.getNub2());
// req.getRequestDispatcher("cha.jsp").forward(req, resp);
return "res";
}
public String dele(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
// String nub2=req.getParameter("nub2");
req.setAttribute("res", cal.getUmb1()-cal.getNub2());
// req.getRequestDispatcher("cha.jsp").forward(req, resp);
return "res";
}
public String chen(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
// String nub1=req.getParameter("nub1");
// String nub2=req.getParameter("nub2");
req.setAttribute("res", cal.getUmb1()*cal.getNub2());
// req.getRequestDispatcher("cha.jsp").forward(req, resp);
return "res";
}
public String chu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
// String nub1=req.getParameter("nub1");
// String nub2=req.getParameter("nub2");
req.setAttribute("res",cal.getUmb1()/cal.getNub2());
// req.getRequestDispatcher("cha.jsp").forward(req, resp);
return "res";
}
@Override
public Cla getModel() {
// TODO Auto-generated method stub
return cal;
}
}
3:优化主控制器Dispatcherservlet
package com.Liuyujian.framework;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
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.Liuyujian.web.AddcalAction;
import com.Liuyujian.web.ChenAction;
import com.Liuyujian.web.ChuAction;
import com.Liuyujian.web.DeletecalAction;
import sun.net.www.content.text.plain;
public class Dispatcherservlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 333239976281186001L;
// private Map<String, Action> actionmap=new HashMap<>();
//在Configmodel对象中包含了所有的子控制器
private ConfigModel conf;
public void init() {
// actionmap.put("/addcal",new AddcalAction() );
// actionmap.put("/delecal",new DeletecalAction() );
// actionmap.put("/chencal",new ChenAction() );
// actionmap.put("/chucal",new ChuAction() );
try {
//解决框架配置文件的冲突问题
String xmlpath = this.getInitParameter("xmlPath");
if(xmlpath==null|| "".equals(xmlpath)) {
//工厂模式
conf=ConfigModelFactory.newInstance();
}else {
conf=ConfigModelFactory.newInstance(xmlpath);
}
} 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 {
init();
String url=req.getRequestURI();//com.Liuyujian.xxxx.action
url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
// Action action=actionmap.get(url);
ActionModel acon=conf.get(url);
try {
//利用反射来简化代码
Action action=(Action)Class.forName(acon.getType()).newInstance();
if(action instanceof ModelDrivern) {
ModelDrivern mdDrivern=(ModelDrivern)action;
Object model = mdDrivern.getModel();
BeanUtils.populate(model, req.getParameterMap());
}
// if(acon instanceof ModelDrivern) {
// Object model=mdDrivern.getModel();
// Map<String, String[]> p=req.getParameterMap();
// Set<Entry<String,String[]>> entrySet = p.entrySet();
// Class<? extends Object> clz = model.getClass();
// for (Entry<String, String[]> entry : entrySet) {
// Field field=clz.getField(entry.getKey());
// field.setAccessible(true);
// field.set(model, entry.getKey());
// }
// }
String coud = action.execute(req, resp);
ForwardModel forwardModel =acon.get(coud);
if(forwardModel!=null) {
String path = forwardModel.getPath();
if("false".equals(forwardModel.getRedirect())){
//做转发的处理
req.getRequestDispatcher(path).forward(req, resp);
}else {
resp.sendRedirect(req.getContextPath()+path);
}
}
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//配置
<?xml version="1.0" encoding="UTF-8"?>
<!--
config标签:可以包含0~N个action标签
-->
<config>
<action path="/cal" type="com.Liuyujian.web.CalAticon">
<forward name="res" path="/cha.jsp" redirect="false" />
</action>
</config>
通过XML对自定义mvc框架进行增强
将Action的信息配置到xml(反射实例化)
自建mvc3.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/cal" type="com.leiyuanlin.web.CalAction">
<forward name="res" path="/res.jsp" redirect="false" />
</action>
</config>
在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.tanzhixian.framework.DispatcherServlet</servlet-class>
<init-param>
<param-name>xmlPath</param-name>
<param-value>/mvc3.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
运行加减乘除:
运行结果:加:28,减:20,乘:96,除6;