前几天在网上看了一篇有关设计模式的文章主要讲的是mvc设计模式的文章,觉得mvc真的叫经典。网上也有人写过类似的文章,个人觉得写的不好,我看了下逻辑乱的不得了,描述也是乱七八糟的,说是代理模式吧又不像,说是工厂设计模式吧他在代码里给你弄个什么反射。看到这样的代码我很想给这位大哥拍砖,这不就是所说的误人子弟吗。所以呢我自己花了一个小时写了个小例子给大家参考一下。下面就一步一步的来作下这个小例子。
1.ADO.NET需要使用到连接字符串,我们先把连接字符串配置到Web.config文件中,如下所示
<appSettings> <!-- 配置连接字符串 --> <add key="SQLConnString" value="Data Source=.\SQLEXPRESS;AttachDbFilename=G:\usemvc\mvc3层架构\usemvc\App_Data\student.mdf;Integrated Security=True;User Instance=True"/> </appSettings>
2.给程序分层
(1)数据访问层
(2)控制器,如ashx
(3)视图层,例如aspx,html
3.开始开发数据访问层
(1)写一个类用来取出配置文件里配置的连接字符串
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; namespace usemvc.Utility { public class ConnectionInfo { //取得web.config里配置的连接字符串 public static string getConnectionString() { //SQLConnString是配置文件里面配置的名称应该保持一致 return ConfigurationSettings.AppSettings["SQLConnString"]; } } }
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; using usemvc.Utility; namespace usemvc.SQLServerDAL { public abstract class SqlHelper { public static readonly string CONN_STR = ConnectionInfo.getConnectionString(); public static SqlDataReader ExecuteReader(string connString, CommandType cmdType, string cmdText, params SqlParameter[] cmdParms) { SqlCommand cmd = new SqlCommand(); SqlConnection conn = new SqlConnection(connString); // 我们在这里用 try/catch 是因为如果这个方法抛出异常,我们目的是关闭数据库连接,再抛出异常, // 因为这时不会有DataReader存在,此后commandBehaviour.CloseConnection将不会工作。 try { PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms); SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return rdr; } catch { conn.Close(); throw; } } private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms) { if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; if (trans != null) cmd.Transaction = trans; cmd.CommandType = cmdType; if (cmdParms != null) { foreach (SqlParameter parm in cmdParms) cmd.Parameters.Add(parm); } } } }(3)编写pojo类
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; namespace usemvc.Model { public class StudentInfo { private int id; private String userName; public String UserName { get { return userName; } set { userName = value; } } private String password; public String Password { get { return password; } set { password = value; } } public int Id { get { return id; } set { id = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using usemvc.Model; namespace usemvc.IDAL { public interface IStudentDao { //通过ID取得用户信息 StudentInfo getStudentInfoByID(int id); //判断数据库是否存在该用户 int getUserCount(string username,string password); } }
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using usemvc.IDAL; using usemvc.Model; using System.Data.SqlClient; namespace usemvc.SQLServerDAL { public class StudentImpl:IStudentDao { //查询用户是否存在 public int getUserCount(string username, string password) { int temp=0; string sql = "select count(username) from m_student where username=@username and password=@password"; //创建一个参数 SqlParameter[] parm = new SqlParameter[] { new SqlParameter("@username",username), new SqlParameter("@password",password) }; using (SqlDataReader sdr = SqlHelper.ExecuteReader(SqlHelper.CONN_STR, CommandType.Text,sql, parm)) { if (sdr.Read()) { temp = sdr.GetInt32(0); } } return temp; } public StudentInfo getStudentInfoByID(int id) { string PARM_ID = "@ID"; string SQL_SELECT_CONTENT = "Select username,password From m_student Where id = @ID"; //用户登录的处理 //创意文章内容类 StudentInfo stu = null; //创建一个参数 SqlParameter parm = new SqlParameter(PARM_ID, SqlDbType.Int, 8); //赋上ID值 parm.Value = id; using (SqlDataReader sdr = SqlHelper.ExecuteReader(SqlHelper.CONN_STR, CommandType.Text, SQL_SELECT_CONTENT, parm)) { if (sdr.Read()) { stu = new StudentInfo(); stu.Password = sdr.GetString(1); stu.UserName = sdr.GetString(0); } } return stu; } } }
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using usemvc.IDAL; using usemvc.Model; using usemvc.DALFactory; namespace usemvc.SQLServerDAL { public class StudentDaoProxy:IStudentDao { private IStudentDao dao; //构造方法实例化dao对象 public StudentDaoProxy() { this.dao = new StudentImpl(); } public StudentInfo getStudentInfoByID(int id) { //调用真实主题操作 return this.dao.getStudentInfoByID(id); } public int getUserCount(string username,string password) { //调用真实主题操作 return this.dao.getUserCount(username,password); } } }
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Reflection; using usemvc.SQLServerDAL; using usemvc.IDAL; namespace usemvc.DALFactory { public class StudentDaoFactory { //取得Dao接口实例 public static IStudentDao getIStudentDaoInstance() { //取得代理操作类StudentDaoProxy实例 return new StudentDaoProxy(); } } }
4.开发控制器层,这里我用ashx来处理
using System; using System.Collections; using System.Data; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Linq; using System.Web.SessionState; using usemvc.DALFactory; namespace usemvc.ashx { /// <summary> /// $codebehindclassname$ 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class CheckLogin : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string username=context.Request["username"]; string password= context.Request["password"]; int temp=StudentDaoFactory.getIStudentDaoInstance().getUserCount(username,password); //下面是业务逻辑 //如果数据库存在该用户 if(temp==1){ //下面是程序的处理逻辑,我就不写了 //跳转或者数据处理 } } public bool IsReusable { get { return false; } } } }
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="usemvc.login" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#login").click(function(){ var username=$("#username").val(); var password=$("#password").val(); $.ajax({ type:"POST", url:"ashx/CheckLogin.ashx", data:"username="+username+"&password="+password, success: function() { //这里只是一个简单的实例,在这里可以在ashx生成xml 在这里可以先解析再做判断 //之后处理自己的业务逻辑 window.location="Default.aspx" } }); }); }); </script> <title>用户登录</title> </head> <body> 用户名:<input type="text" id="username"/><br /> 密码:<input type="password" id="password"/><br /> <input type="button" id="login" value="登录"/> </body> </html>
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using usemvc.SQLServerDAL; using usemvc.Model; using usemvc.DALFactory; namespace usemvc { public partial class _Default : System.Web.UI.Page { StudentInfo ci; protected void Page_Load(object sender, EventArgs e) { //protected System.Web.UI.WebControls.Label username; // protected System.Web.UI.WebControls.Label lblDataTime; this.GetContent(1); //this.GetCount(); } private void GetCount() { int a = StudentDaoFactory.getIStudentDaoInstance().getUserCount("chenruiyin","123456"); this.Response.Write(a); } private void GetContent(int id) { ci = StudentDaoFactory.getIStudentDaoInstance().getStudentInfoByID(1); this.Response.Write("<table border='1' width='500' id='tab'>"); this.Response.Write("<tr>"); this.Response.Write("<td>"+"用户名"+"</td>"); this.Response.Write("<td>" + "密码" + "</td>"); this.Response.Write("</tr>"); this.Response.Write("<tr>"); if (ci != null) { this.Response.Write("<td>"+ci.UserName+"</td>"); this.Response.Write("<td>" + ci.Password + "</td>"); //username.Text = ci.UserName; } this.Response.Write("<tr>"); this.Response.Write("</table>"); } } }