MVC2

本文介绍了一个基于Java的计算器Web应用实现案例,通过DispatcherServlet作为中央控制器接收并处理请求,使用ActionModel描述业务逻辑,ConfigModel配置子控制器信息,实现加减乘除功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

计算器案例
在这里插入图片描述
结果:
在这里插入图片描述
实体类Cal
代码:

package com.pengyuxuan.entity;

public class Cal {

	private int num1;
	private int num2;
	public int getNum1() {
		return num1;
	}
	public void setNum1(int num1) {
		this.num1 = num1;
	}
	public int getNum2() {
		return num2;
	}
	public void setNum2(int num2) {
		this.num2 = num2;
	}
	public Cal(int num1, int num2) {
		super();
		this.num1 = num1;
		this.num2 = num2;
	}
	public Cal() {
		super();
	}
	
}

DispatcherServlet
中央控制器
作用:接受请求,通过请求寻找处理请求的对应的自控器
代码

package com.pengyuxuan.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;


public class DispatcherServlet extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 3794145129007885550L;
	/**
	 * 中央控制器   DispatcherServlet
	 * 作用:接受请求,通过请求寻找处理请求的对应的自控器
	 * 
	 */
	
//  所有的子控制器都应该配置到configModel
	private ConfigModel configModel;
	public void init() {
		try {
			String xmlPath=this.getInitParameter("xmlPath");
			if(xmlPath==null || "".equals(xmlPath)) {
//			   这时configModel对象中有了子控制器所有的信息
				configModel=ConfigModelFactory.newInstance();
			}else {
				configModel=ConfigModelFactory.newInstance(xmlPath);
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
@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 {
	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 {
		Action action =(Action)Class.forName(actionModel.getType()).newInstance();
		if(action instanceof ModelDrivern) {
//			向上转型
			ModelDrivern modelDrivern=(ModelDrivern) action;
//			此时model的所有属性值是null;
			Object model = modelDrivern.getModel();
			BeanUtils.populate(model, req.getParameterMap());
			

		}
//		子控制器的返回码
	    String code = action.execute(req, resp);
//	    根据名字拿到要跳转的界面
	    ForwardModel forwardModel = actionModel.get(code);
	    if(forwardModel!=null) {
//	    	拿到跳转页面的路径
	    	String jspPath = forwardModel.getPath();
	    	if("false".equals(forwardModel.getRedirect())) {
//	    		做转发的处理
	    		req.getRequestDispatcher(jspPath).forward(req, resp);
	    	}else {
//	    		写重定向时必须加上路径名
	    		resp.sendRedirect(req.getContextPath()+jspPath);
	    	}
	    }
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (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();
		}
	}
}

Action 子控制器
转门用来处理业务逻辑的
代码

package com.pengyuxuan.framework;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 子控制器
 * 转门用来处理业务逻辑的
 * @author dell
 *
 */
public interface Action {
	
	String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;

}

ActionSupport 增强版的子控制器
代码:

package com.pengyuxuan.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 dell
 *
 */

public class ActionSupport implements Action {

	@Override
	public String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String methodName=req.getParameter("methodName");
		String code=null;
//		this在这里指的是子控制器它的一个类实例
		try {
			Method m = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
		    m.setAccessible(true);
			code= (String)m.invoke(this, req,resp);
		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return code;
	}

}

ModelDrivern
模型驱动接口
代码:

package com.pengyuxuan.framework;


/**
 * 模型驱动接口
 * 作用是将jsp所有专递过来的参数以及参数值都自动封装到浏览器所要操作的实体类中
 * @author dell
 *
 */

public interface ModelDrivern<T> {
	T getModel();
}

CalAction
加减乘除方法
代码:

package com.pengyuxuan.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.pengyuxuan.entity.Cal;
import com.pengyuxuan.framework.ActionSupport;
import com.pengyuxuan.framework.ModelDrivern;

public class CalAction extends ActionSupport implements ModelDrivern<Cal>{
	private Cal cal=new Cal();
	//加
	public String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.setAttribute("res",cal.getNum1()+cal.getNum2());
		return "res";
	}
	//减
	public String del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.setAttribute("res",cal.getNum1()-cal.getNum2());
		return "res";
	}
	//乘
public String mul(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.setAttribute("res",cal.getNum1()*cal.getNum2());
		return "res";
	}
	//除
	public String div(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.setAttribute("res",cal.getNum1()/cal.getNum2());
		return "res";
	}
	@Override
	public Cal getModel() {
		// TODO Auto-generated method stub
		return cal;
	}
}

配置web.xml
代码:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>pengyuxuan</display-name>
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>com.pengyuxuan.framework.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>xmlPath</param-name>
      <param-value>mvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

ActionModel
用来描述action标签
代码;

package com.pengyuxuan.framework;

import java.io.Serializable;

import java.util.HashMap;
import java.util.Map;

/**
 * 用来描述action标签
 * @author Administrator
 *
 */

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
用来描述config标签

package com.pengyuxuan.framework;

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


/**
 * 用来描述config标签
 * @author Administrator
 *
 */
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.pengyuxuan.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("mvc.xml");
	}

	/**
	 * 
	 * 
	 * @param path
	 * @return
	 * @throws Exception
	 */
	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
用来描述forward标签

代码:

package com.pengyuxuan.framework;

import java.io.Serializable;


/**
 * 用来描述forward标签
 * @author Administrator
 *
 */
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;
	}

}

mvc.xml
将Action的信息配置到xml(反射实例化)
代码:

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

<config>
	<action path="/cal" type="com.pengyuxuan.web.CalAction">
		<forward name="res" path="/res.jsp" redirect="false"  />
	</action>
</config>

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=ISO-8859-1">
<title>Insert title here</title>
</head>
<script type="text/javascript">
function doSub(num) {
	if(num==1){
		calForm.action="${pageContext.request.contextPath}/cal.action?methodName=add";
	}else if(num==2){
		calForm.action="${pageContext.request.contextPath}/cal.action?methodName=del";
	}else if(num==3){
		calForm.action="${pageContext.request.contextPath}/cal.action?methodName=mul";
	}else if(num==4){
		calForm.action="${pageContext.request.contextPath}/cal.action?methodName=div";
	}
	calForm.submit();
}
</script>
<body>
<form name="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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值