web初学之MVC

      之前对JavaEEMVC模式有些许了解,但一直没有很好的掌握,在读代码时候也很模糊不清。因此对MVC又通过各种资料有了全面的理解。

一.首先,需要从了解JavaEE技术开始。JavaEE技术在设计程序时,一般会把程序的结构设计成三层。

     ●表示层—用户界面和用于生成界面的代码组成。

     ●中间层—系统的业务和功能代码。

     ●数据层—完成存储数据库的数据和对数据进行封装。

基于这种程序结构,有了MVCM即为数据层,包括各种JavaBean以及数据库工具。V即为表示层,通常为JspHTML页面,显示在客户端。C即为中间层,一般为Web层的Servlet组件,由它来处理客户端的各种请求以及数据。

二.MVC的简单应用:

1)Eclipse中的创建项目,项目名chapter11

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)数据库连接工具JdbcUtil

 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)+"
");
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设计模式以及代码流程。在此还未解决的问题是最后的表示层页面显示,会在此后逐步解决。

原文地址:https://www.cnblogs.com/smithhan/p/5185308.html