前言:为了能够清晰的理解mvc架构,以一个简单的mvc架构web应用为例。例子为一个beer项目,用户可通过页面选择啤酒的种类,服务端根据用户的选择,给出相应的推荐。
涉及到的代码:
view层:form.html 》 用户选择页面
result.jsp 》 服务器返回推荐页面
model层:BeerExpert.java 》 处理用户选择并给出推荐的逻辑处理
control层:BeerSelect.java 》 负责接收view层传入的数据,并将数据交给model层处理,然后将处理结果重定向到result.jsp
web架构:
代码实现:
form.html
<html>
<body>
<h1 align="Center">Beer Selection Page</h1>
<form method="Post"
action="SelectBeer.do">
<p>Select beer charcteristics</p>
Color:
<select name="color" size="1">
<option value="light">light </option>
<option value="amber">amber </option>
<option value="brown">brown </option>
</select>
<br><br>
<center>
<input type="submit">
</center>
</form>
</body>
</html>
result.jsp
<%@ page import="java.util.*" %> <html>
<body>
<h1 align="center">Beer Recommendations JSP</h1> <%
List styles = (List)request.getAttribute("styles");
Iterator it = styles.iterator();
while(it.hasNext()){
out.print("<br>try:: "+it.next());
}
%>
</body>
</html>
web.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app 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"
version="3.0">
<servlet>
<servlet-name>MyBeer</servlet-name>
<servlet-class>com.example.web.BeerSelect</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>MyBeer</servlet-name>
<url-pattern>/SelectBeer.do</url-pattern>
</servlet-mapping> </web-app>
BeerSelect.java
package com.example.web; import com.example.model.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*; public class BeerSelect extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
response.setContentType("text/html");
String c = request.getParameter("color");
//PrintWriter out = response.getWriter();
BeerExpert expert = new BeerExpert();
List ls = expert.getBrands(c);
//Iterator it = ls.iterator();
//while(it.hasNext()){
// out.println("<br> try:"+it.next());
//} //out.println("Beer Selection Advice<br>");
//ot.println("<br> Got beer color"+c);
request.setAttribute("styles",ls);
RequestDispatcher view = request.getRequestDispatcher("result.jsp"); view.forward(request,response);
}
}
BeerExpert.java
package com.example.model; import java.util.*; public class BeerExpert {
public List getBrands(String color){
List<String> brands = new ArrayList<String>();
if(color.equals("amber")) {
brands.add("Jack Amber");
brands.add("Red Moose");
}
else {
brands.add("Jail Pala Ale");
brands.add("Gout Stout");
}
return(brands);
}
}
测试Beer应用: