SpringMVC架构基础案例

一、思维导图

二、项目需要的jar包,以及辅助类

三、代码块以及运行结果

(3.1)补充知识点:解决配置文件可以随意更改的问题

(3.1.1)代码

(3.1.1.1)中央控制器

package com.zking.framework;

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 org.apache.commons.beanutils.PropertyUtils;

import com.zking.web.BookAction;
import com.zking.web.GoodsAction;

/**
 * 目标: 根据自定义mvvc框架的原理图 完成 框架研发
 * 
 * @author My 
 * 	中央控制器 
 * 		寻找子控制器
 *
 */
//@WebServlet("*.action")
public class DispatchServlet extends HttpServlet {
	// 存放子控制器的容器
//	private Map<String, ActionSuppot> actions = new HashMap<String, ActionSuppot>();
	private ConfigModel configModel = null;
	// 初始化子控制器容器(集合),经过初始化,action容器内部就有了子控制器
	// init,service,destroy
	/*
	 * 需求:
	 * 	在增加一个商品类的增删改查
	 * 步骤:
	 * 	改动init代码
	 * 思考:
	 * 	能不能不改动代码完成需求
	 * 	参考DBAccess的数据源配置文件config.properties
	 * 		1.减少代码改动风险性
	 * 		2.减少代码的编译次数(对于已经部署到服务器后)
	 * 	解决方案:
	 * 		改子自控控制可配置
	 * 	解决步骤:
	 * 		1.必须有配置文件config.xml
	 * 		2.配置文件config.xml中要包含处理业务的子控制器
	 * 		3.读取到配置文件config.xml中对应的处理浏览器中的子控制器
	 * 编码
	 * 		....
	 * 
	 */

	@Override
	public void init() throws ServletException {
		try {
//			configModel = ConfigModelFactory.build();
			//配置的文件位置:web.xml
			String configurationLocation = this.getInitParameter("configurationLocation");
			//判空
			if(configurationLocation == null || "".equals(configurationLocation)) {
				configurationLocation = "/huangyanting.xml";
			}
			configModel = ConfigModelFactory.build(configurationLocation);
		
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
//		actions.put("/book", new BookAction());
//		actions.put("/goods", new GoodsAction());
		// action.put("/order", new BookAction());
		// action.put("/OrderItem", new BookAction());

	}

	@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 {
		// 完成寻找子控制器的过程
		// 浏览器:http://locahost:8080/t266_mvc/book.action?methodName
		// 目标:BookAction.add()...
		/*
		 * 思路: 1.从浏览器URL中获取到“/book”字符串 2.在子控制器容器中拿到BookAction 3.BookAction.add()
		 * 
		 */
		String uri = req.getRequestURI();
		uri = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));
//		ActionSuppot action = actions.get(uri);
		ActionModel actionModel = configModel.pop(uri);
		String type = actionModel.getType();
		ActionSuppot action;
		try {
			action = (ActionSuppot)Class.forName(type).newInstance();
			// ActionSuppot action = new BookAction();
			
			if(action instanceof ModelDriver) {
				ModelDriver m = (ModelDriver) action;
				Object obj = m.getModerl();
//				有对象
//				接收所有的前端jsp传递到后台的参数
				Map<String, String[]> parameterMap = req.getParameterMap();
//				给对象赋值
//				PropertyUtils.getProperty(obj, "");
				BeanUtils.populate(obj, parameterMap);
			
			}
//			execite->delete
			String res=action.execute(req, resp);
			/*
			 * 思路:
			 * 	1.方法执行完必须有一个返回值
			 * 	2.返回值决定是否重定向,还是转发
			 * 	3.通过返回值决定跳转哪一个页面
			 */
			ForwardModel forwardModel = actionModel.pop(res);
			if(forwardModel.isRedirect()) {
				resp.sendRedirect(req.getContextPath()+forwardModel.getPath());
			}else {
				req.getRequestDispatcher(forwardModel.getPath()).forward(req, resp);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

(3.1.1.2)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>j2ee14</display-name>
	<servlet>
		<servlet-name>mvc</servlet-name>
		<servlet-class>com.zking.framework.DispatchServlet</servlet-class>
	
		<!-- <init-param>
			<param-name>configurationLocation</param-name>
			<param-value>/mvc.xml</param-value>
		</init-param> -->
	</servlet>
	
	<servlet-mapping>
		<servlet-name>mvc</servlet-name>
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>
</web-app>

(3.1.1.3)页面代码

<%@ 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>
目前多数人增删改查的代码
<a href="${pageContext.request.contextPath }/book/add">增加</a>
<a href="${pageContext.request.contextPath }/book/delete">删除</a>
<a href="${pageContext.request.contextPath }/book/edit">修改</a>
<a href="${pageContext.request.contextPath }/book/list">查询</a>

<hr color="red">
目前多数人增删改查的代码V2.0
<a href="${pageContext.request.contextPath }/book.action?methodName=add">增加</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=delete">删除</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=edit">修改</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=list">查询</a>


<hr color="red">
目前多数人增删改查的代码V3.0
<a href="${pageContext.request.contextPath }/book.action?methodName=load">回显</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=ref">关联</a>

<hr color="red">
演示初始化的缺陷
<a href="${pageContext.request.contextPath }/goods.action?methodName=add">增加</a>
<a href="${pageContext.request.contextPath }/goods.action?methodName=delete">删除</a>
<a href="${pageContext.request.contextPath }/goods.action?methodName=edit">修改</a>
<a href="${pageContext.request.contextPath }/goods.action?methodName=list">查询</a>


解决参数实力类封装的问题
<form action="${pageContext.request.contextPath }/book.action?methodName=ref" method="post">
	<input type="text" name="bid" value="22">
	<input type="text" name="bname" value="yj">
	<input type="text" name="price" value="212">
	<input type="text" name="author" value="zy">
	<input type="text" name="publish" value="hhhh">
	<input type="text" name="remark" value="wwwww">
	<input type="submit">
</form>

</body>
</html>

(3.1.2)运行页面

(3.1.3)运行结果

(3.2.4)*注意:在重新配置xml后一定要把在代码页面的{@WebServlet("*.action")}配置注释掉,不然就会打不开服务器,然后报下面这个错

 (3.2)利用框架开发项目

(3.2.1)代码

(3.2.1.1)dao层

package com.huangyanting.dao;

import java.util.List;

import com.huangyanting.entity.Book;
import com.huangyanting.util.BaseDao;
import com.huangyanting.util.PageBean;
import com.huangyanting.util.StringUtils;

public class BookDao extends BaseDao<Book>{
	/*public void add(Book book) throws Exception {
		String sql = "insert into t_mvc_book values(?,?,?)";
		Connection con = DBAccess.getConnection();
		PreparedStatement pst = con.prepareStatement(sql);
		pst.setObject(1, book.getBid());
		pst.setObject(2, book.getBname());
		pst.setObject(3, book.getPrice());
		pst.executeUpdate();
		
		
		
	}*/
	
	public void add(Book book) throws Exception{
		String sql = "insert into t_mvc_book values(?,?,?)";
		super.executeUpdate(sql, book, new String[] {"bid","bname","price"});
	}
	
	public void delete(Book book) throws Exception{
		String sql = "delete from t_mvc_book where bid=?";
		super.executeUpdate(sql, book, new String[] {"bid"});
	}
	
	
	public void edit(Book book) throws Exception{
		String sql = "update t_mvc_book set bname=?,price=? where bid=?";
		super.executeUpdate(sql, book, new String[] {"bname","price","bid"});
	}
	
	
	public List<Book> list(Book book,PageBean pageBean) throws Exception{
		String sql = "select * from t_mvc_book where 1=1";
		String bname = book.getBname();
		int bid = book.getBid();
		if(StringUtils.isBlank(bname)) {
			sql += " and bname like '%"+bname+"%'";
		}
		if(bid != 0) {
			sql += " and bid = " + bid;
		}
		return super.executeQuery(sql, Book.class, pageBean);
	}
	
	
	//测试
	public static void main(String[] args) throws Exception {
		Book book = new Book();
		book.setBid(420);
//		book.setBname("wwhhh");
//		book.setPrice(454);
		BookDao bookDao = new BookDao();
//		bookDao.add(book);
		bookDao.delete(book);
		
		
	}

}

(3.2.1.2)子控制器

package com.huangyanting.web;

import java.util.List;

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

import com.huangyanting.dao.BookDao;
import com.huangyanting.entity.Book;
import com.huangyanting.util.PageBean;
import com.zking.framework.ActionSuppot;
import com.zking.framework.ModelDriver;

public class BookAction extends ActionSuppot implements ModelDriver<Book>{
	private Book book = new Book();
	private BookDao bookDao = new BookDao();
	
	@Override
	public Book getModerl() {
		return book;
	}
	
	
	public String add(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		bookDao.add(book);
		return "toList";
		
	}
	
	
	public String delete(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		bookDao.delete(book);
		return "toList";
		
	}
	
	
	
	public String edit(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		bookDao.edit(book);
		return "toList";
		
	}
	
	
	
	public String list(HttpServletRequest req, HttpServletResponse resp) {
		
		PageBean pageBean = new PageBean();
		pageBean.setRequest(req);
		try {
			List<Book> list = bookDao.list(book, pageBean);
			req.setAttribute("books", list);
			req.setAttribute("pageBean", pageBean);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "list";
		
	}
	
	
	public String toEdit(HttpServletRequest req, HttpServletResponse resp) {
		//如果跳转的是新增界面无需查询,如果跳转的是修改界面,需要查询当前bid对应的数据
		if(book.getBid() != 0) {
			try {
				List<Book> list = bookDao.list(book, null);
				req.setAttribute("b", list.get(0));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "toEdit";
	}
}

(3.2.2)运行结果

注意代码层级关系

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值