博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
MVC模式在Java Web应用程序中的实例分析
阅读量:6039 次
发布时间:2019-06-20

本文共 12666 字,大约阅读时间需要 42 分钟。

      MVC在软件架构中是一种比较重要的架构思想,已经被广泛的应用在实际的java web项目开发中,我们所要了解和掌握的是mvc的架构思想和使用mvc模式来分析和解决问题的方法。当然相同或不同的项目都有各种分析解决的思路,这里采用一个应用struts2+hibernate+jsp的实例系统来进一步分析mvc模式。

以班级管理系统为例的架构图:

首先由用户通过VIEW层对系统进行业务请求:

classAdd.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>              新增班级    

班级管理 > 新增班级

请输入新增班级信息

Copyright © 石家庄铁道大学软件工程系

然后由Controller层通过struts的拦截器对view层的拦截过滤,实现调用不同的业务处理逻辑。

web.xml

login.html
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*
contextConfigLocation
/WEB-INF/classes/applicationContext.xml
org.springframework.web.context.ContextLoaderListener
openSessionInView
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
openSessionInView
/*

struts.xml

home.jsp
login.html
classInformation.jsp
classAdd.jsp
classInformation.jsp
classInformation.jsp
studentInformation.jsp
studentAdd.jsp
studentInformation.jsp
studentInformation.jsp

找到相应的action去处理相应的业务:

ClassAddAction.java

package com.zdr.action;import com.opensymphony.xwork2.ActionSupport;import com.zdr.entity.Classunit;import com.zdr.service.ClassunitService;public class ClassAddAction extends ActionSupport{    //变量    private String classunitname = "";    private String classunitnumber = "";    private String result = "";    private ClassunitService classunitService;    private Classunit classnumber;        //函数    public String getClassunitname() {        return classunitname;    }    public void setClassunitname(String classunitname) {        this.classunitname = classunitname;    }    public String getClassunitnumber() {        return classunitnumber;    }    public void setClassunitnumber(String classunitnumber) {        this.classunitnumber = classunitnumber;    }    public String getResult() {        return result;    }    public void setResult(String result) {        this.result = result;    }    public ClassunitService getClassunitService() {        return classunitService;    }    public void setClassunitService(ClassunitService classunitService) {        this.classunitService = classunitService;    }        @Override    public String execute() throws Exception    {        if(classunitService.checkClassnumber(getClassunitnumber()))        {            //result = "班级编号重复!";            return ERROR;        }        else        {            classnumber = new Classunit();            classnumber.setClassNumber(classunitnumber);            classnumber.setClassName(classunitname);            classunitService.addClassunit(classnumber);        }        return SUCCESS;    }    }

通过调用关系,调用model层dao层方法完成业务处理:

package com.zdr.dao;import java.util.List;import java.util.Set;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.hibernate.Criteria;import org.hibernate.LockMode;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.criterion.Restrictions;import org.springframework.context.ApplicationContext;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import com.zdr.entity.Classunit;import com.zdr.entity.Student;/** * A data access object (DAO) providing persistence and search support for * Classunit entities. Transaction control of the save(), update() and delete() * operations can directly support Spring container-managed transactions or they * can be augmented to handle user-managed Spring transactions. Each of these * methods provides additional information for how to configure it for the * desired type of transaction control. *  * @see com.zdr.entity.Classunit * @author MyEclipse Persistence Tools */public class ClassunitDAO extends HibernateDaoSupport {    private static final Log log = LogFactory.getLog(ClassunitDAO.class);    private SessionFactory sessionFactory;    private Session session;    // property constants    public static final String CLASS_NAME = "className";    protected void initDao() {        // do nothing    }        public  boolean checkClassnumber(String  classunitnumber)     {            if(classunitnumber!= null)            {            Classunit cun = findById(classunitnumber);            if(cun == null)            {                return  false;            }            }            return  true;        }        public Classunit findclassunitnumber(String classunitnumber)    {        if(classunitnumber!=null)        {            return findById(classunitnumber);        }        return null;            }    public void save(Classunit transientInstance) {        log.debug("saving Classunit instance");        try {            getHibernateTemplate().save(transientInstance);            log.debug("save successful");        } catch (RuntimeException re) {            log.error("save failed", re);            throw re;        }    }    public void delete(Classunit persistentInstance) {        log.debug("deleting Classunit instance");        try {            getHibernateTemplate().delete(persistentInstance);            log.debug("delete successful");        } catch (RuntimeException re) {            log.error("delete failed", re);            throw re;        }    }    public Classunit findById(java.lang.String id) {        log.debug("getting Classunit instance with id: " + id);        try {            Classunit instance = (Classunit) getHibernateTemplate().get(                    "com.zdr.entity.Classunit", id);            return instance;        } catch (RuntimeException re) {            log.error("get failed", re);            throw re;        }    }    public List
findByExample(Classunit instance) { log.debug("finding Classunit instance by example"); try { List
results = (List
) getHibernateTemplate() .findByExample(instance); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { log.debug("finding Classunit instance with property: " + propertyName + ", value: " + value); try { String queryString = "from Classunit as model where model." + propertyName + "= ?"; return getHibernateTemplate().find(queryString, value); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List
findByClassName(Object className) { return findByProperty(CLASS_NAME, className); } public List
findAll() { log.debug("finding all Classunit instances"); try { String queryString = "from Classunit"; return getHibernateTemplate().find(queryString); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public Classunit merge(Classunit detachedInstance) { log.debug("merging Classunit instance"); try { Classunit result = (Classunit) getHibernateTemplate().merge( detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(Classunit instance) { log.debug("attaching dirty Classunit instance"); try { getHibernateTemplate().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(Classunit instance) { log.debug("attaching clean Classunit instance"); try { getHibernateTemplate().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public static ClassunitDAO getFromApplicationContext(ApplicationContext ctx) { return (ClassunitDAO) ctx.getBean("ClassunitDAO"); }}

处理结果再由struts.xml去返回相应的结果所对应的业务方向。

调用关系图:

总结:

      当用户通过view层向系统发送业务请求时,struts.xml根据已经定义好的处理逻辑进行相应的处理,将其业务分给指定的action来处理。而model层通过不同的业务逻辑调用实现试图和逻辑的分层,由action去调用相应的dao层业务进行业务逻辑处理,处理结果再由struts.xml去返回相应的结果所对应的业务方向。

通过mvc体现的质量属性:

可修改性:将视图与业务逻辑分离,易于业务的变动和修改。

 

转载于:https://www.cnblogs.com/lk0823/p/6825274.html

你可能感兴趣的文章
Matlab编程之——卷积神经网络CNN代码解析
查看>>
三篇文章了解 TiDB 技术内幕 —— 说计算
查看>>
copy strong weak assign的区别
查看>>
OpenCV 入门
查看>>
css 3D transform变换
查看>>
ele表格合并行之后的selection选中
查看>>
正则表达式分解剖析(一文悟透正则表达式)
查看>>
解决UILable标点符号居中的问题
查看>>
HTML5新特性教程
查看>>
ImageOptim-无损图片压缩Mac版
查看>>
12 Go语言map底层浅析
查看>>
vue-resumer 项目中 element-ui 遇到的 textarea autosize 问题
查看>>
以主干开发作为持续交付的基础
查看>>
PHP扩展库PEAR被攻击,近半年下载者或被影响
查看>>
传统运维团队转型应该注意哪些问题?
查看>>
JavaScript函数(二)
查看>>
Airbnb改进部署管道安全性,规范部署顺序
查看>>
腾讯最大规模裁撤中层干部,让贤年轻人
查看>>
当我们谈性能的时候,我们实际上在谈什么?
查看>>
蔡超:入门 Go 语言必须跨越的五个思维误区
查看>>