请给出一个mvc模式编程的实例,最简单的HelloWord

马克-to-win:下面我们先给出一个最简单的mvc例子。这是一个常见的购物车的例子。在下面的例子当中,作为View的add.jsp提交给作为Controller的 ServletHello1.java来处理。真正的处理过程交给了作为Model的Cart.java来处理。作为Controller的 ServletHello1.java,用response.sendRedirect("add.jsp");这句话,最后控制流程跳转到 add.jsp。马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。



例1.1.1:

add.jsp:

<%@ page contentType="text/html; charset=GBK" %>
<html>
<body>
<hr>
<center><h3>书目</h3></center>
<table border="1" width="300" cellspacing="0" cellpadding="3" align="center">
<tr><th>书名</th><th>价格</th></tr>
<tr>
<form action="MarkToWinServlet" method="post">
<td>Java自学</td>
<td>25</td>
<td><input type="submit" name="Submit" value="Add"></td>
<input type="hidden" name="id" value="1">
<input type="hidden" name="title" value="Java自学">
<input type="hidden" name="price" value="25">
</form>
</tr>
<tr>
<form action="MarkToWinServlet" method="post">
<td>C++精通</td>
<td>28</td>
<td><input type="submit" name="Submit" value="Add"></td>
<input type="hidden" name="id" value="2">
<input type="hidden" name="title" value="C++精通">
<input type="hidden" name="price" value="28">
</form>
</tr>
</table>
<a href="cart.jsp">看看购物车</a>
</body>
</html>






package com;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ServletHello1 extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        Cart cart=(Cart)session.getAttribute("cart");
        if(cart==null )  cart = new Cart();
        request.setCharacterEncoding("GBK");
        String id = request.getParameter("id");
        String title = request.getParameter("title");
        String price = request.getParameter("price");
        cart.addItem(id, title, price);
        session.setAttribute("cart", cart);
        response.sendRedirect("add.jsp");
    }
}





package com;
import java.util.Enumeration;
import java.util.Hashtable;
public class Cart {
    protected Hashtable items = new Hashtable();
    public void addItem(String itemId, String title, String price) {
        String[] item = { itemId, title, price, "1" };
        if (items.containsKey(itemId)) {
            /* after the next statement,tmpItem is a reference pointing to the
             * thing in Hashtable,if you change the thing tmpItem points to, you
             * change the thing itself.*/
            String[] tmpItem = (String[]) items.get(itemId);
            int tmpQuant = Integer.parseInt(tmpItem[3]);
            System.out.println("before is " + tmpItem[3]);
            tmpQuant++;
            tmpItem[3] = Integer.toString(tmpQuant);
            String[] tmpItem1 = (String[]) items.get(itemId);
            System.out.println("after is " + tmpItem1[3]+tmpItem1[1]);

        } else {
            items.put(itemId, item);
        }
    }
    public Enumeration getEnumeration() {
        return items.elements();
    }
}


cart.jsp:


<%@ page contentType="text/html; charset=GBK"%>
<%@ page import="java.util.*"%>
<jsp:useBean id="cart" class="com.Cart" scope="session" />
<html>
<body>
    <center>
        <table width="300" border="1" cellspacing="0" cellpadding="3"
            border="0">
            <caption>
                <b>购物车内容</b>
            </caption>
            <tr>
                <th>书名</th>
                <th>价格</th>
                <th>数量</th>
            </tr>
            <%
                Enumeration enu = cart.getEnumeration();
                String[] tmpItem;
                while (enu.hasMoreElements()) {
                    tmpItem = (String[]) enu.nextElement();
            %>
            <tr>
                <td align="center"><%=tmpItem[1]%></td>
                <td align="center">$<%=tmpItem[2]%></td>
                <td align="center"><%=tmpItem[3]%></td>
            </tr>
            <%
                }
            %>
        </table>
    </center>
    <a href="add.jsp">接着买</a>
</body>
</html>



MVC模式下访问数据库

下面的例子给出在mvc模式下如何访问数据库。





例1.2.1:

<%@ page contentType="text/html; charset=GBK" %>
<html>
<body>
<center><h3>学生登记系统(for 教务处)</h3></center>
<form action="MarkToWinServlet" method="post">
姓名<INPUT TYPE="TEXT" NAME="name">
年龄<INPUT TYPE="TEXT" NAME="age">
<input type="submit" name="Submit" value="提交">
</form>
</body>
</html>


package com;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletHello1 extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("GBK");
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        MyBean mb=new MyBean();
        try {
            mb.register(name,age);
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.sendRedirect("add.jsp");
    }
}



package com;
import java.sql.*;
public class MyBean {
    public synchronized void register(String name, String age) throws Exception {
        Connection con;
/*MysqlConnectionPoolDataSource ds is always in the memory once it is
         * created becasue it is static.. */
        con = DatabaseConn.getConnection();
        Statement stmt = con.createStatement();
/*即使表为空,rs.getInt(1)返回值为0,我们的程序逻辑也对*/       
        ResultSet rs = stmt.executeQuery("select max(id) from register");
        rs.next();
        System.out.println(rs.getInt(1));
        int id;
        id=rs.getInt(1);id++;   
        String insertString="insert into register Values("+id+",\""+name+"\","+Integer.valueOf(age)+")";
        System.out.println(insertString);
        stmt.executeUpdate(insertString);
        stmt.close();
        con.close();
    }
}




package com;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import java.sql.*;
import javax.sql.*;
public class DatabaseConn {
    static private MysqlConnectionPoolDataSource ds;
    private Connection con;
    private DatabaseConn() {
        ds = new MysqlConnectionPoolDataSource();
        ds.setURL("jdbc:mysql://localhost:3306/test");
        ds.setUser("root");
        ds.setPassword("1234");
    }
    public static Connection getConnection() throws Exception {
        if (ds == null) {
/*DatabaseConn的目的是让ds有值,和con无关*/          
            new DatabaseConn();
        }
        Connection con = null;
        con = ds.getConnection();
        return con;
    }
}