Java web ----- 第七章MVC模式

目录

前言

7.1  MVC模式介绍

 7.2  JSP中的MVC模式

7.3  模型的生命周期与视图更新 

7.3.1  request bean 

7.3.2  session bean 

7.3.3  application bean

7.4  MVC模式的简单实例

7.4.1  简单计算机器 

7.4.2  表白墙

总结



前言

模型-视图-控制器( Model-View Controller),简称为MVC. MVC已经成为软件设计者必须熟练使用的开发模式。本章必须理解、掌握在JSP程序设计中怎祥具体体现MVC开发模式(其他语言的程序设计是非常类似的,仅仅是具体使用的API不同MVC是一种通过三部分构造一个软件或组件的理想办法。

7.1  MVC模式介绍

 MVC模式主要由三部分构成:
模型(model): 用于存储数据的对象。
●视图(view):向控制器提交所需数据、显示模型中的数据。
●控制器(controller): 负责具体的业务逻辑操作,即控制器根据视图提出的要求对数据做出(商业)处理,将有关结果存储到模型中,并负责让模型和视图进行必要的交互,当模型中的数据变化时,让视图更新显示。
从面向对象的角度看,MVC开发模式可以使程序容易维护,也更容易扩展。在设计程序时,可以将某个对象看作“模型”,然后为“模型”提供恰当的显示组件,即“视图”。在MVC模式中,“视图”“模型”和“控制器”之间是松耦合结构,便于系统的维护和扩展.

 7.2  JSP中的MVC模式

    JSP页面擅长数据的显示,即适合作为用户的视图,例如,JSP页面里可以有HTML标记JavaScript.CSSJava表达式等。本教材侧重JSP本身的重点内容,即服务器端,让JSP页面代码尽量简明,所以没有在JSP页面(客户端)使用JavaScript CSS(熟悉这些内容,可以美化客户端,见2.1节的说明)。在JSP页面中可以使用HTML标记JSP指令(例如getProperty指令)或Java程序片、Java表达式来为用户显示数据,避免使用大量的Java程序片来进行数据的逻辑处理(简明扼要的除外)。servlet 擅长数据的处理,应当尽量避免在servlet中使用out流输出大量的HTML标记来显示数据,否则一旦要修改显示外观就要重新编译servlet。
    通过前面的学习,特别是在学习了第5章后,已经体会到一-些小型的Web应用可以使用JSP页面调用JavaBean完成数据的处理,实现代码复用。在JSP +JavaBean模式中,JavaBean不仅要提供修改和返回数据的方法,而且要经常参与数据的处理。当Web应用变得复杂时,我们希望JavaBean仅仅负责提供修改和返回数据的方法即可,不必参与数据的具体处理,而是把数据的处理交给称作控制器的servlet对象去完成,即servlet控制器负责处理数据,并将有关的结果存储到JavaBean中,实现存储与处理的分离。负责视图功能的JSP页面可以使用Java程序片或用JavaBean标记显示JavaBean中的数据。
JSP中具体实现如下:

  • 模型:JavaBean对象
  • 视图:JSP页面
  • 控制器:Servlet对象

7.3  模型的生命周期与视图更新 

JSP使用useBean格式:

<jsp:useBean id="名字" class = "创建bean的类" scope = "生命周期"/>

 JSP使用Servlet格式:

<jsp:getProperty name="名字" property="bean的属性">

7.3.1  request bean 

1.bean的创建 

BeanClass bean = new  BeanClass();

2.视图更新

Servlet使用RequestDispatcher对象向某个JSP页面发出请求,让所请求的JSP页面显示bean中的数据(不能使用重定向). 

7.3.2  session bean 

1.bean的创建

和上述相同

2.视图更新 

7.3.3  application bean

1.bean的创建

2.视图更新

7.4  MVC模式的简单实例

7.4.1  简单计算机器 

 利用MVC模式构建,具体代码如下:

example7_1_Bean.java

package save.data;
public class Example7_1_Bean { 
   double numberOne,numberTwo,result;
   String operator="+";
   public void setNumberOne(double n){
      numberOne=n;
   }
   public double getNumberOne(){
      return numberOne; 
   }
   public void setNumberTwo(double n){
      numberTwo=n;
   }
   public double getNumberTwo(){
      return numberTwo; 
   }
   public void setOperator(String s){
      operator=s.trim();;
   }
   public String getOperator(){
      return operator;
   }
   public void setResult(double r){
      result=r; 
   }
   public double getResult(){
      return result; 
   }
}

example7_1.jsp

<%@ page contentType="text/html" %>
<%@ page pageEncoding = "utf-8" %>
<jsp:useBean id="digitBean" class ="save.data.Example7_1_Bean" scope="request"/>
<style>
   #tom{
      font-family:宋体;font-size:26;color:blue 
   }
</style>
<HTML><body bgcolor=#ffccff>
<form action="computer" id =tom method=post>
<table>
<tr><td id =tom> 输入两个数:</td>
<td id =tom>
<input type=text name="numberOne" 
       value=<%= digitBean.getNumberOne() %> id =tom size=6/></td>
<td><input type=text name="numberTwo" 
       value=<%=digitBean.getNumberTwo()%> id =tom size=6/></td>
</tr>
<tr><td id =tom>选择运算符号:</td>
<td id =tom>
<select id =tom name="operator">
    <option value="+">+(加)
    <option value="-">-(减)
    <option value="*">*(乘)
    <option value="/">/(除)
</select> 
</td>
<td><input type="submit" id =tom value="提交" name="sub"/></td>
</tr>
</table></form> 
<p id=tom>
运算结果:
<jsp:getProperty name="digitBean" property="numberOne"/>
<jsp:getProperty name="digitBean" property="operator"/>
<jsp:getProperty name="digitBean" property="numberTwo"/> =
<jsp:getProperty name="digitBean" property="result"/> 
</p></body></HTML>

 example7_1_Servlet.java

package handle.data;
import save.data.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Example7_1_Servlet extends HttpServlet{
   public void init(ServletConfig config) throws ServletException{
       super.init(config);
   }
   public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
       Example7_1_Bean digitBean = null;
       digitBean = new Example7_1_Bean();  //创建Javabean对象.
       //digitBean 是request bean:
       request.setAttribute("digitBean",digitBean);
       String str1 = request.getParameter("numberOne");
       String str2 = request.getParameter("numberTwo");
       if(str1==null||str2==null)
         return;
       if(str1.length()==0||str2.length()==0)
         return;
       double numberOne = Double.parseDouble(str1);
       double numberTwo = Double.parseDouble(str2);
       String operator = request.getParameter("operator");
       double result=0;
       if(operator.equals("+"))
           result = numberOne+numberTwo;
       else if(operator.equals("-"))
           result = numberOne-numberTwo;
       else if(operator.equals("*"))
           result = numberOne*numberTwo;
       else if(operator.equals("/"))
           result = numberOne/numberTwo;
       digitBean.setNumberOne(numberOne); //将数据存储在digitBean中 
       digitBean.setNumberTwo(numberTwo);  
       digitBean.setOperator(operator);   
       digitBean.setResult(result); 
       //请求example7_1.jsp显示digitBean中的数据:
       RequestDispatcher dispatcher= request.getRequestDispatcher("example7_1.jsp");
       dispatcher.forward(request,response);
   } 
   public  void  doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
       doPost(request,response);
   }
} 

 结果:

7.4.2  表白墙

exampleWish.java

package save.data;
public class ExpressWish { 
    String contents ;   //表白内容。
    String title;       //标题。
    String dateTime;    //时间。
    String peopleName;  //表白人。
    String id;
    public void setId(String id){
        this.id = id; 
    }
    public String getId(){
        return id;
    }
    public void setPeopleName(String s){
        peopleName = s; 
    }
    public String getPeopleName(){
        return peopleName; 
    }
    public void setContent(String s){
        contents = s; 
    }
    public String getContent(){
        return contents; 
    }
    public void setTitle(String s){
        title = s; 
    }
    public String getTitle(){
        return title; 
    }
    public void setDateTime(String s){
        dateTime = s; 
    }
    public String getDateTime(){
        return dateTime ; 
    }
}

 expressWish_bean.java

package save.data;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Iterator;
public class ExpressWish_Bean { 
    public HashMap<String,ExpressWish> wishList; 
    ArrayList<ExpressWish> wishes;//存放wishList中的表白信息的ArrayList。
    public ExpressWish_Bean(){
        wishList = new HashMap<String,ExpressWish>();
        wishes = new ArrayList<ExpressWish>();
    }
    public void addExpressWish(String id,ExpressWish expressWish){
        wishList.put(id,expressWish);
        putToArrays(wishList);//再把全部表白放到ArrayList wishes。
    }
    public void removeExpressWish(String id){
        wishList.remove(id);
        putToArrays(wishList);
    }
    public String getId(int index) {//返回某个表白者。
       return wishes.get(index).getId();
    }
    public String getPeopleName(int index) {//返回某个表白者。
       return wishes.get(index).getPeopleName();
    }
    public String getTitle(int index){
        return wishes.get(index).getTitle(); 
    }
    public String getContent(int index){
        return wishes.get(index).getContent(); 
    }
    public String getDateTime(int index){
        return wishes.get(index).getDateTime();  
    }
    public int size() {
        return wishes.size();
    }
    void putToArrays(HashMap<String,ExpressWish> list){//把表白放到wishes。
        wishes.clear();
        Iterator<ExpressWish> iterator = list.values().iterator();
        while(iterator.hasNext()){
            ExpressWish wish = iterator.next();
            wishes.add(wish); 
        }
    }
}

ExpressWish_Servlet.java

package handle.data;
import save.data.ExpressWish;
import save.data.ExpressWish_Bean;
import java.util.*;
import java.io.*;
import java.time.LocalDateTime;
import javax.servlet.*;
import javax.servlet.http.*;
public class ExpressWish_Servlet extends HttpServlet{
   int index;  //做id。
   public void init(ServletConfig config) throws ServletException{
       super.init(config);
   }
   synchronized long getIndex() {  //synchronized修饰的方法
       index = index+1;
       return index;
   }
   public void service(HttpServletRequest request,HttpServletResponse response)
                       throws ServletException,IOException{
       request.setCharacterEncoding("utf-8");
       ExpressWish_Bean wishWallBean = null; //wishWallBean存放表白墙内容。
       ServletContext application = getServletContext();
       wishWallBean = (ExpressWish_Bean)application.getAttribute("wishWallBean");
       if(wishWallBean == null ){//wishWallBean不存在就创建wishWallBean。
           wishWallBean = new ExpressWish_Bean();
           application.setAttribute("wishWallBean",wishWallBean);//appication bean。
       }
       String peopleName = request.getParameter("peopleName");//表白者。
       String title = request.getParameter("title"); //标题。
       String content = request.getParameter("contents");//表白内容。
       ExpressWish wish = new ExpressWish();
       if(peopleName.length()==0||title.length()==0||content.length()==0){
            response.sendRedirect("example7_2.jsp");
            return;
       }
       wish.setPeopleName(peopleName);
       wish.setTitle(title);
       wish.setContent(content);                      
       LocalDateTime dateTime = LocalDateTime.now();  
       String str = dateTime.toString();
       String time =str.substring(0,str.lastIndexOf("."));//不要纳秒。
       wish.setDateTime(time);
       long number = getIndex();
       wish.setId(""+number);
       wishWallBean.addExpressWish(""+number,wish);//添加一条表白。
       response.sendRedirect("example7_2_show.jsp"); //显示表白墙。
   }
} 

 example7_2_delete.jsp

<%@ page contentType="text/html" %>
<%@ page pageEncoding = "utf-8" %>
<jsp:useBean id="wishWallBean" class ="save.data.ExpressWish_Bean" scope="application"/>
<HTML><body bgcolor = pink> 
<p style="font-family:宋体;font-size:18;color:blue">
管理员删除表白的页面。
<form action="" method=post >
输入密码:<input type="password" name="password"  size=12 /><br>
输入表白id:<input type="text" name="peopleId" size=6 /> 
<br><input type="submit" name="submit"  value="删除"/>
</form> 
<%  request.setCharacterEncoding("utf-8");
    String password=request.getParameter("password");
    String id=request.getParameter("peopleId");
    if(password == null ) password = "";
    if(id == null ) id = "";
    if(password.equals("123456")){
      wishWallBean.removeExpressWish(id);
    } 
%>
<a href="example7_2_show.jsp">查看表白墙</a>
</p></body></HTML>

结果:
 

 

总结

MVC的核心思想是有效地组合视图,,模型和控制器.在JSP技术中,视图是一个或多个JSP页面,其作用向控制器提交数据和为模型提供数据显示.模型是一个或多个JavaBean对象,用于存储数据.控制器是一个或多个Servlet对象,用于处理数据.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值