博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
谈mvc
阅读量:2379 次
发布时间:2019-05-10

本文共 6679 字,大约阅读时间需要 22 分钟。

 

   首先稍微解释一下MVC的含义,M(model),是指数据模型,这就和数据库有关了。V(view),是指视图,通俗讲应该就是网页界面,C(control)就是实现MV之间的消息的沟通。

网站重要的两个部分就是数据库和界面,我们又通常称之为前台和后台,显然这两个有着密切的关系,但最好把这两个分离开来,或者说,把它们之间的千丝万缕的,隐隐约约的关系,搞的更清晰一些。有一个角色用来单独处理他们之间的关系比较好。这个就是C(control)。于是MVC结构应运而生了。

   下面详细谈一下,自己实现的MVCMVC的结构就是下面的这个图。

 

 

  下面解释一下我写的代码:

   首先是,浏览器发出请求,login,根据web.xml文件配置,请求到达ControlServlet

ControlServlet解析请求路径,得到请求是login,然后根据mvc.pro(自己定义)的文件配置,

利用反射原理实例化相应的请求Action(本身是一个接口)类的对象,调用相应的方法,再

ActionForward(专门负责跳转页面的类)里,跳转页面。

下面是代码:

  三个包:web  webAction  webServlet

package web;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;/** * 连接数据库的代码 *  * @author txc *  */public class DBlink {	/**	 * 判断是是否登入成功的方法	 * 	 * @param userName	 * @param usePwd	 * @return	 * @throws SQLException	 */	public boolean userLogin(String userName, String usePwd)			throws SQLException {		// 这个是连接到数据库的方法		String sql = "select userPwd  from userinfo  where userName = '"				+ userName + "';";		ResultSet rs = linkDB().executeQuery(sql);		while (rs.next()) {			String pwd = rs.getString(1);			if (pwd.equals(usePwd)) {// 密码正确				return true;			}		}		return false;	}	/**	 * 判断是否注册成功的方法	 * 	 * @param userName	 * @param userPwd	 * @return	 * @throws SQLException	 */	public boolean userResgister(String userName, String userPwd)			throws SQLException {		// return true ;		int len = userName.length();		if (len > 20) {			return false;		}		String sql = "select userName from userinfo  where userName = '"				+ userName + "';";		ResultSet rs = linkDB().executeQuery(sql);		if (rs.next()) {// 如果存在的话,肯定不行的			// System.out.println("数据库查询了吗?");			// String name = rs.getString(1);			// System.out.println("数据库查询了吗?"+name);			return false;		} else {// 这个用户名没有被注册			sql = "insert into  userinfo(userName ,userPwd)values ('"					+ userName + "','" + userPwd + "');";			linkDB().executeUpdate(sql);			return true;		}	}	/*	 * 查询的方法	 */	public ResultSet inquire() throws SQLException {		String sql = "select * from userinfo ";		ResultSet rs = linkDB().executeQuery(sql);		return rs;	}	public void operation(int num) throws SQLException {		String sql = " delete from userinfo where id=" + num + ";";		linkDB().executeUpdate(sql);	}	/**	 * 	 * @param sql	 *            sql代码	 * @return 放回结果集对象	 */	private Statement linkDB() {		try {			// 装载对应数据库的驱动类			Class.forName("com.mysql.jdbc.Driver").newInstance();			// 数据库连接串			String dbURL = "jdbc:mysql://localhost:3306/wmszinfo";			// connection 代表程序与数据库的一个连接			Connection con = DriverManager.getConnection(dbURL, "root", "1929");			Statement state = con.createStatement(); // 用于执行sql语句的声明对象,执行后可以方法resultre对象			return state;		} catch (Exception g) {			g.printStackTrace();		}		return null;	}}webAction包package webAction;import java.sql.SQLException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import webServlet.ActionForward;public interface Action {		public ActionForward execute(HttpServletRequest request, HttpServletResponse response) ;	}这是loginAction类package webAction;import java.sql.SQLException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import web.DBlink;import webServlet.ActionForward;public class LoginAction implements Action {	@Override	public ActionForward execute(HttpServletRequest request,			HttpServletResponse response)  {		ActionForward af = null;		DBlink db = new DBlink();		String userName = request.getParameter("userName");		String userpwd = request.getParameter("userPwd");        try {			if(db.userLogin(userName, userpwd)){				//如果登入成功				request.getSession().setAttribute("current",userName);			} 			af = new ActionForward("index.jsp");//最终总是转到index页面		} catch (SQLException e) {			// TODO Auto-generated catch block			e.printStackTrace();		}		return af;	}}这是ControlSevlet类package webServlet;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.util.Properties;import java.util.StringTokenizer;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import webAction.Action;/** * Servlet implementation class ControlServlet */public class ControlServlet extends HttpServlet {	private static final long serialVersionUID = 1L;	Properties pro = new Properties();	/**	 * @see HttpServlet#HttpServlet()	 */	public ControlServlet() {		super();		// TODO Auto-generated constructor stub	}	public void service(HttpServletRequest request, HttpServletResponse response)			throws IOException, ServletException {           		String uri = request.getRequestURI();// 得到请求的路径		File file = new File(uri);		String filename = file.getName();// 只是为了得到login.Action		// 再去掉.Action		StringTokenizer st = new StringTokenizer(filename, ".");		String requestString = "";		if (st.hasMoreElements()) {			requestString = st.nextToken();// 现在是真正得到了login		}		//System.out.println();		// 根据 login得到相应的类		String classname = pro.get(requestString).toString();		try {			Action action = (Action) Class.forName(classname).newInstance();// 根据相应的请求创建相应的对象			// 调用相应的方法			ActionForward af = action.execute(request, response);// 若是登入则登入			// 跳转页面			af.forward(request, response);		} catch (InstantiationException e) {			// TODO Auto-generated catch block			e.printStackTrace();		} catch (IllegalAccessException e) {			// TODO Auto-generated catch block			e.printStackTrace();		} catch (ClassNotFoundException e) {			// TODO Auto-generated catch block			e.printStackTrace();		}	}	@Override 	public void init(){		String path = "/WEB-INF/mvc.pro";		// 我们仔细看一下这些路径是什么意思		 		try {			pro.load(new FileReader(new File(this.getServletContext().getRealPath(					path))));		} catch (FileNotFoundException e) {			// TODO Auto-generated catch block			e.printStackTrace();		} catch (IOException e) {			// TODO Auto-generated catch block			e.printStackTrace();		}	}}这是页面跳转的类package webServlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * 跳转页面的类 * @author txc * */public class ActionForward {	String path = "";//	这是构造方法 	public ActionForward(String path){		this.path = path;	}	public void forward(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{		//跳转页面		request.getRequestDispatcher(path).forward(request, response);	}}

 

mvc.pro是一个自定义配置文件

里面的内容,类似于键值对

如:

login=webAction.LoginActionregister=webAction.RegisterActionexit=webAction.ExitAction

 

另外它和web.xml放在相同的目录下面。这个文件的加载方法,在ControlServelt里面,即init方法。

 

<!--EndFragment--><!--EndFragment-->

转载地址:http://mllxb.baihongyu.com/

你可能感兴趣的文章
Flex HTTPService如何给后台传递参数
查看>>
Flex取得客户端的IP地址
查看>>
不vista下安装oracle10g(r2)注意事项
查看>>
文件列表输出到文件
查看>>
Ubuntu(804) SSH远程管理服务器安装配置
查看>>
android源码
查看>>
使用Hadoop的JAVA API远程访问HDFS
查看>>
Linux下任务调度服务crond使用
查看>>
ZeroMQ的订阅发布(publish-subscribe)模式
查看>>
使用redis存储全球IP库
查看>>
Snappy Java API简介
查看>>
C/C++中正则表达式库RE2的使用
查看>>
HBase Java API(1.2.X)使用简介
查看>>
Java:实现比较接口时,应该全面的进行各种情况的比较
查看>>
python3.*下用mob_pbxproj自动化修改配置
查看>>
使用fir打包,测试跳转安装的坑
查看>>
版本号大小判断,适用规则(X.X.X.X........)
查看>>
关于Objective-C方法签名规则的说明
查看>>
libxml2.dylb 添加后找不到<libxml/tree.h> 头文件
查看>>
关于 [[self class] alloc]的理解
查看>>