首页 > 代码库 > MVC模式在Java Web应用程序中的实例分析
MVC模式在Java Web应用程序中的实例分析
MVC作为软件架构中及其重要的一种架构思想,在实际的java web项目开发中被开发者们广泛的应用。遵循MVC思想的所产生的解决方法也可以因实际情况的不同来进行不同的选择。这里以一个应用struts+hibernate+jsp的实例来进一步认识MVC。
学生管理系统中添加学生模块的的MVC架构:
- Model(系统的业务逻辑):Hibernate进行管理的数据实体+定义的业务逻辑的体现--------数据库操作类,也就是通常所说的Dao层
数据实体(PO,Entity):
package PO; /** * Student entity. @author MyEclipse Persistence Tools */ public class Student implements java.io.Serializable { // Fields private String id; private String name; private String sex; private Integer age; private Float sweight; // Constructors /** default constructor */ public Student() { } /** full constructor */ public Student(String id, String name, String sex, Integer age, Float sweight) { this.id = id; this.name = name; this.sex = sex; this.age = age; this.sweight = sweight; } // Property accessors public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getSex() { return this.sex; } public void setSex(String sex) { this.sex = sex; } public Integer getAge() { return this.age; } public void setAge(Integer age) { this.age = age; } public Float getSweight() { return this.sweight; } public void setSweight(Float sweight) { this.sweight = sweight; } }
数据实体映射文件:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="PO.Student" table="Student" schema="dbo" catalog="dbSm"> <id name="id" type="java.lang.String"> <column name="ID" /> <generator class="assigned" /> </id> <property name="name" type="java.lang.String"> <column name="Name" not-null="true" /> </property> <property name="sex" type="java.lang.String"> <column name="sex" not-null="true" /> </property> <property name="age" type="java.lang.Integer"> <column name="age" not-null="true" /> </property> <property name="sweight" type="java.lang.Float"> <column name="sweight" precision="53" scale="0" not-null="true" /> </property> </class> </hibernate-mapping>
Hibernate映射文件:
<?xml version=‘1.0‘ encoding=‘UTF-8‘?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="dialect"> org.hibernate.dialect.SQLServerDialect </property> <property name="connection.url"> jdbc:sqlserver://127.0.0.1:1433;databaseName=dbSm </property> <property name="connection.username">sa</property> <property name="connection.password">153532</property> <property name="connection.driver_class"> com.microsoft.sqlserver.jdbc.SQLServerDriver </property> <property name="myeclipse.connection.profile">DBSM</property> <mapping resource="PO/Student.hbm.xml" /> </session-factory> </hibernate-configuration>
业务逻辑由Dao体现:
package Dao; import java.util.List; import javax.swing.JOptionPane; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import addHibernateFile.HibernateSessionFactory; import PO.Student; public class StudentDao { private Transaction transaction; private Session session; private Query query; public StudentDao(){ } public boolean saveInfo(Student stu){ try{ session = HibernateSessionFactory.getSession(); transaction = session.beginTransaction(); if(session.get(Student.class,stu.getId())== null) { session.save(stu); } transaction.commit(); session.close(); return true; }catch(Exception e){ message("saveInfo.error:"+e); e.printStackTrace(); return false; } } public List findInfo(String type,Object value) { session = HibernateSessionFactory.getSession(); try{ transaction = session.beginTransaction(); //HQL语句 String queryString = "from Student as model where model."+type+"=?"; query = session.createQuery(queryString); query.setParameter(0, value); List list = query.list(); transaction.commit(); session.close(); return list; }catch(Exception e){ message("findInfo.error:"+e); e.printStackTrace(); return null; } } public List findAllInfo() { session = HibernateSessionFactory.getSession(); try{ transaction = session.beginTransaction(); String queryString = "from Student"; query = session.createQuery(queryString); List list = query.list(); transaction.commit(); session.close(); return list; }catch(Exception e){ message("findInfo.error"+e); e.printStackTrace(); return null; } } }
- View(视图层):由jsp和html页面所展现的让用户进行操作或展示用户操作结果的界面。
addMessage.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title><s:text name="学生信息管理系统-增加"></s:text></title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="http://www.mamicode.com/styles.css"> --> </head> <body bgcolor="#cccccc"> <s:div align="center"> <hr color="#99ccff"> <br/> <table align="center" width="80%"> <tr> <td width="25%"> <s:a href="http://localhost:8080/StudentManage/lookMessage.jsp">查看学生信息</s:a> </td> <td width="25%">添加学生信息</td> <td width="25%"> <s:a href="http://localhost:8080/StudentManage/findMessage.jsp">修改学生信息</s:a> </td> <td width="25%"> <s:a href="http://localhost:8080/StudentManage/deleteMessage.jsp">删除学生信息</s:a> </td> </tr> </table> <br/> <hr color="#99ccff"> <br/><br/><br/> <center><font color="black" size="6">添加学生信息</font></center> </s:div> <s:form action="addMessageAction" method="post"> <table align="center" width="30%" bgcolor="gray" border="5"> <tr> <td> <s:textfield name="id" label="学号" maxLength="16"/> </td> <td> <s:textfield name="name" label="姓名"/> </td> <td> <s:select name="sex" label="性别" list="{‘男‘,‘女‘}"/> </td> <td> <s:textfield name="age" label="年龄"/> </td> <td> <s:textfield name="weight" label="体重"/> </td> <td colspan="2"> <s:submit value="提交"/> <s:reset value="重置"/> </td> </tr> </table> </s:form> </body> </html>
lookMessage.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" import="PO.Student"%> <%@ taglib prefix="s" uri="/struts-tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title><s:text name="学生信息管理系统-查看"></s:text></title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="http://www.mamicode.com/styles.css"> --> </head> <body bgcolor="pink"> <s:div align="center"> <hr color="red"/> <br> <table align="center" width="80%"> <tr> <td width="25%">查看学生信息</td> <td width="25%"> <s:a href="http://localhost:8080/StudentManage/addMessage.jsp">添加学生信息</s:a> </td> <td width="25%"> <s:a href="http://localhost:8080/StudentManage/findMessage.jsp">修改学生信息</s:a> </td> <td width="25%"> <s:a href="http://localhost:8080/StudentManage/deleteMessage.jsp">删除学生信息</s:a> </td> </tr> </table> <br/> <hr color="red"> <br/><br/><br/> <span>你要查询的数据表中共有 <%=request.getSession().getAttribute("count") %>人</span> </s:div> <table align="center" width="80%" border="5"> <tr> <td>记录条数</td> <td>学号</td> <td>姓名</td> <td>性别</td> <td>年龄</td> <td>体重</td> </tr> <% ArrayList list = (ArrayList)session.getAttribute("allInfo"); if(list.isEmpty()) { %> <tr> <td align="center"><span>暂无学生信息!</span></td> </tr> <% } else { for(int i=0;i<list.size();i++) { Student stu = (Student)list.get(i); %> <tr> <td align="center"><%=i+1 %></td> <td><%=stu.getId() %></td> <td><%=stu.getName() %></td> <td><%=stu.getSex() %></td> <td><%=stu.getAge() %></td> <td><%=stu.getSweight() %></td> </tr> <% } } %> </table> </body> </html>
- Controller(控制层):通过struts的拦截器对view层的拦截过滤,实现调用不同的业务处理逻辑。
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-app>
strust.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="default" extends="struts-default"> <action name="lookMessageAction" class="studentAction.LookMessageAction"> <result name="success">lookMessage.jsp</result> <result name="input">/student/index.jsp</result> </action> <action name="addMessageAction" class="studentAction.AddMessageAction"> <result name="success" type="chain">lookMessageAction</result> <result name="input">addMessage.jsp</result> </action> </package> </struts>
lookMessageAction:
package studentAction; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import Dao.StudentDao; import com.opensymphony.xwork2.ActionSupport; public class LookMessageAction extends ActionSupport { private HttpServletRequest request; private String message = "input"; @Override public String execute() throws Exception { request = ServletActionContext.getRequest(); StudentDao dao = new StudentDao(); //实例化 List list = dao.findAllInfo(); //调用StudentDao类中的findAllInfo()方法 request.getSession().setAttribute("count", list.size()); //向session对象传值 request.getSession().setAttribute("allInfo",list); message = "success"; return message; } }
addMessageAction:
package studentAction; import java.util.List; import Dao.StudentDao; import PO.Student; import com.opensymphony.xwork2.ActionSupport; public class AddMessageAction extends ActionSupport { private String id; private String name; private String sex; private int age; private float weight; private String message = "input"; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public float getWeight() { return weight; } public void setWeight(float weight) { this.weight = weight; } public void validate(){ if(this.getId() == null || this.getId().length()==0) { addFieldError("id","学号不允许为空!"); }else { StudentDao dao = new StudentDao(); System.out.println(this.getId()); List list = dao.findInfo("id",this.getId()); if(!list.isEmpty()){ addFieldError("id","学号已存在!"); } } if(this.getName() == null || this.getName().length()==0) { addFieldError("name","姓名不能为空!"); } if(this.getAge()>130) { addFieldError("age","请认真核实年龄!"); } if(this.getAge()>500) { addFieldError("weight","请认真核实体重!"); } } public String execute() throws Exception{ StudentDao dao = new StudentDao(); boolean save = dao.saveInfo(info()); if(save){ message=SUCCESS; } return message; } public Student info(){ Student stu = new Student(); stu.setId(this.getId()); stu.setName(this.getName()); stu.setSex(this.getSex()); stu.setAge(this.getAge()); stu.setSweight(this.getWeight()); return stu; } }
具体的业务流程:
当view层发送一个请求给服务器时,由struts.xml拦截这个请求,根据事先定义好的处理逻辑处理相应的请求。即通过Model层调用不同的业务逻辑实现视图层与逻辑层的分离。拿本例来讲,用户选择添加学生addMessage,由sturts.xml进行拦截,并将解下来的控制交给addMessage.action,由addMessage.action调用StudentDao层的业务逻辑。接着struts.xml获取经过逻辑处理后的结果,根据获取的结果不同选择业务的处理方向。
通过MVC体现的六大基本质量属性:
1.易用性:根据用户进行添加操作的结果返回不同的处理信息
2.可修改性:实现了视图与业务逻辑的分离,方便业务内容的修改与扩展
MVC模式在Java Web应用程序中的实例分析
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。