請給出一個mvc模式編程的實例,最簡單的HelloWord

馬克-to-win:下面我們先給出一個最簡單的mvc例子。這是一個常見的購物車的例子。在下面的例子當中,作為View的add.jsp提交給作為Controller的 ServletHello1.java來處理。真正的處理過程交給了作為Model的Cart.java來處理。作為Controller的 ServletHello1.java,用response.sendRedirect("add.jsp");這句話,最后控制流程跳轉(zhuǎn)到 add.jsp。馬克- to-win:馬克 java社區(qū):防盜版實名手機尾號: 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>購物車內(nèi)容</b>
            </caption>
            <tr>
                <th>書名</th>
                <th>價格</th>
                <th>數(shù)量</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模式下訪問數(shù)據(jù)庫

下面的例子給出在mvc模式下如何訪問數(shù)據(jù)庫。





例1.2.1:

<%@ page contentType="text/html; charset=GBK" %>
<html>
<body>
<center><h3>學生登記系統(tǒng)(for 教務(wù)處)</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無關(guān)*/          
            new DatabaseConn();
        }
        Connection con = null;
        con = ds.getConnection();
        return con;
    }
}