web初學之MVC

      以前對JavaEEMVC模式有些許瞭解,但一直沒有很好的掌握,在讀代碼時候也很模糊不清。所以對MVC又經過各類資料有了全面的理解。java

一.首先,須要從瞭解JavaEE技術開始。JavaEE技術在設計程序時,通常會把程序的結構設計成三層。mysql

     ●表示層—用戶界面和用於生成界面的代碼組成。sql

     ●中間層—系統的業務和功能代碼。數據庫

     ●數據層—完成存儲數據庫的數據和對數據進行封裝。設計模式

基於這種程序結構,有了MVCM即爲數據層,包括各類JavaBean以及數據庫工具。V即爲表示層,一般爲JspHTML頁面,顯示在客戶端。C即爲中間層,通常爲Web層的Servlet組件,由它來處理客戶端的各類請求以及數據。app

二.MVC的簡單應用:jsp

1)Eclipse中的建立項目,項目名chapter11ide

2)模型實體Student工具

 1 package com.chapter11.bean;
 2 
 3 import java.sql.Date;
 4 
 5 public class Student {
 6     private int id;
 7     private String name;
 8     private Date birthday;
 9     public int getId() {
10         return id;
11     }
12     public void setId(int id) {
13         this.id = id;
14     }
15     public String getName() {
16         return name;
17     }
18     public void setName(String name) {
19         this.name = name;
20     }
21     public Date getBirthday() {
22         return birthday;
23     }
24     public void setBirthday(Date birthday) {
25         this.birthday = birthday;
26     }
27     
28 
29 }
JavaBean

3)數據庫鏈接工具JdbcUtilthis

 1 package com.chapter11.util;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.ResultSet;
 6 import java.sql.Statement;
 7 
 8 public class JdbcUtil {
 9     static{
10         try{
11             Class.forName("com.mysql.jdbc.driver");
12         }catch(Exception e)
13         {
14             e.printStackTrace();
15         }
16     }
17     public static Connection getConnection()
18     {
19         Connection con=null;
20         try{
21             con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sms","root","hanzhao1024");
22         }catch(Exception e){
23             e.printStackTrace();
24         }
25         return con;
26     }
27 
28     public static void release(Connection con,Statement stmt,ResultSet rs)
29     {
30         try{
31             if(rs!=null)
32             {
33              rs.close();
34             }
35             
36         }catch(Exception e)
37         {
38             e.printStackTrace();
39             }
40         try{
41             if(stmt!=null)
42             {
43              stmt.close();
44             }
45             
46         }catch(Exception e)
47         {
48             e.printStackTrace();
49             }
50         try{
51             if(con!=null)
52             {
53              con.close();
54             }
55             
56         }catch(Exception e)
57         {
58             e.printStackTrace();
59             }
60         
61     }
62     public static void printRs(ResultSet rs)
63     {
64         StringBuffer sb=new StringBuffer();
65         try{
66             while(rs.next())
67             {
68                 sb.append("id="+rs.getInt(1)+"");
69                 sb.append("name="+rs.getString(2)+"\n");
70             }
71             System.out.println(sb.toString());
72             
73         }catch(Exception e)
74         {
75             e.printStackTrace();
76         }
77         
78     }
79 
80 }
JdbcUtil

4)數據訪問層接口StudentDao

 1 package com.chapter11.dao;
 2 
 3 import java.sql.SQLException;
 4 import java.util.List;
 5 import java.sql.SQLException;
 6 
 7 import com.chapter11.bean.Student;
 8 
 9 public interface StudentDao {
10     public void insertStudent(Student stu)throws SQLException;
11     public List queryAllStudents()throws SQLException;
12     
13 
14 }
StudentDao

5)數據訪問層接口實現類StudentDaoImpl

 1 package com.chapter11.dao;
 2 
 3 import java.sql.Connection;
 4 import java.sql.PreparedStatement;
 5 import java.sql.ResultSet;
 6 import java.sql.SQLException;
 7 import java.util.ArrayList;
 8 import java.util.List;
 9 import com.chapter11.bean.Student;
10 import com.chapter11.util.JdbcUtil;
11 
12 public class StudentDaoImpl implements StudentDao {
13 
14     Connection con=null;
15     public StudentDaoImpl(Connection con)
16     {
17         this.con=con;
18     }
19     PreparedStatement pstmt=null;
20     ResultSet rs=null;
21     public void insertStudent(Student stu)throws SQLException
22     {
23         String sql="insert into student(name,birthday) value(?,?)";
24         pstmt=con.prepareStatement(sql);
25         pstmt.setString(1, stu.getName());
26         pstmt.setDate(2, stu.getBirthday());
27         pstmt.executeUpdate();
28         JdbcUtil.release(null, pstmt, null);
29     }
30     public List queryAllStudents()throws SQLException
31     {
32         String sql="select*from student";
33         List students=new ArrayList();
34         pstmt=con.prepareStatement(sql);
35         ResultSet rs=pstmt.executeQuery();
36         while(rs.next())
37         {
38             Student stu=new Student();
39             stu.setId(rs.getInt("id"));
40             stu.setName(rs.getString("name"));
41             stu.setBirthday(rs.getDate("birthday"));
42             students.add(stu);
43         }
44         JdbcUtil.release(null, pstmt, null);
45         return students;
46     }
47     
48 }
StudentDaoImpl

6)增長和刪除的業務服務層接口StudentService

package com.chapter11.service;

import java.sql.SQLException;
import java.util.List;

import com.chapter11.bean.Student;

public interface StudentService {
    public void addStudent(Student stu)throws SQLException;
    public List findAllStudent()throws SQLException;

}
StudentService

7)增長和刪除的業務服務層接口StudentServiceImpl

 1 package com.chapter11.service;
 2 
 3 import java.sql.Connection;
 4 import java.sql.SQLException;
 5 import java.util.List; 
 6 
 7 import com.chapter11.bean.Student;
 8 import com.chapter11.dao.StudentDao;
 9 import com.chapter11.dao.StudentDaoImpl;
10 import com.chapter11.util.JdbcUtil;
11 
12 public class StudentServiceImpl implements StudentService{
13     public void addStudent(Student stu)throws SQLException
14     {
15         Connection con=JdbcUtil.getConnection();
16         try{
17             con.setAutoCommit(false);
18             StudentDao sdao=new StudentDaoImpl(con);
19             sdao.insertStudent(stu);
20             con.commit();
21             
22         }catch(Exception e)
23         {
24             e.printStackTrace();
25         }
26         
27 
28         
29     }
30     public List findAllStudent()throws SQLException
31     
32     {
33         Connection con=JdbcUtil.getConnection();
34         List students=null;
35         try{
36             con.setAutoCommit(false);
37             StudentDao sdao=new StudentDaoImpl(con);
38             sdao.queryAllStudents();
39             con.commit();
40             
41         }catch(Exception e)
42         {
43             e.printStackTrace();
44         }
45         
46         return students;
47     }
48 
49 }
StudentServiceImpl

8)Web層控制器Servlet

package com.chapter11.servlet;

import java.io.IOException;
import java.sql.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.chapter11.bean.Student;
import com.chapter11.service.*;


@WebServlet("/SMSServletController")
public class SMSServletController extends HttpServlet {
    private static final long serialVersionUID = 1L;
  
    public SMSServletController() {
        super();
      
    }
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request, response);
    }

    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        StudentService ss=new StudentServiceImpl();
        String path=request.getServletPath();
        path=path.substring(0,path.indexOf("."));
        if(path.equalsIgnoreCase("/sms/list"))
        {
            try
            {
                List students=ss.findAllStudent();
                request.setAttribute("students", students);
                forward("list.jsp",request,response);
                
                        
            }catch(Exception e)
            {
                throw new ServletException("error when query!");
            }
        }else if(path.equalsIgnoreCase("/sms/add"))
        {
            request.setCharacterEncoding("UTF-8");
            String name=request.getParameter("name");
            String birthday=request.getParameter("birthday");
            Student student=new Student();
            student.setBirthday(Date.valueOf(birthday));
            student.setName(name);
            try{
                ss.addStudent(student);
                
                }catch(Exception e)
                {
                    e.printStackTrace();
                }
            response.sendRedirect(request.getContextPath()+"/sms/list.do");
            }
            
        }

    private void forward(String url, HttpServletRequest request,
            HttpServletResponse response)throws IOException,ServletException{
        ServletContext application=getServletContext();
        RequestDispatcher ds=application.getRequestDispatcher(url);
        ds.forward(request,response);
    
        
    }

}
Servlet

9)Web層表示頁面

整個過程即爲一個基本的MVC設計模式以及代碼流程。在此還未解決的問題是最後的表示層頁面顯示,會在此後逐步解決。

相關文章
相關標籤/搜索