首页 > 代码库 > 用户管理系统网站框架改进之MVC模式

用户管理系统网站框架改进之MVC模式

从之前的用户管理系统中我们会发现,JSP主要是做界面的,但却用了JSP来对用户进行验证和分页处理,而Servlet处理页面的转跳是最快捷和最方便的,所以对用户管理系统的框架进行了改进,使用MVC模式。

MVC是一种设计模式,它强制性的使应用程序的输入、处理和输出分开。使用MVC应用程序被分为三个核心部件:模型、视图和控制器。它们各自处理自己的任务。

MVC的各个字母分别是M(model模型)、V(view视图)和C(controller控制器)

M主要由Java class来处理,也可以是Java bean,ejb等

V由JSP来处理
C由Servlet来处理

MVC模式简单的框架图如下所示:

技术分享

经过对问题的分析,我们可以对程序进行改进:
增加控制器,将loginCl.jsp用Servlet来替代,并在控制器中去调用模型完成用户的验证,发挥Servlet在控制中的优势,可以改进为如下的框架:

技术分享

实现代码如下:

视图部分:

1.登录界面(login.jsp)

<%@ page language="java" contentType="text/html; charset=gb2312"
    pageEncoding="gb2312"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>用户登录系统</title>
</head>
<body>
<center>
用户登录系统<br>
<hr>
<form action="LoginClServlet" method="post">
用户名:<input type="text" name="username"><br>
密  码:<input type="password" name="passwd"><br>
<input type="submit" value="http://www.mamicode.com/login">
<input type="reset" value="http://www.mamicode.com/重置">
</form>
<hr>
</center>
</body>
</html>

 

2.欢迎页面(wel.jsp)
<%@ page language="java" contentType="text/html; charset=gb2312" import="java.sql.*,java.util.*,com.chongqing.model.*"
    pageEncoding="gb2312"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>欢迎页面</title>
</head>
<body>
<center>
welcome,<%= request.getParameter("user") %><br>
<a href="http://www.mamicode.com/login.jsp">返回重新登录</a>
<hr>
<%
	//分页的功能 	
	//从request中取出pageNow的值
	int pageNow = Integer.parseInt((String)request.getAttribute("pageNow"));

	//取出al的值
    ArrayList<Object> al = (ArrayList<Object>)request.getAttribute("result");
   
    //用表格显示用户的信息
    %>
    <table border="1">
    <tr><td>用户ID</td><td>用户名</td><td>密码</td><td>邮箱</td><td>等级</td></tr> 
    <%
	for(int i=0; i<al.size(); ++i)
    {
		UserBean ub = (UserBean)al.get(i);
		out.println("<tr>");  
        out.println("<td>"+ub.getUserId()+"</td>");  
        out.println("<td>"+ub.getUserName()+"</td>");  
        out.println("<td>"+ub.getPasswd()+"</td>");  
        out.println("<td>"+ub.getMail()+"</td>");  
        out.println("<td>"+ub.getGrade()+"</td>");  
        out.println("</tr>"); 	
    }   
    %>   
    </table>
    <%
	//显示超链接
	if(1 != pageNow)
	{
        out.println("<a href=http://www.mamicode.com/UserClServlet?s_pageNow=1>[首页]"); 	
        out.println("<a href=http://www.mamicode.com/UserClServlet?s_pageNow="+(pageNow-1)+">[上一页]</a>"); 	

	}
	
    //取出pageCount的值
    int pageCount = Integer.parseInt((String)request.getAttribute("pageCount"));
	for(int i=1; i<=pageCount; ++i){		
        out.println("<a href=http://www.mamicode.com/UserClServlet?s_pageNow="+i+">["+i+"]</a>"); 	
	}
	
	if(pageCount != pageNow)
	{
        out.println("<a href=http://www.mamicode.com/UserClServlet?s_pageNow=1>[下一页]"); 	
        out.println("<a href=http://www.mamicode.com/UserClServlet?s_pageNow="+(pageNow+1)+">[尾页]</a>"); 	
	}
%>
</center>
</body>
</html>

 

模型部分:

1.ConnDB.java

//连接到数据库

package com.chongqing.model;

import java.sql.*;  

public class ConnDB {
	 private Connection ct = null;  
     
	  public Connection getConn(){        
	  try {  
		     	
	    //连接到数据库  
	    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");  
	    ct = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;DatabaseName=TestServlet","sa","123456");   
		}  
		catch (Exception ex) {  
		    ex.printStackTrace();  
		}           
		//不用关闭资源  
	  
	return ct;  
	 }  

}

 

2.UserBean.java

// 映射到数据库中的users表,它的一个对象与users表的一条记录相对应,操作UserBean就相当于操作数据库 
package com.chongqing.model;

public class UserBean {
	private int userId;  
    private String userName;  
    private String passwd;  
    private String mail;  
    private int grade;
    
	public int getUserId() {
		return userId;
	}
	public String getUserName() {
		return userName;
	}
	public String getPasswd() {
		return passwd;
	}
	public String getMail() {
		return mail;
	}
	public int getGrade() {
		return grade;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	public void setMail(String mail) {
		this.mail = mail;
	}
	public void setGrade(int grade) {
		this.grade = grade;
	}  
    
    

}

 
3.UserBeanCl.java

//业务逻辑和处理类,用来处理users表,即操作UserBean
package com.chongqing.model;

import java.sql.*;  
import java.util.*;

public class UserBeanCl {
	
	private Connection ct = null;    
    private PreparedStatement ps = null;    
    private ResultSet rs = null;  
    private int pageCount = 0; //一共有多少页(通过计算获得)  
    private int pageSize = 3;   //每页显示3条记录 
      
    //验证用户  
    public boolean checkUser(String u,String p){  
        boolean flag = false;  
          
        try {  
            //得到连接  
            ConnDB cd = new ConnDB();  
            ct = cd.getConn();  
              
            ps = ct.prepareStatement("select * from users where username = ? and passwd = ?");    
            ps.setString(1,u);  
            ps.setString(2,p);  
            rs = ps.executeQuery();      
              
            if(rs.next()){  
                flag = true;  
            }  
      
        }  
        catch (Exception ex) {  
            ex.printStackTrace();  
        }  
        finally {  
            this.close();  
        }  
          
        return flag;  
          
    }  
      
      
    //分页显示结果  
    //不能返回ResultSet,因为关闭数据库资源的时候ResultSet也将消失,这里是返回ArrayList  
    public ArrayList<Object> getResultByPage(int pageNow){  
          
        ArrayList<Object> al = new ArrayList<Object>();  
          
        try {  
            int rowCount = 0;  //一共有多少行记录(通过查表获得)  
                       
            //连接数据库  
            ConnDB cd = new ConnDB();  
            ct = cd.getConn();   
            ps = ct.prepareStatement("select count(*) from users");   
            rs = ps.executeQuery();      
              
            if(rs.next()){  
                rowCount = rs.getInt(1);//获得rowCount的值  
            }  
              
            //计算pageCount的值  
            if(rowCount%pageSize == 0){    
                pageCount = rowCount/pageSize;    
            }else{    
                pageCount = rowCount/pageSize + 1;    
            }    
                  
            ps = ct.prepareStatement("select top "+pageSize+" *  from users where userID not in (select top "+pageSize*(pageNow-1)+" userID from users)");  
            rs = ps.executeQuery();   
                  
            while(rs.next()){  
                  
                //将rs中的每条记录封装到UserBean ub中  
                UserBean ub = new UserBean();  
                  
                ub.setUserId(rs.getInt(1));  
                ub.setUserName(rs.getString(2));  
                ub.setPasswd(rs.getString(3));  
                ub.setMail(rs.getString(4));  
                ub.setGrade(rs.getInt(5));  
                  
                al.add(ub);  //将ub添加到ArrayList中  
                  
            }  
        }  
        catch (Exception ex) {  
            ex.printStackTrace();  
        }  
        finally {  
            this.close();  
        }  
      
        return al;  
    }  
      
    //返回pageCount  
    public int getPageCount(){  
          
        return this.pageCount;  
    }  
      
    //关闭资源  
    public void close(){  
        try {    
                if(null != rs){    
                    rs.close();    
                    rs = null;  
                }    
                if(null != ps){    
                    ps.close();    
                    ps = null;  
                }    
                if(null != ct){    
                    ct.close();    
                    ct = null;  
                }    
            } catch (SQLException e) {    
                e.printStackTrace();    
            }    
          
    }  

}

 
控制器模块:

1.验证用户

//这是控制器,主要完成对用户身份的验证
//控制器本身是不会去完成业务逻辑,它主要是通过调用模型来完成数据的处理

package com.chongqing.controller;

import java.io.IOException;
import java.util.ArrayList;

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.chongqing.model.UserBeanCl;

@WebServlet("/LoginClServlet")
public class LoginClServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//接收用户名和密码,完成对用户的验证
		String u = request.getParameter("username");
		String p = request.getParameter("passwd");

		//到数据库中进行验证
	    UserBeanCl ubc = new UserBeanCl();
	    if(ubc.checkUser(u,p)){
	    	
	    	//合法,转到欢迎页面
	    	//在转跳到wel.jsp页面时,就把要显示的数据给wel.jsp准备好
	    	ArrayList<Object> al = (ArrayList<Object>)ubc.getResultByPage(1);
	    	int pageCount = ubc.getPageCount();
	    	
	    	request.setAttribute("result", al);
	    	request.setAttribute("pageCount", pageCount+"");
	    	request.setAttribute("pageNow", "1");
	    	
	    	//response.sendRedirect("wel.jsp?user="+u);   
	    		    	
	    	//因为sendRedirect方法效率不高,所以软件公司常常是使用转发方法
	    	//这种方法效率高,同时request的对象在下一个页面还可以使用
	    	request.getRequestDispatcher("wel.jsp").forward(request, response);
	    	
	    }else{
	    	
	    	//不合法,转到登录页面
	    	request.getRequestDispatcher("login.jsp").forward(request, response);
	    }
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		this.doGet(request, response);
	}

}

 

2.分页功能

//这个是控制器,将进行分页处理

package com.chongqing.controller;

import java.io.IOException;
import java.util.ArrayList;

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.chongqing.model.UserBeanCl;

@WebServlet("/UserClServlet")
public class UserClServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		int pageNow = Integer.parseInt(request.getParameter("s_pageNow"));

	    UserBeanCl ubc = new UserBeanCl();
    	ArrayList<Object> al = (ArrayList<Object>)ubc.getResultByPage(pageNow);
    	int pageCount = ubc.getPageCount();
    	
    	request.setAttribute("result", al);
    	request.setAttribute("pageCount", pageCount+"");
    	request.setAttribute("pageNow", pageNow+"");
    	
    	request.getRequestDispatcher("wel.jsp").forward(request, response);

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}

 




 

用户管理系统网站框架改进之MVC模式