/*--------------这个html就是View-------------------------*/
<html> ... <!-- 省略不必要的部分 --> ... <Form method=post action= "/Book/Broker "> <!-- 问题 1 --> <table> <tr> <td> Enter ticker: </td> <td> <input type=text length=5 name= "ticker "> </td> </tr> <tr> <td> Number of shares: </td> <td> <input type=text length=5 name= "numShares "> </td> </tr> <tr> <td> Share Price: </td> <td> <input type=text length=5 name= "price "> </td> </tr> </table> <hr> <table border=1> <tr> <td> <input type=hidden name= "Buy " value= "/jsp/Buy.jsp "> <input type=submit name= "action " value= "Buy "> </td> <!-- 注意 --> <td> <input type=hidden name= "Sell " value= "/jsp/Sell.jsp "> <input type=submit name= "action " value= "Sell "> </td> <!-- 注意 --> <td> <input type=hidden name= "Cancel " value= "/jsp/Cancel.jsp "> <input type=submit name= "action " value= "Cancel "> </td> <!-- 注意 --> <td> <input type=reset value= "reset "> </td> .... <!-- 省略不必要的部分 --> .... <!-- 注意该例子三个提交按钮“Buy”,“Sell”,“Cancel”都用同一个名字“action” ----------------------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------------------
/*---------
这个可以看成是controller
-----------*/
package simple; ... ... //和第一个例子相同,引入servlet包,这里省略 public calss BrokerServlet extends HttpServlet { private static final String MAPPINGS_FILE= "/WEB-INF/config.properties ";
private Properties properties=new Properties(); public void init(ServletConfig config) throws ServletException { super.init(config); try{ properties.load(config.getServletContext().getResourceAsStream(MAPPINGS_FILE)); } catch(IOExcetion ioexp){ .... } public void doPost(HttpServletRequest request,HttpServetResponse response) throws ServletException,IOException { RequestDispatcher rd = null; String action = request.getParameter( "action "); String nextURL = properties.getProperty(action); if(nextURL!=null){ rd = request.getRequestDispatcher(nextURL); rd.forward(request,response); } } } 下面是属性文件 # Mapping of actions to destinations Buy=/jsp/Buy.jsp Sell=/jsp/Sell.jsp Cancel=/jsp/Cancel.jsp
粗剖析:1,html 文件即 V(view),是客户端交互可见的界面,当用户有动作(点击按钮),就提交form
2,服务器程序BrokerServlet 就是c(controller),接收html(view)的请求,并且将请求和Model(config)联系;
将从Model获得的数据(config文件中的那些文件名)提交给view(客户端浏览器)显示相应的页面。
3,config文件就是所谓的M(model)
细剖析:
本实例的最大好处可以看到,首先充分分离了V - C - M ;客户端只要提交请求就行而且重要的是他在界面的几个按钮都用name =“action”,这样在服务器端就可以统一处理了;而服务器端接收请求,加载config文件(Model),动态根据用户请求的信息来确定要返回给客户端的页面 rd.forward(request,response);
也就是说 如果客户端html页面如果再加一个按钮 name="action",然后在直接在配置文件里面加一条响应该按钮点击的响应页面就OK了 ,而 服务器端代码可以纹丝不动。
